file_id
int64
1
215k
content
stringlengths
7
454k
repo
stringlengths
6
113
path
stringlengths
6
251
214,252
package com.magictool.web.configuration; import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.cache.RedisCacheConfiguration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.RedisSerializationContext; import org.springframework.data.redis.serializer.StringRedisSerializer; import java.time.Duration; /** * redis配置类 * * @author lijf */ @Configuration public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setEnableTransactionSupport(true); //key和value的序列化机制 redisTemplate.setKeySerializer(new StringRedisSerializer()); //设置HashKey的序列化机制 redisTemplate.setHashKeySerializer(new StringRedisSerializer()); //设置Value的序列化机制 redisTemplate.setValueSerializer(getJsonSerializer()); redisTemplate.setHashValueSerializer(getJsonSerializer()); //设置RedisConnectionFactory redisTemplate.setConnectionFactory(factory); return redisTemplate; } public Jackson2JsonRedisSerializer<Object> getJsonSerializer() { Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<Object>(Object.class); ObjectMapper om = new ObjectMapper(); //只针对非空的属性进行序列化 om.setSerializationInclusion(JsonInclude.Include.NON_NULL); //访问类型 om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); //将类的全名序列化到json字符串中 om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_ARRAY); //对于匹配不了的属性忽略报错信息 om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); //不包含任何属性的bean也不报错 om.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); serializer.setObjectMapper(om); return serializer; } @Bean public RedisCacheConfiguration redisCacheConfiguration() { RedisCacheConfiguration configuration = RedisCacheConfiguration.defaultCacheConfig(); return configuration.serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer())) .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(getJsonSerializer())) .entryTtl(Duration.ofMinutes(60)); } }
james-ljf/magic-tool
src/main/java/com/magictool/web/configuration/RedisConfig.java
214,253
package com.google.jstestdriver.idea.rt; import com.google.jstestdriver.Args4jFlagsParser; import com.google.jstestdriver.Flags; import com.google.jstestdriver.FlagsImpl; import com.google.jstestdriver.FlagsParser; import org.jetbrains.annotations.NotNull; import java.util.List; /** * @author Sergey Simonchik */ public class IntelliJFlagParser implements FlagsParser { private final JstdSettings mySettings; private final FlagsParser myOriginal; private final boolean myDryRun; public IntelliJFlagParser(@NotNull JstdSettings settings, boolean dryRun) { mySettings = settings; myDryRun = dryRun; myOriginal = new Args4jFlagsParser(); } @Override public Flags parseArgument(String[] strings) { Flags flags = myOriginal.parseArgument(strings); if (flags instanceof FlagsImpl) { fix((FlagsImpl) flags); } return flags; } private void fix(@NotNull FlagsImpl flags) { List<String> tests = mySettings.getTestFileScope().toJstdList(); if (myDryRun) { flags.setDryRunFor(tests); } else { flags.setTests(tests); } } }
JetBrains/intellij-obsolete-plugins
JsTestDriver/rt/src/main/java/com/google/jstestdriver/idea/rt/IntelliJFlagParser.java
214,254
/* * * * Copyright 2019 Werner Punz * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the Software * is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package net.werpu.tools.supportive.fs.common; import com.google.common.base.Strings; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.editor.Document; import com.intellij.openapi.module.Module; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.PsiManager; import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.impl.file.PsiDirectoryFactory; import lombok.Getter; import net.werpu.tools.indexes.AngularIndex; import net.werpu.tools.supportive.refactor.IRefactorUnit; import net.werpu.tools.supportive.reflectRefact.PsiWalkFunctions; import net.werpu.tools.supportive.utils.IntellijUtils; import net.werpu.tools.supportive.utils.StringUtils; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import static com.google.common.collect.Streams.concat; import static net.werpu.tools.supportive.fs.common.AngularVersion.NG; import static net.werpu.tools.supportive.fs.common.AngularVersion.TN_DEC; import static net.werpu.tools.supportive.reflectRefact.PsiWalkFunctions.*; import static net.werpu.tools.supportive.utils.IntellijUtils.getTsExtension; import static net.werpu.tools.supportive.utils.StringUtils.normalizePath; import static net.werpu.tools.supportive.utils.StringUtils.stripQuotes; /** * intellij deals with two levels of files * a) The virtual file * b) The Psi File parsing level * <p> * while this makes sense from a design point of view * often it is overly convoluted to juggle both levels * Hence we are going to introduce a context wich does most of the juggling */ @Getter public class IntellijFileContext { Project project; PsiFile psiFile; Module module; Document document; VirtualFile virtualFile; //workaround for shadow files and refactoring //TODO find out why refactoring does not work on virtual shadow files String shadowText; public IntellijFileContext(AnActionEvent event) { this(event.getProject(), getPossibleRootFolder(event)); } public IntellijFileContext(Project project) { this(project, getProjectFile(project)); } //todo inherently problematic because sometimes the psi file does not exist //and get psi file throws an error from intellij public IntellijFileContext(Project project, PsiFile psiFile) { this.project = project; this.psiFile = psiFile; this.virtualFile = psiFile.getVirtualFile(); this.document = PsiDocumentManager.getInstance(project).getDocument(psiFile); this.module = ProjectRootManager.getInstance(project).getFileIndex().getModuleForFile(virtualFile); postConstruct(); } public IntellijFileContext(Project project, VirtualFile virtualFile) { this.project = project; //NPE on find file here in some scenarii this.psiFile = PsiManager.getInstance(project).findFile(virtualFile); this.virtualFile = virtualFile; this.document = (psiFile != null) ? PsiDocumentManager.getInstance(project).getDocument(psiFile) : null; this.module = ProjectRootManager.getInstance(project).getFileIndex().getModuleForFile(virtualFile); postConstruct(); } public static VirtualFile getPossibleRootFolder(AnActionEvent event) { VirtualFile folderOrFile = IntellijUtils.getFolderOrFile(event); if (folderOrFile == null) { folderOrFile = event.getProject().getProjectFile(); } return folderOrFile; } public static VirtualFile getProjectFile(Project project) { VirtualFile projectFile = project.getProjectFile(); if (projectFile == null) { projectFile = project.getBaseDir(); } return projectFile; } protected void postConstruct() { } public String getText() { try { if (virtualFile.isDirectory()) { return ""; } if (psiFile != null && !Strings.isNullOrEmpty(psiFile.getText())) { return psiFile.getText(); } return new String(virtualFile.contentsToByteArray(), virtualFile.getCharset()); } catch (IOException e) { e.printStackTrace(); return ""; } } public void setText(String text) throws IOException { this.shadowText = text; virtualFile.setBinaryContent(text.getBytes(virtualFile.getCharset())); } public String getModuleRelativePath() { return virtualFile.getPath().replaceAll(module.getModuleFile().getParent().getPath(), "."); } public String calculateRelPathTo(IntellijFileContext root) { Path routesFilePath = Paths.get(root.getVirtualFile().isDirectory() ? root.getVirtualFile().getPath() : root.getVirtualFile().getParent().getPath()); Path componentFilePath = Paths.get(getVirtualFile().getPath()); Path relPath = routesFilePath.relativize(componentFilePath); return normalizePath("./" + relPath.toString()) .replaceAll("" + "//", "/"); } public IntellijFileContext getProjectDir() { return new IntellijFileContext(getProject(), getProject().getBaseDir()); } public List<PsiElement> findPsiElements(Function<PsiElement, Boolean> psiElementVisitor) { return findPsiElements(psiElementVisitor, false); } public Optional<PsiElement> findPsiElement(Function<PsiElement, Boolean> psiElementVisitor) { List<PsiElement> found = findPsiElements(psiElementVisitor, true); if (found.isEmpty()) { return Optional.empty(); } else { return Optional.ofNullable(found.get(0)); } } public void commit() throws IOException { PsiDocumentManager.getInstance(project).commitDocument(document); } public List<IntellijFileContext> getChildren(Function<VirtualFile, Boolean> fileVisitor) { return Arrays.stream(virtualFile.getChildren()) .filter(vFile -> fileVisitor.apply(vFile)) .map(vFile -> new IntellijFileContext(project, vFile)) .collect(Collectors.toList()); } public void reformat() { CodeStyleManager.getInstance(project).reformat(psiFile); } public void reformat(Function<PsiElement, Boolean> psiElementVisitor) { final CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(project); findPsiElements(psiElementVisitor).stream().forEach(el -> { codeStyleManager.reformat(el); }); } public Optional<IntellijFileContext> getParent() { VirtualFile parent = this.virtualFile.getParent(); if (parent == null) { return Optional.empty(); } else { if (!parent.getCanonicalPath().contains(project.getBaseDir().getCanonicalPath())) { return Optional.empty(); } return Optional.ofNullable(new IntellijFileContext(project, parent)); } } public boolean isBelow(IntellijFileContext child) { return child.getFolderPath().startsWith(this.getFolderPath()); } public List<IntellijFileContext> findFirstUpwards(Function<PsiFile, Boolean> psiElementVisitor) { if (psiFile != null && psiElementVisitor.apply(this.psiFile)) { return Arrays.asList(this); } List<IntellijFileContext> retVal = findInCurrentDir(psiElementVisitor); if (retVal.isEmpty()) { Optional<IntellijFileContext> parent = getParent(); if (!parent.isPresent()) { return Collections.emptyList(); } return parent.get().findFirstUpwards(psiElementVisitor); } return retVal; } public List<IntellijFileContext> findInCurrentDir(Function<PsiFile, Boolean> psiElementVisitor) { return this.getChildren(vFile -> { IntellijFileContext ctx = new IntellijFileContext(project, vFile); if (ctx.getPsiFile() != null) { return psiElementVisitor.apply(ctx.getPsiFile()); } else { return false; } }); } /** * goes an element tree upwards and finds all files/dirs triggered * by the visitor * * @param psiElementVisitor an element visitor which returns true once it has found everything * @param recurseOnceFound recurses deeper into the tree if set to true even if an element already is found * @return */ public List<IntellijFileContext> find(Function<PsiFile, Boolean> psiElementVisitor, boolean recurseOnceFound) { if (psiFile != null && psiElementVisitor.apply(this.psiFile)) { return Arrays.asList(this); } List<IntellijFileContext> retVal = findInCurrentDir(psiElementVisitor); if (!recurseOnceFound && !retVal.isEmpty()) { return retVal; } return getChildren(virtualFile1 -> { return virtualFile1.isDirectory() && !virtualFile1.getName().startsWith("."); }).stream().flatMap(intellijFileContext -> intellijFileContext.find(psiElementVisitor, recurseOnceFound).stream()) .collect(Collectors.toList()); } public void refactorContent(List<IRefactorUnit> refactorings) throws IOException { if (refactorings.isEmpty()) { return; } this.setText(calculateRefactoring(refactorings)); } public String calculateRefactoring(List<IRefactorUnit> refactorings) { if (refactorings.isEmpty()) { return refactorings.get(0).getFile().getText(); } //all refactorings must be of the same vFile TODO add check here String toSplit = refactorings.get(0).getFile().getText(); return StringUtils.refactor(refactorings, toSplit); } public String calculateRefactoring(List<IRefactorUnit> refactorings, PsiElementContext rootElement) { if (refactorings.isEmpty()) { return rootElement.getText(); } return StringUtils.refactor(refactorings, rootElement.getElement()); } protected List<PsiElement> findPsiElements(Function<PsiElement, Boolean> psiElementVisitor, boolean firstOnly) { if (psiFile == null) {//not parseable return Collections.emptyList(); } return walkPsiTree(psiFile, psiElementVisitor, firstOnly); } public boolean isPsiFile() { return psiFile != null; } public String getFolderPath() { if (virtualFile == null || virtualFile.getParent() == null) { return "____NaN____"; } return virtualFile.isDirectory() ? virtualFile.getPath() : virtualFile.getParent().getPath(); } public IRefactorUnit refactorIn(Function<PsiFile, IRefactorUnit> refactorHandler) { return refactorHandler.apply(this.psiFile); } public void copy(IntellijFileContext newDir) throws IOException { if (!newDir.getVirtualFile().isDirectory()) { throw new IOException("Target is not a dir"); } if (!this.isPsiFile()) { throw new IOException("Source is not a dir"); } PsiDirectoryFactory.getInstance(project).createDirectory(newDir.getVirtualFile()).add(this.psiFile); } /** * dectecs thr angular version with a package.json in its root * * @return */ public Optional<AngularVersion> getAngularVersion() { if (AngularIndex.isBelowAngularVersion(this, NG)) { return Optional.of(NG); } else if (AngularIndex.isBelowAngularVersion(this, TN_DEC)) { return Optional.of(TN_DEC); } return Optional.empty(); } public boolean isAngularChild(AngularVersion angularVersion) { return AngularIndex.isBelowAngularVersion(this, angularVersion); } public boolean isAngularChild() { return AngularIndex.isBelowAngularVersion(this, AngularVersion.NG) || AngularIndex.isBelowAngularVersion(this, AngularVersion.TN_DEC); } public Optional<IntellijFileContext> getAngularRoot() { Optional<IntellijFileContext> fileContext = findFirstUpwards(psiFile -> psiFile.getVirtualFile().getName().equals(NPM_ROOT)).stream().findFirst(); Optional<IntellijFileContext> fileContext2 = findFirstUpwards(psiFile -> psiFile.getVirtualFile().getName().equals(NG_PRJ_MARKER)).stream().findFirst(); Optional<IntellijFileContext> fileContext3 = findFirstUpwards(psiFile -> psiFile.getVirtualFile().getName().equals(TN_DEC_PRJ_MARKER)).stream().findFirst(); return Optional.ofNullable(fileContext.orElse(fileContext2.orElse(fileContext3.orElse(null)))); } public boolean isChildOf(IntellijFileContext ctx) { Path child = Paths.get(getVirtualFile().isDirectory() ? this.getVirtualFile().getPath() : this.getVirtualFile().getParent().getPath()); Path parent = Paths.get(ctx.getVirtualFile().isDirectory() ? ctx.getVirtualFile().getPath() : ctx.getVirtualFile().getParent().getPath()); return child.startsWith(parent); } public Stream<PsiElementContext> queryContent(Object... items) { return PsiWalkFunctions.queryContent(this.getPsiFile(), items); } public Stream<PsiElementContext> $q(Object... items) { return PsiWalkFunctions.queryContent(this.getPsiFile(), items); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || !(o instanceof IntellijFileContext)) return false; IntellijFileContext that = (IntellijFileContext) o; Path pThis = Paths.get(this.getVirtualFile().getPath()); Path pOther = Paths.get(that.getVirtualFile().getPath()); try { return pThis.relativize(pOther).toString().isEmpty(); } catch (IllegalArgumentException ex) { //different root no chance in hell that this equals out return false; } } public IntellijFileContext relative(PsiElement importStr) { return new IntellijFileContext(getProject(), getVirtualFile().getParent().findFileByRelativePath(stripQuotes(importStr.getText()) + getTsExtension())); } public Optional<NgModuleFileContext> getNearestModule() { IntellijFileContext project = new IntellijFileContext(this.getProject()); ContextFactory ctxf = ContextFactory.getInstance(project); String filterStr = StringUtils.normalizePath(this.getFolderPath()); return concat( ctxf.getModulesFor(project, TN_DEC, filterStr).stream(), ctxf.getModulesFor(project, NG, filterStr).stream() ).reduce((el1, el2) -> { String folderPathFile = el1.getFolderPath(); String folderPathModule = el2.getFolderPath(); return folderPathFile.length() > folderPathModule.length() ? el1 : el2; }); } public boolean isSourceFile() { return ProjectFileIndex.getInstance(project).getSourceRootForFile(virtualFile) != null; } /*public boolean isWebFile() { return WebUtil.isInsideWebRoots(virtualFile, project); }*/ public boolean isBuildTarget() { ProjectFileIndex projectFileIndex = ProjectFileIndex.getInstance(project); return projectFileIndex.isExcluded(virtualFile) || projectFileIndex.isUnderIgnored(virtualFile); } /** * Base file information * get the base file name aka my.foo -> returns my * * @return */ public String getBaseName() { String fileName = getFileName(); int endIndex = fileName.lastIndexOf("."); if (endIndex == -1) { return fileName; } String rawName = fileName.substring(0, endIndex); return rawName; } /** * returns the raw filename * * @return */ @NotNull public String getFileName() { return this.getVirtualFile().getName(); } /** * returns only the ending * * @return */ public String getFileEnding() { String fileName = getFileName(); return fileName.substring(fileName.lastIndexOf(".") + 1); } }
werpu/tinydecscodegen
codegen_plugin/src/main/java/net/werpu/tools/supportive/fs/common/IntellijFileContext.java
214,256
package jezzsantos.automate.plugin.infrastructure.ui; import com.intellij.openapi.fileEditor.FileEditorManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.LocalFileSystem; import com.jetbrains.rd.util.UsedImplicitly; import jezzsantos.automate.plugin.application.services.interfaces.IFileEditor; import org.jetbrains.annotations.NotNull; import java.io.File; public class IntelliJFileEditor implements IFileEditor { private final Project project; @UsedImplicitly public IntelliJFileEditor(@NotNull Project project) { this.project = project; } @Override public boolean openFile(@NotNull String path) { var file = new File(path); if (!file.exists()) { return false; } var virtualFile = LocalFileSystem.getInstance().findFileByIoFile(file); if (virtualFile == null) { return false; } var editor = FileEditorManager.getInstance(this.project) .openFile(virtualFile, true); return editor.length > 0; } }
jezzsantos/automate.plugin-rider
src/main/java/jezzsantos/automate/plugin/infrastructure/ui/IntelliJFileEditor.java
214,257
/* * SPDX-FileCopyrightText: 2022 Atos * SPDX-License-Identifier: EUPL-1.2+ */ package net.atos.zac.app.klanten.converter; import static net.atos.zac.app.klanten.model.personen.RESTPersonenParameters.Cardinaliteit.NON; import static net.atos.zac.app.klanten.model.personen.RESTPersonenParameters.Cardinaliteit.OPT; import static net.atos.zac.app.klanten.model.personen.RESTPersonenParameters.Cardinaliteit.REQ; import static net.atos.zac.util.StringUtil.NON_BREAKING_SPACE; import static net.atos.zac.util.StringUtil.ONBEKEND; import static net.atos.zac.util.StringUtil.joinNonBlankWith; import static org.apache.commons.lang3.StringUtils.SPACE; import static org.apache.commons.lang3.StringUtils.isNotBlank; import static org.apache.commons.lang3.StringUtils.replace; import java.util.Collections; import java.util.List; import java.util.Objects; import net.atos.client.brp.model.AbstractDatum; import net.atos.client.brp.model.AbstractVerblijfplaats; import net.atos.client.brp.model.Adres; import net.atos.client.brp.model.AdresseringBeperkt; import net.atos.client.brp.model.DatumOnbekend; import net.atos.client.brp.model.JaarDatum; import net.atos.client.brp.model.JaarMaandDatum; import net.atos.client.brp.model.PersonenQuery; import net.atos.client.brp.model.PersonenQueryResponse; import net.atos.client.brp.model.Persoon; import net.atos.client.brp.model.PersoonBeperkt; import net.atos.client.brp.model.RaadpleegMetBurgerservicenummer; import net.atos.client.brp.model.RaadpleegMetBurgerservicenummerResponse; import net.atos.client.brp.model.VerblijfadresBinnenland; import net.atos.client.brp.model.VerblijfadresBuitenland; import net.atos.client.brp.model.VerblijfplaatsBuitenland; import net.atos.client.brp.model.VerblijfplaatsOnbekend; import net.atos.client.brp.model.VolledigeDatum; import net.atos.client.brp.model.Waardetabel; import net.atos.client.brp.model.ZoekMetGeslachtsnaamEnGeboortedatum; import net.atos.client.brp.model.ZoekMetGeslachtsnaamEnGeboortedatumResponse; import net.atos.client.brp.model.ZoekMetNaamEnGemeenteVanInschrijving; import net.atos.client.brp.model.ZoekMetNaamEnGemeenteVanInschrijvingResponse; import net.atos.client.brp.model.ZoekMetNummeraanduidingIdentificatieResponse; import net.atos.client.brp.model.ZoekMetPostcodeEnHuisnummer; import net.atos.client.brp.model.ZoekMetPostcodeEnHuisnummerResponse; import net.atos.client.brp.model.ZoekMetStraatHuisnummerEnGemeenteVanInschrijving; import net.atos.client.brp.model.ZoekMetStraatHuisnummerEnGemeenteVanInschrijvingResponse; import net.atos.zac.app.klanten.model.personen.RESTListPersonenParameters; import net.atos.zac.app.klanten.model.personen.RESTPersonenParameters; import net.atos.zac.app.klanten.model.personen.RESTPersoon; public class RESTPersoonConverter { // Moet overeenkomen met wat er in convertToPersonenQuery gebeurt. public static final List<RESTPersonenParameters> VALID_PERSONEN_QUERIES = List.of( new RESTPersonenParameters(REQ, NON, NON, NON, NON, NON, NON, NON, NON), new RESTPersonenParameters(NON, REQ, OPT, OPT, REQ, NON, NON, NON, NON), new RESTPersonenParameters(NON, REQ, REQ, OPT, NON, REQ, NON, NON, NON), new RESTPersonenParameters(NON, NON, NON, NON, NON, NON, REQ, REQ, NON), new RESTPersonenParameters(NON, NON, NON, NON, NON, REQ, NON, REQ, REQ) ); public List<RESTPersoon> convertPersonen(final List<Persoon> personen) { return personen.stream().map(this::convertPersoon).toList(); } public List<RESTPersoon> convertPersonenBeperkt(final List<PersoonBeperkt> personen) { return personen.stream().map(this::convertPersoonBeperkt).toList(); } public RESTPersoon convertPersoon(final Persoon persoon) { final RESTPersoon restPersoon = new RESTPersoon(); restPersoon.bsn = persoon.getBurgerservicenummer(); if (persoon.getGeslacht() != null) { restPersoon.geslacht = convertGeslacht(persoon.getGeslacht()); } if (persoon.getNaam() != null) { restPersoon.naam = persoon.getNaam().getVolledigeNaam(); } if (persoon.getGeboorte() != null) { restPersoon.geboortedatum = convertGeboortedatum(persoon.getGeboorte().getDatum()); } if (persoon.getVerblijfplaats() != null) { restPersoon.verblijfplaats = convertVerblijfplaats(persoon.getVerblijfplaats()); } return restPersoon; } public RESTPersoon convertPersoonBeperkt(final PersoonBeperkt persoon) { final RESTPersoon restPersoon = new RESTPersoon(); restPersoon.bsn = persoon.getBurgerservicenummer(); if (persoon.getGeslacht() != null) { restPersoon.geslacht = convertGeslacht(persoon.getGeslacht()); } if (persoon.getNaam() != null) { restPersoon.naam = persoon.getNaam().getVolledigeNaam(); } if (persoon.getGeboorte() != null) { restPersoon.geboortedatum = convertGeboortedatum(persoon.getGeboorte().getDatum()); } if (persoon.getAdressering() != null) { final AdresseringBeperkt adressering = persoon.getAdressering(); restPersoon.verblijfplaats = joinNonBlankWith(", ", adressering.getAdresregel1(), adressering.getAdresregel2(), adressering.getAdresregel3()); } return restPersoon; } public PersonenQuery convertToPersonenQuery(final RESTListPersonenParameters parameters) { if (isNotBlank(parameters.bsn)) { final var query = new RaadpleegMetBurgerservicenummer(); query.addBurgerservicenummerItem(parameters.bsn); return query; } if (isNotBlank(parameters.geslachtsnaam) && parameters.geboortedatum != null) { final var query = new ZoekMetGeslachtsnaamEnGeboortedatum(); query.setGeslachtsnaam(parameters.geslachtsnaam); query.setGeboortedatum(parameters.geboortedatum); query.setVoornamen(parameters.voornamen); query.setVoorvoegsel(parameters.voorvoegsel); return query; } if (isNotBlank(parameters.geslachtsnaam) && isNotBlank(parameters.voornamen) && isNotBlank(parameters.gemeenteVanInschrijving)) { final var query = new ZoekMetNaamEnGemeenteVanInschrijving(); query.setGeslachtsnaam(parameters.geslachtsnaam); query.setVoornamen(parameters.voornamen); query.setGemeenteVanInschrijving(parameters.gemeenteVanInschrijving); query.setVoorvoegsel(parameters.voorvoegsel); return query; } if (isNotBlank(parameters.postcode) && parameters.huisnummer != null) { final var query = new ZoekMetPostcodeEnHuisnummer(); query.setPostcode(parameters.postcode); query.setHuisnummer(parameters.huisnummer); return query; } if (isNotBlank(parameters.straat) && parameters.huisnummer != null && isNotBlank(parameters.gemeenteVanInschrijving)) { final var query = new ZoekMetStraatHuisnummerEnGemeenteVanInschrijving(); query.setStraat(parameters.straat); query.setHuisnummer(parameters.huisnummer); query.setGemeenteVanInschrijving(parameters.gemeenteVanInschrijving); return query; } throw new IllegalArgumentException("Ongeldige combinatie van zoek parameters"); } public List<RESTPersoon> convertFromPersonenQueryResponse(final PersonenQueryResponse personenQueryResponse) { return switch (personenQueryResponse) { case RaadpleegMetBurgerservicenummerResponse response -> convertPersonen(response.getPersonen()); case ZoekMetGeslachtsnaamEnGeboortedatumResponse response -> convertPersonenBeperkt(response.getPersonen()); case ZoekMetNaamEnGemeenteVanInschrijvingResponse response -> convertPersonenBeperkt(response.getPersonen()); case ZoekMetNummeraanduidingIdentificatieResponse response -> convertPersonenBeperkt(response.getPersonen()); case ZoekMetPostcodeEnHuisnummerResponse response -> convertPersonenBeperkt(response.getPersonen()); case ZoekMetStraatHuisnummerEnGemeenteVanInschrijvingResponse response -> convertPersonenBeperkt(response.getPersonen()); default -> Collections.emptyList(); }; } private String convertGeslacht(final Waardetabel geslacht) { return isNotBlank(geslacht.getOmschrijving()) ? geslacht.getOmschrijving() : geslacht.getCode(); } private String convertGeboortedatum(final AbstractDatum abstractDatum) { return switch (abstractDatum) { case VolledigeDatum volledigeDatum -> volledigeDatum.getDatum().toString(); case JaarMaandDatum jaarMaandDatum -> "%d2-%d4".formatted(jaarMaandDatum.getMaand(), jaarMaandDatum.getJaar()); case JaarDatum jaarDatum -> "%d4".formatted(jaarDatum.getJaar()); case DatumOnbekend datumOnbekend -> ONBEKEND; default -> null; }; } private String convertVerblijfplaats(final AbstractVerblijfplaats abstractVerblijfplaats) { return switch (abstractVerblijfplaats) { case Adres adres && adres.getVerblijfadres() != null -> convertVerblijfadresBinnenland(adres.getVerblijfadres()); case VerblijfplaatsBuitenland verblijfplaatsBuitenland && verblijfplaatsBuitenland.getVerblijfadres() != null -> convertVerblijfadresBuitenland(verblijfplaatsBuitenland.getVerblijfadres()); case VerblijfplaatsOnbekend verblijfplaatsOnbekend -> ONBEKEND; default -> null; }; } private String convertVerblijfadresBinnenland(final VerblijfadresBinnenland verblijfadresBinnenland) { final String adres = replace(joinNonBlankWith(NON_BREAKING_SPACE, verblijfadresBinnenland.getOfficieleStraatnaam(), Objects.toString(verblijfadresBinnenland.getHuisnummer(), null), verblijfadresBinnenland.getHuisnummertoevoeging(), verblijfadresBinnenland.getHuisletter()), SPACE, NON_BREAKING_SPACE); final String postcode = replace(verblijfadresBinnenland.getPostcode(), SPACE, NON_BREAKING_SPACE); final String woonplaats = replace(verblijfadresBinnenland.getWoonplaats(), SPACE, NON_BREAKING_SPACE); return joinNonBlankWith(", ", adres, postcode, woonplaats); } private String convertVerblijfadresBuitenland(VerblijfadresBuitenland verblijfadresBuitenland) { return joinNonBlankWith(", ", verblijfadresBuitenland.getRegel1(), verblijfadresBuitenland.getRegel2(), verblijfadresBuitenland.getRegel3()); } }
NL-AMS-LOCGOV/zaakafhandelcomponent
src/main/java/net/atos/zac/app/klanten/converter/RESTPersoonConverter.java
214,258
package com.xkj.mlrc.fsimage; import com.jcraft.jsch.*; import com.xkj.mlrc.clean.util.PropsUtil; import com.xkj.mlrc.common.shell.Shell; import lombok.extern.slf4j.Slf4j; import java.io.File; import java.io.IOException; import java.util.ArrayList; /** * 远程ssh解析fsimage文件 * * @author [email protected] * @date 2020/4/23 12:38 * @desc */ @Slf4j public class GenerateFsimageTable { public static Shell shell; public static void main(String[] args) throws IOException, JSchException { // ssh远程登录NameNode所在的机器 sshLoginNameNodeHost(); // 解析fsimage文件并上传到hive表对应的路径 generateFsimageCsv2Hive(); } private static void generateFsimageCsv2Hive() throws IOException, JSchException { //获取存放fsimage文件的目录 String cmd1 = "hdfs getconf -confKey dfs.namenode.name.dir"; shell.execute(cmd1); ArrayList<String> list1 = shell.getStandardOutput(); String fsimageDir = list1.get(list1.size() - 1).split(",")[0]; //获取最新的fsimage文件的路径 String cmd2 = "find ${fsimageDir}/current -type f -name 'fsimage_*' | grep -v '.md5' | sort -n | tail -n1"; shell.execute(cmd2.replace("${fsimageDir}", fsimageDir)); ArrayList<String> list2 = shell.getStandardOutput(); String fsimageFile = list2.get(list2.size() - 1); //拷贝fsimage文件到ssh登录的HOME目录,并加上时间戳后缀 String userHomeDir = "/home/" + shell.username; long timestamp = System.currentTimeMillis(); String fsimageFileName = new File(fsimageFile).getName() + "_" + timestamp; String cmd3 = "cp ${fsimageFile} ${userhome}/${fsimageFileName}"; cmd3 = cmd3.replace("${fsimageFile}", fsimageFile).replace("${userhome}", userHomeDir).replace("${fsimageFileName}", fsimageFileName); shell.execute(cmd3); //解析fsimage成csv文件 String cmd4 = "hdfs oiv -p Delimited -delimiter ',' -i ${userhome}/${fsimageFileName} -o ${userhome}/fsimage.csv"; cmd4 = cmd4.replace("${userhome}", userHomeDir).replace("${fsimageFileName}", fsimageFileName); shell.execute(cmd4); // 创建fsimage表 String cmd5 = "hive -S -e \"CREATE TABLE IF NOT EXISTS fsimage( " + "path string, " + "replication int, " + "modificationtime string, " + "accesstime string, " + "preferredblocksize bigint, " + "blockscount int, " + "filesize bigint, " + "nsquota int, " + "dsquota int, " + "permission string, " + "username string, " + "groupname string) " + "ROW FORMAT DELIMITED " + "FIELDS TERMINATED BY ',' " + "STORED AS INPUTFORMAT " + "'org.apache.hadoop.mapred.TextInputFormat' " + "OUTPUTFORMAT " + "'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat' " + "location '/tmp/fsimage'\""; shell.execute(cmd5); // 上传fsimage.csv文件到hive表,为后面统计分析做准备 String cmd6 = "hadoop fs -put -f ${userhome}/fsimage.csv /tmp/fsimage/"; cmd6 = cmd6.replace("${userhome}", userHomeDir); shell.execute(cmd6); // 删除无用的数据 String cmd7 = "rm -rf ${userhome}/fsimage*"; cmd7 = cmd7.replace("${userhome}", userHomeDir); shell.execute(cmd7); } /** * ssh登录namenode host */ private static void sshLoginNameNodeHost() throws IOException, JSchException { String host = PropsUtil.getProp("ssh.namenode.host"); String user = PropsUtil.getProp("ssh.namenode.user"); String password = PropsUtil.getProp("ssh.namenode.password"); shell = new Shell(host, user, password); int code = shell.execute("ls"); System.out.println(code); if (code == 0) { log.info("用户:{} 登录host:{}成功!!", user, host); } else { log.error("用户:{} 登录host:{}失败!!", user, host); System.exit(-1); } } }
lijufeng2016/data-manager
src/main/java/com/xkj/mlrc/fsimage/GenerateFsimageTable.java
214,259
package com.xkj.mlrc.fsimage; import com.xkj.mlrc.clean.util.DateUtil; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Data; import lombok.NoArgsConstructor; import org.apache.hadoop.fs.Path; import org.apache.spark.api.java.function.FilterFunction; import org.apache.spark.sql.Dataset; import org.apache.spark.sql.Row; import org.apache.spark.sql.SparkSession; import java.io.Serializable; /** * @author [email protected] * @date 2020/4/22 14:18 * @desc 获取fsimage信息表 */ @Data @AllArgsConstructor @NoArgsConstructor @Builder() public class GetFromFsImageInfo implements Serializable { private SparkSession spark; // 目标路径,要删除的路径,包含所有子路径 private String targetPath; // 要避开扫描的路径,包含所有子路径 private String avoidPath; // 要过滤的带有前缀的文件 private String avoidSuffix; // 要过滤的带有后缀的文件 private String avoidPrefix; // 过滤多少天之前未读的数据 private Integer expire; // hdfs根路径 private String hdfsroot; /** * 获取要删除的所有文件 * * @return Dataset<Row> * @throws NullPointerException 空指针异常 */ public Dataset<Row> getAllFiles() throws NullPointerException { if (expire == null || expire == 0) { throw new NullPointerException("expire必须大于0!!"); } // 获取过期数据的日期 String nDayFmtDAte = DateUtil.getNDayFmtDAte("yyyy-MM-dd HH:mm", 0 - expire); // 获取要删的文件 String sqlText = "select * from fsimage where replication>0 and accesstime<'" + nDayFmtDAte + "'"; Dataset<Row> fsImage = spark.sql(sqlText); // 以下根据传入的各个参数过滤数据 if (null != targetPath) { fsImage = fsImage.filter(new FilterFunction<Row>() { @Override public boolean call(Row row) throws Exception { String[] targetPaths = targetPath.split(","); boolean contains = false; for (int i = 0; i < targetPaths.length; i++) { String path = targetPaths[i]; String fileAbsPath = row.getAs("path").toString(); if (fileAbsPath.startsWith(path)) { contains = true; } } return contains; } }); } if (null != avoidPath) { String[] avoidPaths = avoidPath.split(","); for (int i = 0; i < avoidPaths.length; i++) { String path = avoidPaths[i]; fsImage = fsImage.filter(new FilterFunction<Row>() { @Override public boolean call(Row row) throws Exception { String fileAbsPath = row.getAs("path").toString(); return !fileAbsPath.startsWith(path); } }); } } if (null != avoidSuffix) { String[] avoidSuffixs = avoidSuffix.split(","); for (int i = 0; i < avoidSuffixs.length; i++) { String suffix = avoidSuffixs[i]; fsImage = fsImage.filter(new FilterFunction<Row>() { @Override public boolean call(Row row) throws Exception { String path = row.getAs("path").toString(); return !path.endsWith(suffix); } }); } } if (null != avoidPrefix) { String[] avoidPrefixs = avoidPrefix.split(","); for (int i = 0; i < avoidPrefixs.length; i++) { String prefix = avoidPrefixs[i]; fsImage = fsImage.filter(new FilterFunction<Row>() { @Override public boolean call(Row row) throws Exception { String pathName = row.getAs("path").toString(); String fileName = new Path(pathName).getName(); return !fileName.startsWith(prefix); } }); } } return fsImage; } /** * 获取所有文件的目录 * * @return Dataset<Row> */ public Dataset<Row> getAllFilesDir() { Dataset<Row> allFiles = getAllFiles(); Dataset<Row> fsimage = allFiles.selectExpr("*", "SUBSTRING_INDEX(path,'/',size(split(path,'/'))-1) as dir"); return fsimage; } /** * 根据目录下的访问时间最大的文件决定目录是否删除 * * @return Dataset<Row> */ public Dataset<Row> getAllShouldDelDirsByLastAccesstime() { getAllFilesDir().createOrReplaceTempView("fsimage_dirs"); String sqlText = "select * from " + " (" + " select *," + " row_number() over (partition by dir order by accesstime desc) rank " + " from fsimage_dirs" + " ) tmp where rank=1"; Dataset<Row> fsimage = spark.sql(sqlText).selectExpr("*", "concat('" + hdfsroot + "',dir) as hdfs_abs_path"); return fsimage; } }
lijufeng2016/data-manager
src/main/java/com/xkj/mlrc/fsimage/GetFromFsImageInfo.java
214,262
package nl.topicus.eduarte.web.components.modalwindow.verblijfsvergunning; import nl.topicus.cobra.util.ComponentUtil; import nl.topicus.cobra.web.components.modal.CobraModalWindowBasePanel; import nl.topicus.eduarte.entities.landelijk.Verblijfsvergunning; import nl.topicus.eduarte.web.components.modalwindow.AbstractZoekenModalWindow; import nl.topicus.eduarte.zoekfilters.LandelijkCodeNaamZoekFilter; import org.apache.wicket.model.IModel; public class VerblijfsvergunningSelectieModalWindow extends AbstractZoekenModalWindow<Verblijfsvergunning> { private static final long serialVersionUID = 1L; private LandelijkCodeNaamZoekFilter<Verblijfsvergunning> filter; public VerblijfsvergunningSelectieModalWindow(String id, IModel<Verblijfsvergunning> model, LandelijkCodeNaamZoekFilter<Verblijfsvergunning> filter) { super(id, model, filter); this.filter = filter; setTitle("Verblijfsvergunning selecteren"); } @Override protected CobraModalWindowBasePanel<Verblijfsvergunning> createContents(String id) { return new VerblijfsvergunningSelectiePanel(id, this, filter); } @Override protected void onDetach() { super.onDetach(); ComponentUtil.detachQuietly(filter); } }
topicusonderwijs/tribe-krd-opensource
eduarte/core/src/main/java/nl/topicus/eduarte/web/components/modalwindow/verblijfsvergunning/VerblijfsvergunningSelectieModalWindow.java
214,263
package com.xkj.mlrc.clean.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; /** * @author: [email protected] * @Date: 2018/7/5 13:47 * @Version: 1.0 */ public class DateUtil { private DateUtil() { } public static final String DATE_FORMAT_MEDIUM = "yyyy-MM-dd"; public static final String DATE_FORMAT_LONG= "yyyy-MM-dd HH:mm:ss"; private static Logger logger = LoggerFactory.getLogger(DateUtil.class); /** * 判断时间是否在时间段内 * * @param nowTime * @param beginTime * @param endTime * @return */ public static boolean belongCalendar(Date nowTime, Date beginTime, Date endTime) { Calendar date = Calendar.getInstance(); date.setTime(nowTime); Calendar begin = Calendar.getInstance(); begin.setTime(beginTime); Calendar end = Calendar.getInstance(); end.setTime(endTime); return (date.after(begin) && date.before(end)); } /** * 格式化日期 * @param fmt 格式 * @return */ public static String getCurrentFormatDate(String fmt) { String formatDate = ""; try { SimpleDateFormat format = new SimpleDateFormat(fmt); Date date = new Date(); formatDate = format.format(date); }catch (Exception e){ logger.error(e.toString(),e); } return formatDate; } /** * 获取N天前后的凌晨零点 yyyy-MM-dd HH:mm:ss * @param n * @return */ public static String getNDayBeforeOrAfterZeroMorning(int n) { Calendar instance = Calendar.getInstance(); SimpleDateFormat sdfCn = new SimpleDateFormat(DATE_FORMAT_MEDIUM); instance.add(Calendar.DAY_OF_MONTH, n); Date parse = instance.getTime(); String nDayBefore = sdfCn.format(parse); return nDayBefore+" 00:00:00"; } /** * 获取前一天时间字符串,返回例子:2018-07-30 */ public static final String getYesterDay(){ Date date=new Date(); Calendar calendar = new GregorianCalendar(); calendar.setTime(date); calendar.add(Calendar.DATE,-1); date=calendar.getTime(); SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT_MEDIUM); return formatter.format(date); } /** * 转换成Timestamp * @param formatDt * @return */ public static long parseToTimestamp(String format,String formatDt) { SimpleDateFormat formatDate = new SimpleDateFormat(format); Date date = null; try { date = formatDate.parse(formatDt); return date.getTime() / 1000; } catch (ParseException e) { logger.error(e.toString(),e); } return 0; } /** * 获取n天前的日期 * @param format 格式 * @param n 天数 * @return * @throws ParseException */ public static String getNDayFmtDAte(String format,int n) { Calendar instance = Calendar.getInstance(); SimpleDateFormat sdfCn = new SimpleDateFormat(format); instance.add(Calendar.DAY_OF_MONTH, n); Date parse = instance.getTime(); return sdfCn.format(parse); } /** * 根据day获取n天前的日期 * @param format 格式 * @param n 天数 * @return * @throws ParseException */ public static String getNDayFmtByDay(String format,String day,int n) { Calendar instance = Calendar.getInstance(); SimpleDateFormat sdfCn = new SimpleDateFormat(format); try { Date date = sdfCn.parse(day); instance.setTime(date); } catch (ParseException e) { e.printStackTrace(); } instance.add(Calendar.DAY_OF_MONTH, n); Date parse = instance.getTime(); return sdfCn.format(parse); } /** * 获取前天的日期 */ public static final String getBeforeYe(){ Date date=new Date(); Calendar calendar = new GregorianCalendar(); calendar.setTime(date); calendar.add(Calendar.DATE,-2); date=calendar.getTime(); SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT_MEDIUM); return formatter.format(date); } /** * 获取前N天的日期(不包含今天) */ public static List<String> getNday(Integer num){ if(num==null||num<=0){ return new ArrayList<>(); } SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT_MEDIUM); List<String> li = new ArrayList<>(); Date date=new Date(); Calendar calendar = new GregorianCalendar(); for(int i=num;i>=1;i--){ calendar.setTime(date); calendar.add(Calendar.DATE,-i); li.add(formatter.format(calendar.getTime())); } return li; } /** * 格式化日期转为Date * @param fmtDate yyyy-MM-dd HH:mm:ss * @return date */ public static Date parse2Date(String fmtDate){ Date date; SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_LONG); try { date = sdf.parse(fmtDate); } catch (ParseException e) { date = new Date(); } return date; } /** * 获取当天还剩余的时间,单位:S * @return ... */ public static int getLeftSecondsToday(){ SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT_LONG); String nowStr = dateFormat.format(new Date()); String patten = " "; String endStr = nowStr.substring(0,nowStr.indexOf(patten)) + " 23:59:59"; int leftSeconds = 0; try { leftSeconds = Integer.valueOf((dateFormat.parse(endStr).getTime() - dateFormat.parse(nowStr).getTime()) / 1000+""); } catch (ParseException e) { logger.error(e.toString(),e); } return leftSeconds; } /** * 时间戳转换为格式化时间戳 * @param timestamp * @return */ public static String parseToFmtDateStr(Integer timestamp){ SimpleDateFormat fmt = new SimpleDateFormat(DATE_FORMAT_LONG); return fmt.format(new Date(timestamp * 1000L)); } /** * 根据两个日期获取两日期之间的日期 * @param beginDay 格式为2019-05-08 * @param endDay 格式为2019-05-09 * @return */ public static List<String> getDays(String beginDay,String endDay){ // 返回的日期集合 List<String> days = new ArrayList<>(); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); try { Date start = dateFormat.parse(beginDay); Date end = dateFormat.parse(endDay); Calendar tempStart = Calendar.getInstance(); tempStart.setTime(start); Calendar tempEnd = Calendar.getInstance(); tempEnd.setTime(end); tempEnd.add(Calendar.DATE, +1); while (tempStart.before(tempEnd)) { days.add(dateFormat.format(tempStart.getTime())); tempStart.add(Calendar.DAY_OF_YEAR, 1); } } catch (ParseException e) { e.printStackTrace(); } return days; } /** * 时间戳转换为格式化时间戳 * @param timestamp * @return */ public static String parseTimestamp2FmtDateStr(String format,Long timestamp){ SimpleDateFormat fmt = new SimpleDateFormat(format); return fmt.format(new Date(timestamp * 1000L)); } /** * 判断时间是否在时间段内 * 传入24小时制格式,如01 03 表示凌晨1点与3点,15表示下午3点。 * 04 到 19 表示凌晨4点到今天的下午7点 * 19 到 09 表示晚上7点到第二天上午9点 * * @param now ... * @param beginHour ... * @param endHour ... * @return ... */ public static boolean judgeTimeBetween(Date now, String beginHour, String endHour) { int iBeginHour = Integer.valueOf(beginHour); int iEndHour = Integer.valueOf(endHour); if (iBeginHour == iEndHour) { return true; } Calendar date = Calendar.getInstance(); date.set(Calendar.HOUR_OF_DAY, iBeginHour); date.set(Calendar.MINUTE, 0); date.set(Calendar.SECOND, 0); Date beginTime = date.getTime(); if (iEndHour == 0) { date.set(Calendar.HOUR_OF_DAY, 23); date.set(Calendar.MINUTE, 59); date.set(Calendar.SECOND, 59); Date endTime = date.getTime(); if (now.after(beginTime) && now.before(endTime)) { return true; } } if (iBeginHour < iEndHour) { date.set(Calendar.HOUR_OF_DAY, iEndHour); date.set(Calendar.MINUTE, 0); date.set(Calendar.SECOND, 0); Date endTime = date.getTime(); if (now.after(beginTime) && now.before(endTime)) { return true; } } else { date.setTime(now); int nowHour = date.get(Calendar.HOUR_OF_DAY); if (nowHour >= iBeginHour) { return true; } else { if (nowHour < iEndHour) { return true; } } } return false; } public static void main(String[] args) { String nDayFmtDAte = DateUtil.getNDayFmtDAte("yyyy-MM-dd HH:mm:ss", 3); System.out.println(nDayFmtDAte); } }
lijufeng2016/data-manager
src/main/java/com/xkj/mlrc/clean/util/DateUtil.java
214,266
package com.collect.algorithm; //演示FIFO、LRU两种算法及其数据结构 public class TestQueue { public static void main(String[] args) { testFifo(); // 测试FIFO算法用到的数据结构 testLru(); // 测试LRU算法用到的数据结构 } // 测试FIFO算法(先进先出)用到的数据结构 private static void testFifo() { // 声明一个容量为5的先进先出队列 FifoList<Character> fifoList = new FifoList<Character>(5); //String str = "abcdefghijklfghlijf"; String str = "先天下之忧而忧后天下之乐而乐天天快乐"; for (int i = 0; i < str.length(); i++) { fifoList.add(str.charAt(i)); // 把字符加入先进先出队列 } System.out.println("先进先出队列的大小为" + fifoList.size()); System.out.println("先进先出队列的当前元素包括:" + fifoList); } // 测试LRU算法(最久未使用)用到的数据结构 private static void testLru() { // 声明一个容量为5的最久未使用队列 LruMap<Character, Integer> lruMap = new LruMap<Character, Integer>(5); //String str = "abcdefghijklfghlijf"; String str = "先天下之忧而忧后天下之乐而乐天天快乐"; for (int i = 0; i < str.length(); i++) { // 把字符加入最久未使用队列。其中键名为该字符,键值为序号 lruMap.put(str.charAt(i), i); } System.out.println("最久未使用队列的大小为" + lruMap.size()); System.out.println("最久未使用队列的当前元素包括:" + lruMap); } }
aqi00/java
chapter09/src/com/collect/algorithm/TestQueue.java
214,267
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */ package nl.procura.gba.web.components.containers; import com.vaadin.data.Item; import nl.procura.burgerzaken.gba.core.enums.GBATable; import nl.procura.vaadin.component.field.fieldvalues.FieldValue; import nl.procura.vaadin.component.field.fieldvalues.TabelFieldValue; public class VerblijfstitelContainer extends TabelContainer { public VerblijfstitelContainer() { this(false); } private VerblijfstitelContainer(boolean isCurrent) { super(GBATable.VERBLIJFSTITEL, isCurrent); } @Override public Item addItem(Object itemId) { if (itemId instanceof FieldValue) { TabelFieldValue fd = (TabelFieldValue) itemId; return super.addItem(new TabelFieldValue(fd.getValue(), fd.getValue() + ": " + fd.getDescription())); } return super.addItem(itemId); } }
vrijBRP/vrijBRP-Balie
gba-web/src/main/java/nl/procura/gba/web/components/containers/VerblijfstitelContainer.java
214,268
package com.alibaba.datax.plugin.writer.rediswriter.writer; import com.alibaba.datax.common.element.Record; import com.alibaba.datax.common.plugin.RecordReceiver; import com.alibaba.datax.common.util.Configuration; import com.alibaba.datax.plugin.writer.rediswriter.RedisWriteAbstract; /** * @author [email protected] * @date 2020/5/19 16:15 * @desc string类型写redis */ public class StringTypeWriter extends RedisWriteAbstract { public StringTypeWriter(Configuration configuration) { super(configuration); } @Override public void checkAndGetParams() { super.checkAndGetParams(); } @Override public void addToPipLine(RecordReceiver lineReceiver) { Record record; while ((record = lineReceiver.getFromReader()) != null) { String redisKey; String redisValue; if (null != keyIndex) { String key = record.getColumn(keyIndex).asString(); redisKey = keyPreffix + key + keySuffix; redisValue = record.getColumn(valueIndex).asString(); } else { redisKey = keyPreffix + strKey + keySuffix; redisValue = record.getColumn(valueIndex).asString(); } pipelined.set(redisKey, redisValue); pipelined.expire(redisKey, expire); records++; } } }
lijufeng2016/DataX-redis-writer
src/main/java/com/alibaba/datax/plugin/writer/rediswriter/writer/StringTypeWriter.java
214,271
package com.xkj.mlrc.common.shell; /** * @author [email protected] * @date 2020/4/24 14:56 * @desc */ import com.jcraft.jsch.UserInfo; public class MyUserInfo implements UserInfo { @Override public String getPassphrase() { // TODO Auto-generated method stub System.out.println("MyUserInfo.getPassphrase()"); return null; } @Override public String getPassword() { // TODO Auto-generated method stub System.out.println("MyUserInfo.getPassword()"); return null; } @Override public boolean promptPassphrase(String arg0) { // TODO Auto-generated method stub System.out.println("MyUserInfo.promptPassphrase()"); System.out.println(arg0); return false; } @Override public boolean promptPassword(String arg0) { // TODO Auto-generated method stub System.out.println("MyUserInfo.promptPassword()"); System.out.println(arg0); return false; } @Override public boolean promptYesNo(String arg0) { // TODO Auto-generated method stub' System.out.println("MyUserInfo.promptYesNo()"); System.out.println(arg0); if (arg0.contains("The authenticity of host")) { return true; } return true; } @Override public void showMessage(String arg0) { // TODO Auto-generated method stub System.out.println("MyUserInfo.showMessage()"); } }
lijufeng2016/data-manager
src/main/java/com/xkj/mlrc/common/shell/MyUserInfo.java
214,272
class n343230 { public Source resolve(String edbYkWln, String Cv5tVeuU) throws TransformerException { if (edbYkWln.endsWith(".txt")) { try { URL tGOu95Rb = new URL(new URL(Cv5tVeuU), edbYkWln); java.io.InputStream lRuNAArb = tGOu95Rb.openConnection().getInputStream(); java.io.InputStreamReader uj8L25nC = new java.io.InputStreamReader(lRuNAArb, "iso-8859-1"); StringBuffer LVKB8hNS = new StringBuffer(); while (true) { int YKVdpSBU = uj8L25nC.read(); if (YKVdpSBU < 0) break; LVKB8hNS.append((char) YKVdpSBU); } com.icl.saxon.expr.TextFragmentValue GsFo56hg = new com.icl.saxon.expr.TextFragmentValue( LVKB8hNS.toString(), tGOu95Rb.toString(), (com.icl.saxon.Controller) transformer); return GsFo56hg.getFirst(); } catch (Exception LIJfhFtR) { throw new TransformerException(LIJfhFtR); } } else { return null; } } }
Santiago-Yu/SPAT
Benchmarks/9133/transformed/_0/n343230.java
214,273
package nl.topicus.eduarte.dao.helpers; import nl.topicus.cobra.dao.helpers.BatchZoekFilterDataAccessHelper; import nl.topicus.eduarte.entities.landelijk.Verblijfsvergunning; import nl.topicus.eduarte.zoekfilters.LandelijkCodeNaamZoekFilter; public interface VerblijfsvergunningDataAccessHelper extends BatchZoekFilterDataAccessHelper<Verblijfsvergunning, LandelijkCodeNaamZoekFilter<Verblijfsvergunning>> { public Verblijfsvergunning get(String code); }
topicusonderwijs/tribe-krd-opensource
eduarte/core/src/main/java/nl/topicus/eduarte/dao/helpers/VerblijfsvergunningDataAccessHelper.java
214,274
package org.cloudbees.equality; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.Level; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.annotations.TearDown; import org.openjdk.jmh.infra.Blackhole; @State(Scope.Thread) public class EqualityCosts { private Object x = new Object(); private Object y = new Object(); private Object z = new Object(); private Object w = new Object(); private Object a1; private Object a2; private Object a3; private Object a4; private Object b1; private Object b2; private Object b3; private Object b4; private Object c1; private Object c2; private Object c3; private Object c4; private Object d1; private Object d2; private Object d3; private Object d4; private Object e1; private Object e2; private Object e3; private Object e4; private Object f1; int something; public EqualityCosts() { } @Setup(Level.Iteration) public void init() { x = createSomething(); y = createSomething(); z = createSomething(); w = createSomething(); a1 = new BeanA(x, z); a2 = new BeanA(x, w); a3 = new BeanA(y, z); a4 = new BeanA(y, w); b1 = new BeanB(x, z); b2 = new BeanB(x, w); b3 = new BeanB(y, z); b4 = new BeanB(y, w); c1 = new BeanC(x, z); c2 = new BeanC(x, w); c3 = new BeanC(y, z); c4 = new BeanC(y, w); d1 = new BeanD(x, z); d2 = new BeanD(x, w); d3 = new BeanD(y, z); d4 = new BeanD(y, w); e1 = new BeanE(x, z); e2 = new BeanE(x, w); e3 = new BeanE(y, z); e4 = new BeanE(y, w); f1 = new BeanF(x, z); } @TearDown(Level.Iteration) public void preventInliningOptimization(Blackhole bh) { a1 = createSomething(); a2 = createSomething(); a3 = createSomething(); a4 = createSomething(); b1 = createSomething(); b2 = createSomething(); b3 = createSomething(); b4 = createSomething(); c1 = createSomething(); c2 = createSomething(); c3 = createSomething(); c4 = createSomething(); d1 = createSomething(); d2 = createSomething(); d3 = createSomething(); d4 = createSomething(); e1 = createSomething(); e2 = createSomething(); e3 = createSomething(); e4 = createSomething(); f1 = createSomething(); optionalFilter_xa(bh); optionalFilter_xn(bh); optionalFilter_xo(bh); optionalFilter_xx(bh); optionalFilter_xy(bh); optionalFilter_xz(bh); optionalFilter_xw(bh); intellijDefault_xa(bh); intellijDefault_xn(bh); intellijDefault_xo(bh); intellijDefault_xx(bh); intellijDefault_xy(bh); intellijDefault_xz(bh); intellijDefault_xw(bh); intellijInline_xn(bh); intellijInline_xx(bh); objectsEquals_xa(bh); objectsEquals_xn(bh); objectsEquals_xx(bh); objectsEquals_xy(bh); objectsEquals_xz(bh); commonsLang3_xa(bh); commonsLang3_xn(bh); commonsLang3_xx(bh); commonsLang3_xy(bh); commonsLang3_xz(bh); intellijFields_xa(bh); intellijFields_xn(bh); intellijFields_xx(bh); intellijFields_xy(bh); intellijFields_xz(bh); reference(bh); } private Object createSomething() { // we want a prime number of object types that all have their own impl of .equals switch (something++) { case 0: return new Object(){ @Override public boolean equals(Object obj) { return this == obj; } @Override public String toString() { return "0"; } }; case 1: return new Object() { @Override public boolean equals(Object obj) { return this == obj; } @Override public String toString() { return "1"; } }; case 2: return new Object() { @Override public boolean equals(Object obj) { return this == obj; } @Override public String toString() { return "2"; } }; case 3: return new Object() { @Override public boolean equals(Object obj) { return this == obj; } @Override public String toString() { return "3"; } }; case 4: return new Object() { @Override public boolean equals(Object obj) { return this == obj; } @Override public String toString() { return "4"; } }; case 5: return new Object() { @Override public boolean equals(Object obj) { return this == obj; } @Override public String toString() { return "5"; } }; default: something = 0; return new Object() { @Override public boolean equals(Object obj) { return this == obj; } @Override public String toString() { return "6"; } }; } } @Benchmark public void optionalFilter(Blackhole bh) { Bean b = new Bean(...); bh.consume(b.equals(b)); bh.consume(b.equals(null)); bh.consume(b.equals("")); bh.consume(b.equals(new Bean(...))); } @Benchmark public void optionalFilter_xa(Blackhole bh) { bh.consume(a1.equals(null)); bh.consume(a1.equals(x)); bh.consume(a1.equals(a1)); bh.consume(a1.equals(a2)); bh.consume(a1.equals(a3)); bh.consume(a1.equals(a4)); } @Benchmark public void optionalFilter_xn(Blackhole bh) { bh.consume(a1.equals(null)); } @Benchmark public void optionalFilter_xo(Blackhole bh) { bh.consume(a1.equals(x)); } @Benchmark public void optionalFilter_xx(Blackhole bh) { bh.consume(a1.equals(a1)); } @Benchmark public void optionalFilter_xy(Blackhole bh) { bh.consume(a1.equals(a2)); } @Benchmark public void optionalFilter_xz(Blackhole bh) { bh.consume(a1.equals(a3)); } @Benchmark public void optionalFilter_xw(Blackhole bh) { bh.consume(a1.equals(a4)); } @Benchmark public void intellijDefault_xa(Blackhole bh) { bh.consume(b1.equals(null)); bh.consume(b1.equals(x)); bh.consume(b1.equals(b1)); bh.consume(b1.equals(b2)); bh.consume(b1.equals(b3)); bh.consume(b1.equals(b4)); } @Benchmark public void intellijDefault_xn(Blackhole bh) { bh.consume(b1.equals(null)); } @Benchmark public void intellijDefault_xo(Blackhole bh) { bh.consume(b1.equals(x)); } @Benchmark public void intellijDefault_xx(Blackhole bh) { bh.consume(b1.equals(b1)); } @Benchmark public void intellijDefault_xy(Blackhole bh) { bh.consume(b1.equals(b2)); } @Benchmark public void intellijDefault_xz(Blackhole bh) { bh.consume(b1.equals(b3)); } @Benchmark public void intellijDefault_xw(Blackhole bh) { bh.consume(b1.equals(b4)); } @Benchmark public void intellijInline_xn(Blackhole bh) { bh.consume(f1.equals(null)); } @Benchmark public void intellijInline_xx(Blackhole bh) { bh.consume(f1.equals(f1)); } @Benchmark public void objectsEquals_xa(Blackhole bh) { bh.consume(c1.equals(null)); bh.consume(c1.equals(x)); bh.consume(c1.equals(c1)); bh.consume(c1.equals(c2)); bh.consume(c1.equals(c3)); bh.consume(c1.equals(c4)); } @Benchmark public void objectsEquals_xn(Blackhole bh) { bh.consume(c1.equals(null)); } @Benchmark public void objectsEquals_xx(Blackhole bh) { bh.consume(c1.equals(c1)); } @Benchmark public void objectsEquals_xy(Blackhole bh) { bh.consume(c1.equals(c2)); } @Benchmark public void objectsEquals_xz(Blackhole bh) { bh.consume(c1.equals(c3)); } @Benchmark public void commonsLang3_xa(Blackhole bh) { bh.consume(d1.equals(null)); bh.consume(d1.equals(x)); bh.consume(d1.equals(d1)); bh.consume(d1.equals(d2)); bh.consume(d1.equals(d3)); bh.consume(d1.equals(d4)); } @Benchmark public void commonsLang3_xn(Blackhole bh) { bh.consume(d1.equals(null)); } @Benchmark public void commonsLang3_xx(Blackhole bh) { bh.consume(d1.equals(d1)); } @Benchmark public void commonsLang3_xy(Blackhole bh) { bh.consume(d1.equals(d2)); } @Benchmark public void commonsLang3_xz(Blackhole bh) { bh.consume(d1.equals(d3)); } @Benchmark public void intellijFields_xa(Blackhole bh) { bh.consume(e1.equals(null)); bh.consume(e1.equals(x)); bh.consume(e1.equals(e1)); bh.consume(e1.equals(e2)); bh.consume(e1.equals(e3)); bh.consume(e1.equals(e4)); } @Benchmark public void intellijFields_xn(Blackhole bh) { bh.consume(e1.equals(null)); } @Benchmark public void intellijFields_xx(Blackhole bh) { bh.consume(e1.equals(e1)); } @Benchmark public void intellijFields_xy(Blackhole bh) { bh.consume(e1.equals(e2)); } @Benchmark public void intellijFields_xz(Blackhole bh) { bh.consume(e1.equals(e3)); } @Benchmark public void reference(Blackhole bh) { bh.consume(true); } }
stephenc/cost-of-equality
src/main/java/org/cloudbees/equality/EqualityCosts.java
214,276
package greenmoonsoftware.gopherwave.intellij; import com.intellij.openapi.editor.Document; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.vfs.VfsUtilCore; import com.intellij.openapi.vfs.VirtualFile; public class IntellijFileDocumentManager implements IFileDocumentManager { private final Project project; public IntellijFileDocumentManager(Project project) { this.project = project; } @Override public String getRelativePath(Document document) { VirtualFile file = getFile(document); if (file == null) { System.out.println("Could not find file"); return ""; } return VfsUtilCore.getRelativePath(file, project.getBaseDir(), '/'); } private VirtualFile getFile(Document document) { return FileDocumentManager.getInstance().getFile(document); } }
greathouse/tidewater
eventsourcing/gopherwave/gopherwave-intellij/src/main/greenmoonsoftware/gopherwave/intellij/IntellijFileDocumentManager.java
214,278
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */ package nl.procura.gba.web.modules.bs.geboorte.page60; import static nl.procura.standard.Globalfunctions.pos; import java.io.Serializable; import java.lang.annotation.ElementType; import nl.procura.gba.web.components.containers.LandContainer; import nl.procura.gba.web.components.fields.GbaComboBox; import nl.procura.gba.web.components.layouts.form.GbaForm; import nl.procura.gba.web.components.listeners.FieldChangeListener; import nl.procura.gba.web.services.bs.geboorte.DossierGeboorte; import nl.procura.vaadin.annotation.field.Field; import nl.procura.vaadin.annotation.field.FormFieldFactoryBean; import nl.procura.vaadin.annotation.field.Immediate; import nl.procura.vaadin.annotation.field.Select; import nl.procura.vaadin.component.field.fieldvalues.FieldValue; import lombok.Data; public class Page60GeboorteStap3 extends GbaForm<Page60GeboorteStap3.Page60GeboorteBean4> { public static final String VERBLIJFSLAND = "verblijfsLand"; public Page60GeboorteStap3(DossierGeboorte geboorte) { setCaption("Stap 3"); setReadThrough(true); setColumnWidths("200px", ""); setOrder(VERBLIJFSLAND); Page60GeboorteBean4 bean = new Page60GeboorteBean4(); if (pos(geboorte.getVerblijfsLandAfstamming().getValue())) { bean.setVerblijfsLand(geboorte.getVerblijfsLandAfstamming()); } setBean(bean); } @Override public void setBean(Object bean) { super.setBean(bean); getField(VERBLIJFSLAND).addListener(new FieldChangeListener<FieldValue>() { @Override public void onChange(FieldValue value) { onWijzigingVerblijfsland(value); } }); } @Override public Page60GeboorteBean4 getNewBean() { return new Page60GeboorteBean4(); } public FieldValue getVerblijfsLand() { return getBean().getVerblijfsLand(); } public void setVerblijfsLand(FieldValue land) { getBean().setVerblijfsLand(land); if (getField(VERBLIJFSLAND) != null) { getField(VERBLIJFSLAND).setValue(land); } } @SuppressWarnings("unused") protected void onWijzigingVerblijfsland(FieldValue land) { } @Data @FormFieldFactoryBean(accessType = ElementType.FIELD) public class Page60GeboorteBean4 implements Serializable { @Field(customTypeClass = GbaComboBox.class, caption = "Verblijfplaats (land) kind in?", required = true, width = "300px") @Select(containerDataSource = LandContainer.class) @Immediate private FieldValue verblijfsLand = new FieldValue(); } }
vrijBRP/vrijBRP-Balie
gba-web/src/main/java/nl/procura/gba/web/modules/bs/geboorte/page60/Page60GeboorteStap3.java
214,279
package com.alibaba.datax.plugin.writer.rediswriter.writer; import com.alibaba.datax.common.element.Record; import com.alibaba.datax.common.plugin.RecordReceiver; import com.alibaba.datax.common.util.Configuration; import com.alibaba.datax.plugin.writer.rediswriter.RedisWriteAbstract; /** * @author [email protected] * @date 2020/5/19 16:15 * @desc string类型写redis */ public class StringTypeWriter extends RedisWriteAbstract { public StringTypeWriter(Configuration configuration) { super(configuration); } @Override public void checkAndGetParams() { super.checkAndGetParams(); } @Override public void addToPipLine(RecordReceiver lineReceiver) { Record record; while ((record = lineReceiver.getFromReader()) != null) { String redisKey; String redisValue; if (null != keyIndex) { String key = record.getColumn(keyIndex).asString(); redisKey = keyPreffix + key + keySuffix; redisValue = record.getColumn(valueIndex).asString(); } else { redisKey = keyPreffix + strKey + keySuffix; redisValue = record.getColumn(valueIndex).asString(); } redisValue = valuePreffix + redisValue + valueSuffix; pipelined.set(redisKey, redisValue); pipelined.expire(redisKey, expire); records++; } } }
lijufeng2016/DataX
rediswriter/src/main/java/com/alibaba/datax/plugin/writer/rediswriter/writer/StringTypeWriter.java
214,280
package com.alibaba.datax.plugin.writer.rediswriter.writer; import com.alibaba.datax.common.element.Record; import com.alibaba.datax.common.exception.CommonErrorCode; import com.alibaba.datax.common.exception.DataXException; import com.alibaba.datax.common.plugin.RecordReceiver; import com.alibaba.datax.common.util.Configuration; import com.alibaba.datax.plugin.writer.rediswriter.Constant; import com.alibaba.datax.plugin.writer.rediswriter.Key; import com.alibaba.datax.plugin.writer.rediswriter.RedisWriteAbstract; import org.apache.commons.lang3.StringUtils; /** * @author [email protected] * @date 2020/5/19 16:18 * @desc list类型写redis */ public class ListTypeWriter extends RedisWriteAbstract { String pushType; String valueDelimiter; public ListTypeWriter(Configuration configuration) { super(configuration); } @Override public void checkAndGetParams() { super.checkAndGetParams(); Configuration detailConfig = this.configuration.getConfiguration(Key.CONFIG); pushType = detailConfig.getString(Key.LIST_PUSH_TYPE, Constant.LIST_PUSH_TYPE_OVERWRITE); valueDelimiter = detailConfig.getString(Key.LIST_VALUE_DELIMITER); if (StringUtils.isBlank(valueDelimiter)) { throw DataXException.asDataXException(CommonErrorCode.CONFIG_ERROR, "valueDelimiter不能为空!请检查配置"); } if(!Constant.LIST_PUSH_TYPE_LPUSH.equalsIgnoreCase(pushType) && !Constant.LIST_PUSH_TYPE_RPUSH.equalsIgnoreCase(pushType) && !Constant.LIST_PUSH_TYPE_OVERWRITE.equalsIgnoreCase(pushType)){ throw DataXException.asDataXException(CommonErrorCode.CONFIG_ERROR, "pushType不合法!list类型只支持lpush,rpush,overwrite!请检查配置!pushType:"+pushType); } } @Override public void addToPipLine(RecordReceiver lineReceiver) { Record record; while ((record = lineReceiver.getFromReader()) != null) { String redisKey; String columnValue; if (null != keyIndex) { String key = record.getColumn(keyIndex).asString(); redisKey = keyPreffix + key + keySuffix; } else { redisKey = keyPreffix + strKey + keySuffix; } columnValue = record.getColumn(valueIndex).asString(); String[] redisValue = columnValue.split(valueDelimiter); switch (pushType) { case Constant.LIST_PUSH_TYPE_OVERWRITE: pipelined.del(redisKey); pipelined.rpush(redisKey, redisValue); break; case Constant.LIST_PUSH_TYPE_RPUSH: pipelined.rpush(redisKey, redisValue); break; case Constant.LIST_PUSH_TYPE_LPUSH: pipelined.lpush(redisKey, redisValue); break; } records++; } } }
lijufeng2016/DataX-redis-writer
src/main/java/com/alibaba/datax/plugin/writer/rediswriter/writer/ListTypeWriter.java
214,282
import codeinspect.Inspect; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonProperty; import com.intellij.codeInsight.CodeSmellInfo; import com.intellij.codeInsight.daemon.impl.HighlightInfo; import com.intellij.codeInsight.intention.IntentionAction; import com.intellij.codeInsight.lookup.LookupElement; import com.intellij.codeInsight.lookup.LookupElementBuilder; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.*; import com.intellij.psi.impl.file.PsiPackageImpl; import com.intellij.util.ui.UIUtil; import com.neovim.Neovim; import com.neovim.NeovimHandler; import com.neovim.SocketNeovim; import com.neovim.msgpack.MessagePackRPC; import complete.*; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class NeovimIntellijComplete extends AnAction { private static final Logger LOG = Logger.getInstance(NeovimIntellijComplete.class); private Neovim mNeovim; public static class Updater { private static final Logger LOG = Logger.getInstance(NeovimIntellijComplete.class); private Neovim mNeovim; private EmbeditorRequestHandler mEmbeditorRequestHandler; private Fix[] mCachedFixes = new Fix[0]; public Updater(Neovim nvim){ mNeovim = nvim; mEmbeditorRequestHandler = new EmbeditorRequestHandler(); } /** * Hack to have up to date files when doing quickfix stuff... * @param path */ @NeovimHandler("IntellijOnWrite") public void intellijOnWrite(String path) { ApplicationManager.getApplication().invokeAndWait(() -> { PsiFile f = EmbeditorUtil.findTargetFile(path); if (f != null) { VirtualFile vf = f.getVirtualFile(); if (vf != null) vf.refresh(false, true); } }, ModalityState.any()); } @NeovimHandler("TextChanged") public void changed(String args) { LOG.info("Text changed"); } @NeovimHandler("IntellijFixProblem") public void intellijFixProblem(String path, List<String> lines, int fixId) { final String fileContent = String.join("\n", lines) ; for (Fix f : mCachedFixes) { if (f.getFixId() == fixId) { Inspect.doFix(path, fileContent, f.getAction()); break; } } } @NeovimHandler("IntellijProblems") public Fix[] intellijProblems(String path, List<String> lines, final int row, final int col) { final String fileContent = String.join("\n", lines) ; List<HighlightInfo.IntentionActionDescriptor> allFixes = Inspect.getFixes(path, fileContent, row, col); List<Fix> fixes = new ArrayList<>(); for (int i = 0; i < allFixes.size(); i++) { HighlightInfo.IntentionActionDescriptor d = allFixes.get(i); if (d.getAction().getText().length() == 0) continue; fixes.add(new Fix(d.getAction().getText(), i, d)); } mCachedFixes = fixes.toArray(new Fix[fixes.size()]); return mCachedFixes; } @NeovimHandler("IntellijCodeSmell") public Problem[] intellijCodeSmell(final String path, final List<String> lines) { final String fileContent = String.join("\n", lines); List<Problem> retval = new ArrayList<Problem>(); CodeSmellInfo[] smells = mEmbeditorRequestHandler.inspectCode(path, fileContent); for (CodeSmellInfo smell : smells) { retval.add(new Problem(smell.getStartLine(), smell.getStartColumn(), smell.getDescription())); } return retval.toArray(new Problem[]{}); } @NeovimHandler("IntellijComplete") public DeopleteItem[] intellijComplete(final String path, final String bufferContents, final int row, final int col) { LookupElement[] c = mEmbeditorRequestHandler.getCompletionVariants(path, bufferContents, row, col); if (c.length < 0) return null; DeopleteHelper dh = new DeopleteHelper(); UIUtil.invokeAndWaitIfNeeded((Runnable) () -> { for (LookupElement i : c) { if (i instanceof PsiPackage || i instanceof LookupElementBuilder || i.getPsiElement() instanceof PsiPackageImpl) { dh.add(i.getLookupString(), "", ""); continue; } String word = i.getLookupString(); List<String> params = new ArrayList<String>(); String info; String kind = ""; PsiElement psiElement = i.getPsiElement(); if (psiElement == null) { dh.add(word, "", ""); continue; } for (PsiElement e : psiElement.getChildren()) { if (e instanceof PsiParameterList) { for (PsiParameter param : ((PsiParameterList)e).getParameters()) { params.add(param.getTypeElement().getText() + " " + param.getName()); } } else if (e instanceof PsiTypeElement) { kind = e.getText(); } } info = "(" + String.join(", ", params) + ")"; dh.add(word, info, kind); } }); return dh.getItems(); } private class Fix { @JsonProperty private String description; @JsonProperty private int fixId; @JsonIgnore private HighlightInfo.IntentionActionDescriptor action; public Fix(String description, int fixId, HighlightInfo.IntentionActionDescriptor action) { this.description = description; this.fixId = fixId; this.action = action; } public String getDescription() { return description; } public int getFixId() { return fixId; } public HighlightInfo.IntentionActionDescriptor getAction() { return action; } } } public NeovimIntellijComplete() { } @Override public void actionPerformed(AnActionEvent e) { NeovimDialog dialog = new NeovimDialog(true); dialog.show(); if (dialog.isOK()) { LOG.warn(dialog.getAddr()); MessagePackRPC.Connection conn; //HostAndPort hp = HostAndPort.fromParts("127.0.0.1", 7650); try { conn = new SocketNeovim(dialog.getAddr()); } catch (IOException ex) { LOG.error("Failed to connect to neovim", ex); return; } mNeovim = Neovim.connectTo(conn); LOG.info("Connected to neovim"); long cid = mNeovim.getChannelId().join(); mNeovim.commandOutput("let g:intellijID=" + cid); // Refresh file on intellij on write so we can have uptodate stuff when doing codeanalyzis mNeovim.commandOutput("au BufWritePost * call rpcnotify(g:intellijID, \"IntellijOnWrite\", expand(\"%:p\"))"); mNeovim.register(new Updater(mNeovim)); mNeovim.sendVimCommand("echo 'Intellij connected.'"); } } }
nathandouglas/neovim-intellij-complete
src/NeovimIntellijComplete.java
214,285
/* * SPDX-FileCopyrightText: 2023 Atos * SPDX-License-Identifier: EUPL-1.2+ */ package net.atos.client.bag.util; import javax.json.bind.adapter.JsonbAdapter; import net.atos.client.bag.model.StatusVerblijfsobject; public class StatusVerblijfsobjectEnumAdapter implements JsonbAdapter<StatusVerblijfsobject, String> { @Override public String adaptToJson(final StatusVerblijfsobject statusVerblijfsobject) { return statusVerblijfsobject.toString(); } @Override public StatusVerblijfsobject adaptFromJson(final String json) { return StatusVerblijfsobject.fromValue(json); } }
NL-AMS-LOCGOV/zaakafhandelcomponent
src/main/java/net/atos/client/bag/util/StatusVerblijfsobjectEnumAdapter.java
214,286
package ogame.flota; import app.GameClient; import app.czas.CzasLotu; import com.Log; import com.Waiter; import ogame.Header; import ogame.SciezkaWebElementu; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; public class FlotaIII { private static SciezkaWebElementu missionsContainer = new SciezkaWebElementu("/html/body/div[5]/div[3]/div[2]/div[3]/div/div[4]/div[2]/div[2]/ul/li[","]"); private static SciezkaWebElementu mission = new SciezkaWebElementu("/html/body/div[5]/div[3]/div[2]/div[3]/div/div[4]/div[2]/div[2]/ul/li[","]/a"); /** * Klika w wybraną misję. * @param w driver * @param nr Rodzaj misji: * 1 - Ekspedycja * 2 - Kolonizuj * 3 - Recykluj pola * 4 - Transportuj * 5 - Stacjonuj * 6 - Szpieguj * 7 - Zatrzymaj * 8 - Atakuj * 9 - Atak związku * 10 - Niszcz */ public static void kliknijMisje(WebDriver w, int nr) { if(Header.dobryHeaderWyswietlony(w,"Wyślij flotę III", FlotaIII.class.getName())) { WebElement e; missionsContainer.setVar(nr); e = w.findElement(By.xpath(missionsContainer.toString())); if(e.getAttribute("class").contains("on")) { mission.setVar(nr); e = w.findElement(By.xpath(mission.toString())); e.click(); Log.printLog(FlotaIII.class.getName(), "Kliknięto misję nr "+nr); } else Log.printLog(FlotaIII.class.getName(), "Misja niedostępna"); } else Log.printLog(FlotaIII.class.getName(), "Nie znaleziono WebElementu - Misja nr " + nr + "."); } /** * Zwraca rozdaj misji w postaci Integer. Wartość domyślna jest 2 - misja kolonizuj. * @param missionType * * 1 - Ekspedycja * * 2 - Kolonizuj * * 3 - Recykluj pola * * 4 - Transportuj * * 5 - Stacjonuj * * 6 - Szpieguj * * 7 - Zatrzymaj * * 8 - Atakuj * * 9 - Atak związku * * 10 - Niszcz * @return Wartość domyślna jest 2 - misja kolonizuj lub jak powyżej */ public static int intMissionType(String missionType) { switch (missionType) { case "Ekspedycja": return 1; case "Kolonizuj": return 2; case "Recykluj pola": return 3; case "Transportuj": return 4; case "Stacjonuj": return 5; case "Szpieguj": return 6; case "Zatrzymaj": return 7; case "Atakuj": return 8; case "Atak związku": return 9; case "Niszcz": return 10; } return 2; } /** * Klika w button wszystkie suurowce. */ public static void clickWszystkieSurowce(WebDriver w) { if(Header.dobryHeaderWyswietlony(w,"Wyślij flotę III", FlotaIII.class.getName())) { WebElement e = w.findElement(By.xpath("/html/body/div[5]/div[3]/div[2]/div[3]/div/div[4]/div[3]/div[2]/form/div[1]/div[2]/div[4]/a/img")); GameClient.scrollToElement(w, e); e.click(); Log.printLog(FlotaIII.class.getName(),"Klikam wszystkie surowce."); } else Log.printLog(FlotaIII.class.getName(),"Nie znaleziono WebElementu - Wszystkie surowce."); } /** * Klika w button wyślij flotę. */ public static void wyslijFlote(WebDriver w) { if(Header.dobryHeaderWyswietlony(w,"Wyślij flotę III", FlotaIII.class.getName())) { WebElement e = w.findElement(By.xpath("/html/body/div[5]/div[3]/div[2]/div[3]/div/div[4]/div[3]/div[2]/form/div[2]/a[2]/span")); GameClient.scrollToElement(w,e); e.click(); Log.printLog(FlotaIII.class.getName(),"Kliknąłem wyślij."); } else Log.printLog(FlotaIII.class.getName(),"Nie znaleziono WebElementu - Wyślij flotę."); } /** * Komunikat wyświetla się gdy osiągnieliśmy maksymalną ilość kolonii i wysyłamy na misję kolonizuj. Potwierdza komunikat * @param w driver * @param className klasa */ public static void potwierdzMisjeKolonizuj(WebDriver w, String className) { String [] paths = { "//*[@id=\"errorBoxDecisionYes\"]", }; WebElement e; int index = 0; boolean bool = true; while(bool) { try { e = w.findElement(By.xpath(paths[index])); bool = false; e.click(); } catch(Exception ex) { index++; } finally { if(index > 5) { bool = false; Log.printLog(className,"Sprawdzono wszystkie ścieżki, żadna nie pasuje."); } if(bool) { Log.printLog(className, "Nie widoczny ErrorBox do misji kolonizuj. Czekam... po raz "+ index); Waiter.sleep(100,100); } } } Log.printLog(className, "Nie widoczny ErrorBox do misji kolonizuj."); } /** * Sprawdza czy została wybrana jakaś misja. * @param className Nazwa klasy z której jest metoda wywoływana. * @return Jeżeli została wybrana misja, to zwróci <b>true</b>. */ public static boolean isMissionSelected(WebDriver w, String className) { if(Header.dobryHeaderWyswietlony(w,"Wyślij flotę III", FlotaIII.class.getName())) { WebElement e; for (int i = 1; i <= 10; i++) { mission.setVar(i); e = w.findElement(By.xpath(mission.toString())); if (e.getAttribute("class").contains("selected")) { Log.printLog(className,"Wybrano misję nr "+i+"."); return true; } } } Log.printLog(className,"Nie wybrano żadnej misji."); return false; } public static CzasLotu czasLotu(WebDriver w) { CzasLotu czasLotu = new CzasLotu(); if(Header.dobryHeaderWyswietlony(w,"Wyślij flotę III", FlotaIII.class.getName())) { WebElement e = w.findElement(By.xpath("/html/body/div[5]/div[3]/div[2]/div[3]/div/div[4]/div[3]/div[2]/form/div[1]/div[1]/ul/li[4]/span")); czasLotu.setCzasString(e.getText().split(" ")[0]); Log.printLog(FlotaIII.class.getName(),"Pobrałem dane o czasie lotu."); } else Log.printLog(FlotaIII.class.getName(),"Nie znaleziono WebElementu - czas lotu."); return czasLotu; } public static CzasLotu przylot(WebDriver w) { CzasLotu czasLotu = new CzasLotu(); if(Header.dobryHeaderWyswietlony(w,"Wyślij flotę III", FlotaIII.class.getName())) { WebElement e = w.findElement(By.xpath("/html/body/div[5]/div[3]/div[2]/div[3]/div/div[4]/div[3]/div[2]/form/div[1]/div[1]/ul/li[5]/span/span")); String [] tmp = e.getText().split(" "); czasLotu.setCzasString(tmp[1]); czasLotu.setDataString(tmp[0]); Log.printLog(FlotaIII.class.getName(),"Pobrałem dane o czasie przylotu."); } else Log.printLog(FlotaIII.class.getName(),"Nie znaleziono WebElementu - czas przylotu."); return czasLotu; } public static CzasLotu powrot(WebDriver w) { CzasLotu czasLotu = new CzasLotu(); if(Header.dobryHeaderWyswietlony(w,"Wyślij flotę III", FlotaIII.class.getName())) { WebElement e = w.findElement(By.xpath("/html/body/div[5]/div[3]/div[2]/div[3]/div/div[4]/div[3]/div[2]/form/div[1]/div[1]/ul/li[6]/span/span")); String [] tmp = e.getText().split(" "); czasLotu.setCzasString(tmp[1]); czasLotu.setDataString(tmp[0]); Log.printLog(FlotaIII.class.getName(),"Pobrałem dane o czasie powrotu."); } else Log.printLog(FlotaIII.class.getName(),"Nie znaleziono WebElementu - czas powrotu."); return czasLotu; } /** * Pobiera dane o wolnej przestrzeni ładunkowej wysyłanej floty. */ public static int wolnaPrzestrzenLadunkowa(WebDriver w) { if(Header.dobryHeaderWyswietlony(w,"Wyślij flotę III", FlotaIII.class.getName())) { WebElement e = w.findElement(By.xpath("//*[@id=\"remainingresources\"]")); String [] tmpTab = e.getText().split("\\."); StringBuilder tmpString = new StringBuilder(); for(String s : tmpTab) { tmpString.append(s); } return Integer.valueOf(tmpString.toString()); } else Log.printLog(FlotaIII.class.getName(),"Nie znaleziono WebElementu - czas powrotu."); return -1; } /** * Metoda pobierająca dane o maksymalne przestrzeni ładunkowej wysyłanej floty. */ public static int maksymalnaPrzestrzenLadunkowa(WebDriver w) { if(Header.dobryHeaderWyswietlony(w,"Wyślij flotę III", FlotaIII.class.getName())) { WebElement e = w.findElement(By.xpath("//*[@id=\"maxresources\"]")); String [] tmpTab = e.getText().split("\\."); StringBuilder tmpString = new StringBuilder(); for(String s : tmpTab) { tmpString.append(s); } return Integer.valueOf(tmpString.toString()); } else Log.printLog(FlotaIII.class.getName(),"Nie znaleziono WebElementu - czas powrotu."); return -1; } }
shahhimtest/ogamebot4
src/ogame/flota/FlotaIII.java
214,287
package com.alibaba.datax.plugin.writer.rediswriter; import com.alibaba.datax.common.exception.CommonErrorCode; import com.alibaba.datax.common.exception.DataXException; import com.alibaba.datax.common.plugin.RecordReceiver; import com.alibaba.datax.common.util.Configuration; import org.apache.commons.lang3.StringUtils; import redis.clients.jedis.PipelineBase; /** * @author [email protected] * @date 2020/5/19 15:56 * @desc 写redis对象抽象类 */ public abstract class RedisWriteAbstract { protected Configuration configuration; protected PipelineBase pipelined; Object redisClient; protected int records; protected String keyPreffix; protected String keySuffix; protected Integer batchSize; protected Integer expire; protected String strKey; protected Integer keyIndex; protected Integer valueIndex; public RedisWriteAbstract(Configuration configuration) { this.configuration = configuration; } public PipelineBase getRedisPipelineBase(Configuration configuration) { String mode = configuration.getNecessaryValue(Key.REDISMODE, CommonErrorCode.CONFIG_ERROR); String addr = configuration.getNecessaryValue(Key.ADDRESS, CommonErrorCode.CONFIG_ERROR); String auth = configuration.getString(Key.AUTH); if (Constant.CLUSTER.equalsIgnoreCase(mode)) { redisClient = RedisWriterHelper.getJedisCluster(addr, auth); } else { redisClient = RedisWriterHelper.getJedis(addr, auth); } return RedisWriterHelper.getPipeLine(redisClient); } /** * 初始化公共参数 */ public void initCommonParams() { Configuration detailConfig = this.configuration.getConfiguration(Key.CONFIG); batchSize = detailConfig.getInt(Key.BATCH_SIZE, 1000); keyPreffix = detailConfig.getString(Key.KEY_PREFIX, ""); keySuffix = detailConfig.getString(Key.KEY_SUFFIX, ""); expire = detailConfig.getInt(Key.EXPIRE, Integer.MAX_VALUE); pipelined = getRedisPipelineBase(configuration); } /** * 检查和解析参数 */ public void checkAndGetParams() { Configuration detailConfig = configuration.getConfiguration(Key.CONFIG); String colKey = detailConfig.getString(Key.COLKEY, null); String strKey = detailConfig.getString(Key.STRING_KEY, null); if ((StringUtils.isBlank(colKey) && StringUtils.isBlank(strKey))) { throw DataXException.asDataXException(CommonErrorCode.CONFIG_ERROR, "strKey或colKey不能为空!请检查配置"); } if ((StringUtils.isNotBlank(colKey) && StringUtils.isNotBlank(strKey))) { throw DataXException.asDataXException(CommonErrorCode.CONFIG_ERROR, "strKey或colKey不能同时存在!请检查配置"); } if (StringUtils.isNotBlank(colKey)) { keyIndex = detailConfig.getConfiguration(Key.COLKEY).getInt(Key.COL_INDEX); } else { this.strKey = strKey; } String colValue = detailConfig.getString(Key.COLVALUE, null); if (StringUtils.isNotBlank(colKey) && StringUtils.isBlank(colValue)) { throw DataXException.asDataXException(CommonErrorCode.CONFIG_ERROR, "colValue不能为空!请检查配置"); } String writeType = configuration.getString(Key.WRITE_TYPE); // hash类型的colValue配置里面有多个column,要考虑排除获取valueIndex,HashTypeWriter子类单独处理 if (!Constant.WRITE_TYPE_HASH.equalsIgnoreCase(writeType)) { valueIndex = detailConfig.getConfiguration(Key.COLVALUE).getInt(Key.COL_INDEX); } } /** * 把数据add到pipeline * * @param lineReceiver PipelineBase */ public abstract void addToPipLine(RecordReceiver lineReceiver); /** * 正式写入数据到redis */ public void syscData() { if (records >= batchSize) { RedisWriterHelper.syscData(pipelined); records = 0; } } public void syscAllData() { RedisWriterHelper.syscData(pipelined); } /** * 关闭资源 */ public void close() { RedisWriterHelper.syscData(pipelined); RedisWriterHelper.close(redisClient); } }
lijufeng2016/DataX-redis-writer
src/main/java/com/alibaba/datax/plugin/writer/rediswriter/RedisWriteAbstract.java
214,288
/* * Copyright 2021 - 2022 Procura B.V. * * In licentie gegeven krachtens de EUPL, versie 1.2 * U mag dit werk niet gebruiken, behalve onder de voorwaarden van de licentie. * U kunt een kopie van de licentie vinden op: * * https://github.com/vrijBRP/vrijBRP/blob/master/LICENSE.md * * Deze bevat zowel de Nederlandse als de Engelse tekst * * Tenzij dit op grond van toepasselijk recht vereist is of schriftelijk * is overeengekomen, wordt software krachtens deze licentie verspreid * "zoals deze is", ZONDER ENIGE GARANTIES OF VOORWAARDEN, noch expliciet * noch impliciet. * Zie de licentie voor de specifieke bepalingen voor toestemmingen en * beperkingen op grond van de licentie. */ package nl.procura.gba.web.services.zaken.rijbewijs; import static nl.procura.standard.Globalfunctions.*; import nl.procura.diensten.gba.ple.extensions.BasePLExt; import nl.procura.diensten.gba.ple.openoffice.DocumentPL; import nl.procura.gba.common.DateTime; import nl.procura.gba.common.ZaakStatusType; import nl.procura.gba.common.ZaakType; import nl.procura.gba.jpa.personen.db.Location; import nl.procura.gba.jpa.personen.db.Nrd; import nl.procura.gba.jpa.personen.db.Usr; import nl.procura.gba.web.components.fields.values.UsrFieldValue; import nl.procura.gba.web.services.beheer.locatie.Locatie; import nl.procura.gba.web.services.gba.basistabellen.gemeente.Gemeente; import nl.procura.gba.web.services.zaken.algemeen.GenericZaak; import nl.procura.gba.web.services.zaken.algemeen.ZaakAfhaalbaar; import nl.procura.gba.web.services.zaken.algemeen.ZaakHistorie; import nl.procura.gba.web.services.zaken.algemeen.contact.ContactZaak; import nl.procura.gba.web.services.zaken.algemeen.contact.ZaakContact; import nl.procura.gba.web.services.zaken.identiteit.Identificatie; import nl.procura.gba.web.services.zaken.reisdocumenten.clausule.VermeldTitelType; import nl.procura.java.reflection.ReflectionUtil; import nl.procura.vaadin.component.field.fieldvalues.AnrFieldValue; import nl.procura.vaadin.component.field.fieldvalues.BsnFieldValue; import nl.procura.vaadin.component.field.fieldvalues.FieldValue; public class RijbewijsAanvraag extends Nrd implements ContactZaak, ZaakAfhaalbaar { private static final long serialVersionUID = -3468735287544148942L; private final GenericZaak zaak = new GenericZaak(); private Contactgegevens contactgegevens = new Contactgegevens(this); private RijbewijsAanvraagStatussen statussen = new RijbewijsAanvraagStatussen(); public RijbewijsAanvraag() { setStatus(ZaakStatusType.OPGENOMEN); } public String getAanvraagNummer() { return getAanvrNr(); } public void setAanvraagNummer(String aanvraagNummer) { setAanvrNr(aanvraagNummer); } @Override public AnrFieldValue getAnummer() { return new AnrFieldValue(getAnr()); } @Override public void setAnummer(AnrFieldValue anr) { setAnr(FieldValue.from(anr).getStringValue()); } @Override public BasePLExt getBasisPersoon() { return zaak.getBasisPersoon(); } @Override public void setBasisPersoon(BasePLExt basisPersoon) { zaak.setBasisPersoon(basisPersoon); } @Override public BsnFieldValue getBurgerServiceNummer() { return new BsnFieldValue(astr(getBsn())); } @Override public void setBurgerServiceNummer(BsnFieldValue bsn) { setBsn(FieldValue.from(bsn).getBigDecimalValue()); } public int getCodeRas() { return aval(getCRaas()); } public void setCodeRas(int codeRas) { setCRaas(toBigDecimal(codeRas)); } public long getCodeVerblijfstitel() { return along(getCVbt()); } public void setCodeVerblijfstitel(long cvbt) { setCVbt(toBigDecimal(cvbt)); } @Override public ZaakContact getContact() { return zaak.getContact(); } @Override public void setContact(ZaakContact contact) { zaak.setContact(contact); } public Contactgegevens getContactgegevens() { return contactgegevens; } public void setContactgegevens(Contactgegevens contactgegevens) { this.contactgegevens = contactgegevens; } @Override public DateTime getDatumIngang() { return new DateTime(getDatumTijdInvoer().getLongDate()); } @Override public void setDatumIngang(DateTime dt) { setDAanvr(toBigDecimal(dt.getLongDate())); } @Override public DateTime getDatumTijdInvoer() { return new DateTime(getDAanvr(), getTAanvr()); } @Override public void setDatumTijdInvoer(DateTime dt) { setDAanvr(toBigDecimal(dt.getLongDate())); setTAanvr(toBigDecimal(dt.getLongTime())); } public DateTime getDatumVertrek() { return new DateTime(getDVertrek()); } public void setDatumVertrek(DateTime date) { setDVertrek(toBigDecimal(date.getLongDate())); } public DateTime getDatumVestiging() { return new DateTime(getDVestiging()); } public void setDatumVestiging(DateTime date) { setDVestiging(toBigDecimal(date.getLongDate())); } public UsrFieldValue getGebruikerAanvraag() { return new UsrFieldValue(getUsr().getCUsr(), getUsr().getUsrfullname()); } public void setGebruikerAanvraag(UsrFieldValue gebruiker) { setUsr(new Usr(along(gebruiker.getValue()), gebruiker.getDescription())); } public UsrFieldValue getGebruikerUitgifte() { return new UsrFieldValue(getUsrUitgifte().getCUsr(), getUsrUitgifte().getUsrfullname()); } public void setGebruikerUitgifte(UsrFieldValue gebruiker) { setUsrUitgifte(new Usr(along(gebruiker.getValue()), gebruiker.getDescription())); } @Override public Gemeente getGemeente() { return zaak.getGemeente(); } @Override public void setGemeente(Gemeente gemeente) { zaak.setGemeente(gemeente); } @Override public Identificatie getIdentificatie() { return zaak.getIdentificatie(); } @Override public void setIdentificatie(Identificatie identificatie) { zaak.setIdentificatie(identificatie); } @Override public UsrFieldValue getIngevoerdDoor() { return new UsrFieldValue(getUsr().getCUsr(), getUsr().getUsrfullname()); } @Override public void setIngevoerdDoor(UsrFieldValue ingevoerdDoor) { setUsr(new Usr(along(ingevoerdDoor.getValue()), ingevoerdDoor.getDescription())); } public long getLandVertrek() { return along(getLVertrek()); } public void setLandVertrek(long cLand) { setLVertrek(toBigDecimal(cLand)); } public long getLandVestiging() { return along(getLVestiging()); } public void setLandVestiging(long cLand) { setLVestiging(toBigDecimal(cLand)); } @Override public Locatie getLocatieAfhaal() { return zaak.getLocatieAfhaal(getAfhaalLocation()); } @Override public void setLocatieAfhaal(Locatie locatieAfhaal) { zaak.setLocatieAfhaal(locatieAfhaal); setAfhaalLocation(ReflectionUtil.deepCopyBean(Location.class, locatieAfhaal)); } @Override public Locatie getLocatieInvoer() { return zaak.getLocatieInvoer(getLocation()); } @Override public void setLocatieInvoer(Locatie locatieInvoer) { zaak.setLocatieInvoer(locatieInvoer); setLocation(ReflectionUtil.deepCopyBean(Location.class, locatieInvoer)); } public NaamgebruikType getNaamgebruik() { return NaamgebruikType.getByRdwCode(along(getCNaamgebruik())); } public void setNaamgebruik(NaamgebruikType naamgebruik) { setCNaamgebruik(astr(naamgebruik.getRdwCode())); } public DocumentPL getPersoon() { return zaak.getPersoon(); } public String getProcesVerbaalVerlies() { return getPvVerlies(); } public void setProcesVerbaalVerlies(String procesVerbaalVerlies) { setPvVerlies(procesVerbaalVerlies); } public RijbewijsAanvraagReden getRedenAanvraag() { return RijbewijsAanvraagReden.get(along(getRdnAanvr())); } public void setRedenAanvraag(RijbewijsAanvraagReden redenAanvraag) { setRdnAanvr(toBigDecimal(redenAanvraag.getCode())); } public String getRijbewijsnummer() { String nieuwNr = astr(getRbwNr()); String oudNr = astr(getVervangingsRbwNr()); return (fil(nieuwNr) && nieuwNr.equals(oudNr)) ? "" : getRbwNr(); } public void setRijbewijsnummer(String rijbewijsnummer) { setRbwNr(rijbewijsnummer); } @Override public String getSoort() { return getSoortAanvraag().getOms(); } public RijbewijsAanvraagSoort getSoortAanvraag() { return RijbewijsAanvraagSoort.get(along(getSrtAanvr())); } // Algemene methodes public void setSoortAanvraag(RijbewijsAanvraagSoort soortAanvraag) { setSrtAanvr(toBigDecimal(soortAanvraag.getCode())); } @Override public ZaakStatusType getStatus() { return ZaakStatusType.get(along(getIndVerwerkt())); } @Override public void setStatus(ZaakStatusType status) { setIndVerwerkt(toBigDecimal(status.getCode())); } public RijbewijsAanvraagStatussen getStatussen() { return statussen; } public void setStatussen(RijbewijsAanvraagStatussen statussen) { this.statussen = statussen; } @Override public ZaakType getType() { return ZaakType.RIJBEWIJS; } public String getVervangingsRbwNr() { return getRbwNrVerv(); } public void setVervangingsRbwNr(String vervangingsRbwNr) { setRbwNrVerv(vervangingsRbwNr); } @Override public ZaakHistorie getZaakHistorie() { return zaak.getZaakHistorie(); } public boolean isGbaBestendig() { return isTru(getGbaBest()); } public void setGbaBestendig(boolean gbaBestendig) { setGbaBest(gbaBestendig ? "J" : "N"); } public boolean isIndicatie185() { return isTru(getInd185dagen()); } public void setIndicatie185(boolean indicatie185) { setInd185dagen(indicatie185 ? "J" : "N"); } public boolean isSpoed() { return isTru(getSpoedAfh()); } public void setSpoed(boolean spoed) { setSpoedAfh(spoed ? "J" : "N"); } public VermeldTitelType getVermeldingTitel() { return VermeldTitelType.get(getVermeldTp().intValue()); } public void setVermeldingTitel(VermeldTitelType type) { setVermeldTp(toBigDecimal(type.getCode())); } }
vrijBRP/vrijBRP-Balie
gba-services/src/main/java/nl/procura/gba/web/services/zaken/rijbewijs/RijbewijsAanvraag.java
214,289
/* * Copyright 2020-2021 The Open Zaakbrug Contributors * * Licensed under the EUPL, Version 1.2 or – as soon they will be approved by the * European Commission - subsequent versions of the EUPL (the "Licence"); * * You may not use this work except in compliance with the Licence. * You may obtain a copy of the Licence at: * * https://joinup.ec.europa.eu/software/page/eupl5 * * Unless required by applicable law or agreed to in writing, software distributed under the Licence is distributed on an "AS IS" basis, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the Licence for the specific language governing permissions and limitations under the Licence. */ package nl.haarlem.translations.zdstozgw.config.model; import java.util.List; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; import lombok.Data; @Data public class Configuration { @Expose public String requestHandlerImplementation = null; @Expose public List<Organisatie> organisaties = null; @Expose public ZgwRolOmschrijving zgwRolOmschrijving = null; @Expose public List<ZaaktypeMetCoalesceResultaat> beeindigZaakWanneerEinddatum = null; @Expose public List<ZaaktypeMetCoalesceResultaat> einddatumEnResultaatWanneerLastStatus = null; @Expose public List<TranslateVerblijfsadresForZaaktype> translateVerblijfsadresForZaaktype = null; @Expose public Replication replication = null; @Expose public List<Translation> translations = null; public String getTranslationsString() { String combinations = ""; for (Translation t : this.getTranslations()) { combinations += "\n\tpath: './" + t.getPath() + "' soapaction: '" + t.getSoapaction() + "'"; } return combinations; } }
Sudwest-Fryslan/OpenZaakBrug
src/main/java/nl/haarlem/translations/zdstozgw/config/model/Configuration.java
214,291
/* * SPDX-FileCopyrightText: 2023 Atos * SPDX-License-Identifier: EUPL-1.2+ */ package net.atos.client.brp.util; import java.lang.reflect.Type; import javax.json.JsonObject; import javax.json.bind.Jsonb; import javax.json.bind.JsonbBuilder; import javax.json.bind.JsonbConfig; import javax.json.bind.serializer.DeserializationContext; import javax.json.bind.serializer.JsonbDeserializer; import javax.json.stream.JsonParser; import net.atos.client.brp.model.AbstractVerblijfplaats; import net.atos.client.brp.model.Adres; import net.atos.client.brp.model.Locatie; import net.atos.client.brp.model.VerblijfplaatsBuitenland; import net.atos.client.brp.model.VerblijfplaatsOnbekend; public class AbstractVerblijfplaatsJsonbDeserializer implements JsonbDeserializer<AbstractVerblijfplaats> { private static final Jsonb JSONB = JsonbBuilder.create( new JsonbConfig().withPropertyVisibilityStrategy(new FieldPropertyVisibilityStrategy())); @Override public AbstractVerblijfplaats deserialize(final JsonParser parser, final DeserializationContext ctx, final Type rtType) { final JsonObject jsonObject = parser.getObject(); final String type = jsonObject.getString("type"); return switch (type) { case "VerblijfplaatsBuitenland" -> JSONB.fromJson(jsonObject.toString(), VerblijfplaatsBuitenland.class); case "Adres" -> JSONB.fromJson(jsonObject.toString(), Adres.class); case "VerblijfplaatsOnbekend" -> JSONB.fromJson(jsonObject.toString(), VerblijfplaatsOnbekend.class); case "Locatie" -> JSONB.fromJson(jsonObject.toString(), Locatie.class); default -> throw new RuntimeException("Type '%s' wordt niet ondersteund".formatted(type)); }; } }
NL-AMS-LOCGOV/zaakafhandelcomponent
src/main/java/net/atos/client/brp/util/AbstractVerblijfplaatsJsonbDeserializer.java
214,292
package com.magictool.web.util; import org.apache.commons.lang3.time.DateFormatUtils; import org.apache.commons.lang3.time.DateUtils; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; /** * Time tool class * * @author lijf */ public class DateUtil extends DateUtils { /** * 计算两次时间差,返回“xx , xx , xx ” * 建议使用replaceAll() 方法用逗号分隔得到类似的“xx 日 xx 小时 xx 分钟” 格式 * * @param endDate 结束时间 * @param startDate 开始时间 * @return String */ public static String getDatePoor(Date endDate, Date startDate) { long nd = 1000 * 24 * 60 * 60L; long nh = 1000 * 60 * 60L; long nm = 1000 * 60L; // 获得两个时间的毫秒时间差异 long diff = endDate.getTime() - startDate.getTime(); long day = diff / nd; long hour = diff % nd / nh; long min = diff % nd % nh / nm; if (day < 0 && hour < 0 && min < 0) { return null; } return day + "," + hour + "," + min + ","; } /** * 计算两个日期之间的天数并返回 * * @param endDate 结束时间 * @param startDate 开始时间 * @return Integer */ public static Integer getDatePoorAge(Date endDate, Date startDate) { long nd = 1000 * 24 * 60 * 60L; long nh = 1000 * 60 * 60L; long nm = 1000 * 60L; long diff = endDate.getTime() - startDate.getTime(); long day = diff / nd; long hour = diff % nd / nh; long min = diff % nd % nh / nm; if (day < 0 && hour < 0 && min < 0) { return null; } return (int) day; } }
james-ljf/magic-tool
src/main/java/com/magictool/web/util/DateUtil.java
214,293
package com.magictool.web.util; import org.springframework.util.CollectionUtils; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.function.Function; /** * 集合处理工具 * @author lijf */ public class ListUtils { /** * 根据集合范型的属性删除集合中的重复元素 * @param list 集合 * @param function such as:User::getUId */ public static <T,E> void removeElement(List<T> list, Function<T,E> function){ if (CollectionUtils.isEmpty(list)){ return; } Set<E> set = new HashSet<>(); list.removeIf(e -> function.apply(e) != null && !set.add(function.apply(e))); } }
james-ljf/magic-tool
src/main/java/com/magictool/web/util/ListUtils.java
214,295
package com.syntax.class17; public class IntellijFeatures3 { public static void main(String[] args) { int [] arr={10,20,30,40,50}; for (int j : arr) { System.out.println(j); } } }
mrdagdemir/Class17
IntellijFeatures3.java
214,296
package com.xkj.mlrc.clean.util; import com.xkj.mlrc.clean.domain.ParamOption; import org.kohsuke.args4j.CmdLineException; import org.kohsuke.args4j.CmdLineParser; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @Author: [email protected] * @Date: 2018/8/22 18:33 * @Version: 1.0 */ public class ArgsUtil { private static Logger logger = LoggerFactory.getLogger(ArgsUtil.class); static CmdLineParser parser; private ArgsUtil() {} /** * 解析参数 * @param args * @return */ public static ParamOption getOption(String[] args){ //开始解析命令参数 ParamOption option = new ParamOption(); parser = new CmdLineParser(option); try { parser.parseArgument(args); } catch (CmdLineException e) { logger.error(e.toString(),e); } return option; } /** * 参数说明 */ public static void showHelp(){ parser.printUsage(System.out); } }
lijufeng2016/data-manager
src/main/java/com/xkj/mlrc/clean/util/ArgsUtil.java
214,297
package com.magictool.web.entity; import com.magictool.web.entity.dto.Code; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; import java.io.Serializable; import java.util.Map; /** * @author lijf */ @Data @Accessors(chain = true) @AllArgsConstructor @NoArgsConstructor public class Response<T> implements Serializable { private static final long serialVersionUID = 7390569824082954874L; /** * 自定义业务状态码,8888表示请求成功,非8888则表示请求异常 */ private String code; /** * 错误信息,调用成功则为空 */ private String msg; /** * 调用是否成功,true成功,false异常 */ private boolean isSuccess; /** * 返回的结果 * 不进行序列化 */ private transient T result; /** * 拓展信息 * 不进行序列化 */ private transient Map<String, Object> expandInfo; public static <T> Response<T> success(T result){ return generateResponse(true, Code.SUCCESS, result); } public static <T> Response<T> fail(String code, String msg) { return fail(Code.business(code, msg)); } public static <T> Response<T> fail(Code code) { return generateResponse(false, code, null); } private static <T> Response<T> generateResponse(boolean isSuccess, Code code, T result){ Response<T> response = new Response<>(); response.setCode(code.getCode()) .setMsg(code.getMsg()) .setResult(result) .setSuccess(isSuccess); return response; } @Override public String toString() { return "Response{" + "code='" + code + '\'' + ", msg='" + msg + '\'' + ", isSuccess=" + isSuccess + ", result=" + result + '}'; } }
james-ljf/magic-tool
src/main/java/com/magictool/web/entity/Response.java
214,298
package com.xkj.mlrc.clean.util; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.util.Properties; /** * 获取系统配置的工具类 * * @author [email protected] * @return */ public final class PropsUtil { private static Properties props = null; private static Logger logger = LoggerFactory.getLogger(PropsUtil.class); static { try { props = new Properties(); props.load(PropsUtil.class.getClassLoader().getResourceAsStream("config.properties")); } catch (IOException e) { logger.error(e.toString()); } } private PropsUtil() { } /** * 获取配置 * * @param key key * @return value */ public static String getProp(String key) { if (props != null) { return props.getProperty(key); } return null; } }
lijufeng2016/data-manager
src/main/java/com/xkj/mlrc/clean/util/PropsUtil.java
214,299
package com.xkj.mlrc.clean.domain; /** * 日志对象 * @author [email protected] * @date 2020/4/21 14:09 * @desc */ public class LogBean { String path; Integer replication; String modificationtime; String accesstime; Long preferredblocksize; Integer blockscount; Long filesize; Integer nsquota; Integer dsquota; String permission; String username; String groupname; }
lijufeng2016/data-manager
src/main/java/com/xkj/mlrc/clean/domain/LogBean.java
214,300
/* * The MIT License (MIT) * * Copyright (c) 2018 Chris Magnussen and Elior Boukhobza * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. * * */ package com.chrisrm.idea; import com.intellij.ide.plugins.PluginManagerConfigurable; import com.intellij.openapi.components.BaseComponent; import com.intellij.openapi.wm.impl.ToolWindowImpl; import com.intellij.ui.CaptionPanel; import com.intellij.util.ui.JBSwingUtilities; import javassist.*; import javassist.expr.ExprEditor; import javassist.expr.MethodCall; import javassist.expr.NewExpr; import org.jetbrains.annotations.NonNls; @SuppressWarnings({"StandardVariableNames", "CallToSuspiciousStringMethod", "HardCodedStringLiteral", "DuplicateStringLiteralInspection"}) public final class MTHackComponent implements BaseComponent { static { hackTitleLabel(); hackSpeedSearch(); // hackFlatWelcomeFrame(); hackPluginManagerNew(); hackIntelliJFailures(); } /** * Fix fatal error introduced by intellij */ private static void hackIntelliJFailures() { try { final ClassPool cp = new ClassPool(true); cp.insertClassPath(new ClassClassPath(JBSwingUtilities.class)); final CtClass ctClass2 = cp.get("com.intellij.util.IJSwingUtilities"); final CtMethod method = ctClass2.getDeclaredMethod("updateComponentTreeUI"); method.instrument(new ExprEditor() { @Override public void edit(final MethodCall m) throws CannotCompileException { if ("decorateWindowHeader".equals(m.getMethodName())) { m.replace("{ }"); } } }); ctClass2.toClass(); } catch (final CannotCompileException | NotFoundException e) { e.printStackTrace(); } } @SuppressWarnings("OverlyComplexAnonymousInnerClass") private static void hackPluginManagerNew() { try { final ClassPool cp = new ClassPool(true); cp.insertClassPath(new ClassClassPath(PluginManagerConfigurable.class)); // 1: Hack Plugin Groups color final CtClass ctClass = cp.get("com.intellij.ide.plugins.newui.PluginsGroupComponent"); final CtMethod addGroup = ctClass.getDeclaredMethod("addGroup", new CtClass[]{ cp.get("com.intellij.ide.plugins.newui.PluginsGroup"), cp.get("java.util.List"), cp.get("int") }); addGroup.instrument(new ExprEditor() { @Override public void edit(final MethodCall m) throws CannotCompileException { if ("setForeground".equals(m.getMethodName())) { final String fgColor = "javax.swing.UIManager.getColor(\"List.foreground\")"; m.replace(String.format("{ $1 = %s; $_ = $proceed($$); }", fgColor)); } } @Override public void edit(final NewExpr e) throws CannotCompileException { if (e.getClassName().contains("OpaquePanel")) { final String bgColor = "javax.swing.UIManager.getColor(\"List.background\")"; e.replace(String.format("{ $2 = %s; $_ = $proceed($$); }", bgColor)); } } }); ctClass.toClass(); // 2. Hack plugin tags color final CtClass ctClass2 = cp.get("com.intellij.ide.plugins.newui.TagComponent"); final CtMethod method = ctClass2.getDeclaredMethod("paintComponent"); method.instrument(new ExprEditor() { @Override public void edit(final MethodCall m) throws CannotCompileException { if ("setColor".equals(m.getMethodName())) { final String bgColor = "javax.swing.UIManager.getColor(\"Button.mt.background\")"; m.replace(String.format("{ $1 = %s; $proceed($$); }", bgColor)); } } }); ctClass2.toClass(); } catch (final CannotCompileException | NotFoundException e) { e.printStackTrace(); } } /** * For better dialog titles (since I have no idea how to know when dialogs appear, I can't attach events so I'm directly hacking * the source code). I hate doing this. */ private static void hackTitleLabel() { // Hack method try { @NonNls final ClassPool cp = new ClassPool(true); cp.insertClassPath(new ClassClassPath(CaptionPanel.class)); final CtClass ctClass = cp.get("com.intellij.ui.TitlePanel"); final CtConstructor declaredConstructor = ctClass.getDeclaredConstructor(new CtClass[]{ cp.get("javax.swing.Icon"), cp.get("javax.swing.Icon")}); declaredConstructor.instrument(new ExprEditor() { @Override public void edit(final MethodCall m) throws CannotCompileException { final String s = m.getMethodName(); if ("setHorizontalAlignment".equals(s)) { // Set title at the left m.replace("{ $1 = javax.swing.SwingConstants.LEFT; $_ = $proceed($$); }"); } else if ("setBorder".equals(s)) { // Bigger heading m.replace("{ $_ = $proceed($$); myLabel.setFont(myLabel.getFont().deriveFont(1, com.intellij.util.ui.JBUI.scale(16.0f))); }"); } } }); final CtMethod getPreferredSize = ctClass.getDeclaredMethod("getPreferredSize"); getPreferredSize.instrument(new ExprEditor() { @Override public void edit(final MethodCall m) throws CannotCompileException { if ("headerHeight".equals(m.getMethodName())) { // Set title at the left m.replace("{ $_ = 40; }"); } } }); ctClass.toClass(); } catch (final CannotCompileException | NotFoundException e) { e.printStackTrace(); } } /** * Fix Speed Search (typing into dialogs) color */ private static void hackSpeedSearch() { // Hack method try { @NonNls final ClassPool cp = new ClassPool(true); cp.insertClassPath(new ClassClassPath(ToolWindowImpl.class)); final CtClass ctClass = cp.get("com.intellij.ui.SpeedSearchBase$SearchPopup"); final CtConstructor declaredConstructor = ctClass.getDeclaredConstructors()[0]; declaredConstructor.instrument(new ExprEditor() { @Override public void edit(final MethodCall m) throws CannotCompileException { if ("setBackground".equals(m.getMethodName())) { final String bgColor = "com.intellij.util.ui.UIUtil.getToolTipBackground().brighter();"; m.replace(String.format("{ $1 = %s; $proceed($$); }", bgColor)); } else if ("setBorder".equals(m.getMethodName())) { final String borderColor = "null"; m.replace(String.format("{ $1 = %s; $proceed($$); }", borderColor)); } } }); ctClass.toClass(); } catch (final CannotCompileException | NotFoundException e) { e.printStackTrace(); } } }
jefersonla/material-theme-jetbrains
src/main/java/com/chrisrm/idea/MTHackComponent.java
214,301
package saros.intellij.filesystem; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.util.ThrowableComputable; import com.intellij.openapi.vfs.VirtualFile; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.file.FileAlreadyExistsException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import saros.filesystem.IFile; import saros.filesystem.IFolder; import saros.filesystem.IResource; import saros.intellij.runtime.FilesystemRunner; import saros.util.PathUtils; /** Intellij implementation of the Saros folder interface. */ public class IntellijFolder extends AbstractIntellijResource implements IFolder { private static final Logger log = Logger.getLogger(IntellijFolder.class); public IntellijFolder( @NotNull IntellijReferencePoint referencePoint, @NotNull Path relativePath) { super(referencePoint, relativePath); } @Override public boolean exists() { if (!referencePoint.exists()) { return false; } VirtualFile virtualFile = getVirtualFile(); return existsInternal(virtualFile); } /** * whether the given virtual file is not <code>null</code>, exists, and is a directory. * * @param virtualFile the virtual file to check * @return whether the given virtual file is not <code>null</code>, exists, and is a directory */ private static boolean existsInternal(@Nullable VirtualFile virtualFile) { return virtualFile != null && virtualFile.exists() && virtualFile.isDirectory(); } @Override public boolean exists(@NotNull Path path) { return referencePoint.exists(relativePath.resolve(path)); } @Override @NotNull public List<IResource> members() throws IOException { VirtualFile folder = getVirtualFile(); if (folder == null || !folder.exists()) { throw new FileNotFoundException( "Could not obtain child resources for " + this + " as it does not exist or is not valid"); } if (!folder.isDirectory()) { throw new IOException( "Could not obtain child resources for " + this + " as it is not a directory."); } List<IResource> result = new ArrayList<>(); VirtualFile[] children = folder.getChildren(); for (VirtualFile child : children) { Path childPath = relativePath.resolve(child.getName()); result.add( child.isDirectory() ? new IntellijFolder(referencePoint, childPath) : new IntellijFile(referencePoint, childPath)); } return result; } @Override @NotNull public IFile getFile(@NotNull String pathString) { return getFile(Paths.get(pathString)); } @Override @NotNull public IFile getFile(@NotNull Path path) { if (PathUtils.isEmpty(path)) { throw new IllegalArgumentException("Can not create file handle for an empty path"); } Path referencePointRelativeChildPath = relativePath.resolve(path); return new IntellijFile(referencePoint, referencePointRelativeChildPath); } @Override @NotNull public IFolder getFolder(@NotNull String pathString) { return getFolder(Paths.get(pathString)); } @Override @NotNull public IFolder getFolder(@NotNull Path path) { if (PathUtils.isEmpty(path)) { throw new IllegalArgumentException("Can not create folder handle for an empty path"); } Path referencePointRelativeChildPath = relativePath.resolve(path); return new IntellijFolder(referencePoint, referencePointRelativeChildPath); } @Override public void delete() throws IOException { FilesystemRunner.runWriteAction( (ThrowableComputable<Void, IOException>) () -> { deleteInternal(); return null; }, ModalityState.defaultModalityState()); } /** * Deletes the folder in the filesystem. * * @throws IOException if the resource is a file or the deletion failed * @see VirtualFile#delete(Object) */ private void deleteInternal() throws IOException { VirtualFile virtualFile = getVirtualFile(); if (virtualFile == null || !virtualFile.exists()) { log.debug("Ignoring file deletion request for " + this + " as folder does not exist"); return; } if (!virtualFile.isDirectory()) { throw new IOException("Failed to delete " + this + " as it is not a folder"); } virtualFile.delete(IntellijFolder.this); } @Override public void create() throws IOException { FilesystemRunner.runWriteAction( (ThrowableComputable<Void, IOException>) () -> { createInternal(); return null; }, ModalityState.defaultModalityState()); } /** * Creates the folder in the local filesystem. * * @throws FileAlreadyExistsException if a resource with the same name already exists * @throws FileNotFoundException if the parent directory of the folder does not exist */ private void createInternal() throws IOException { IResource parent = getParent(); VirtualFile parentFile = referencePoint.findVirtualFile(parent.getReferencePointRelativePath()); if (parentFile == null || !parentFile.exists()) { throw new FileNotFoundException( "Could not create " + this + " as its parent folder " + parent + " does not exist or is not valid"); } VirtualFile virtualFile = parentFile.findChild(getName()); if (virtualFile != null && virtualFile.exists()) { throw new FileAlreadyExistsException( "Could not create " + this + " as a resource with the same name already exists: " + virtualFile); } parentFile.createChildDirectory(this, getName()); } }
saros-project/saros
intellij/src/saros/intellij/filesystem/IntellijFolder.java
214,302
package com.alibaba.datax.plugin.writer.rediswriter; import com.alibaba.datax.common.exception.CommonErrorCode; import com.alibaba.datax.common.exception.DataXException; import com.alibaba.datax.common.plugin.RecordReceiver; import com.alibaba.datax.common.util.Configuration; import org.apache.commons.lang3.StringUtils; import redis.clients.jedis.PipelineBase; /** * @author [email protected] * @date 2020/5/19 15:56 * @desc 写redis对象抽象类 */ public abstract class RedisWriteAbstract { protected Configuration configuration; protected PipelineBase pipelined; Object redisClient; protected int records; protected String keyPreffix; protected String keySuffix; protected String valuePreffix; protected String valueSuffix; protected Integer batchSize; protected Integer expire; protected String strKey; protected Integer keyIndex; protected Integer valueIndex; public RedisWriteAbstract(Configuration configuration) { this.configuration = configuration; } public PipelineBase getRedisPipelineBase(Configuration configuration) { String mode = configuration.getNecessaryValue(Key.REDISMODE, CommonErrorCode.CONFIG_ERROR); String addr = configuration.getNecessaryValue(Key.ADDRESS, CommonErrorCode.CONFIG_ERROR); String auth = configuration.getString(Key.AUTH); if (Constant.CLUSTER.equalsIgnoreCase(mode)) { redisClient = RedisWriterHelper.getJedisCluster(addr, auth); } else { redisClient = RedisWriterHelper.getJedis(addr, auth); } return RedisWriterHelper.getPipeLine(redisClient); } /** * 初始化公共参数 */ public void initCommonParams() { Configuration detailConfig = this.configuration.getConfiguration(Key.CONFIG); batchSize = detailConfig.getInt(Key.BATCH_SIZE, 1000); keyPreffix = detailConfig.getString(Key.KEY_PREFIX, ""); keySuffix = detailConfig.getString(Key.KEY_SUFFIX, ""); valuePreffix = detailConfig.getString(Key.VALUE_PREFIX, ""); valueSuffix = detailConfig.getString(Key.VALUE_SUFFIX, ""); expire = detailConfig.getInt(Key.EXPIRE, Integer.MAX_VALUE); pipelined = getRedisPipelineBase(configuration); } /** * 检查和解析参数 */ public void checkAndGetParams() { Configuration detailConfig = configuration.getConfiguration(Key.CONFIG); String colKey = detailConfig.getString(Key.COLKEY, null); String strKey = detailConfig.getString(Key.STRING_KEY, null); if ((StringUtils.isBlank(colKey) && StringUtils.isBlank(strKey))) { throw DataXException.asDataXException(CommonErrorCode.CONFIG_ERROR, "strKey或colKey不能为空!请检查配置"); } if ((StringUtils.isNotBlank(colKey) && StringUtils.isNotBlank(strKey))) { throw DataXException.asDataXException(CommonErrorCode.CONFIG_ERROR, "strKey或colKey不能同时存在!请检查配置"); } if (StringUtils.isNotBlank(colKey)) { keyIndex = detailConfig.getConfiguration(Key.COLKEY).getInt(Key.COL_INDEX); } else { this.strKey = strKey; } String colValue = detailConfig.getString(Key.COLVALUE, null); if (StringUtils.isNotBlank(colKey) && StringUtils.isBlank(colValue)) { throw DataXException.asDataXException(CommonErrorCode.CONFIG_ERROR, "colValue不能为空!请检查配置"); } String writeType = configuration.getString(Key.WRITE_TYPE); // hash类型的colValue配置里面有多个column,要考虑排除获取valueIndex,HashTypeWriter子类单独处理 if (!Constant.WRITE_TYPE_HASH.equalsIgnoreCase(writeType)) { valueIndex = detailConfig.getConfiguration(Key.COLVALUE).getInt(Key.COL_INDEX); } } /** * 把数据add到pipeline * * @param lineReceiver PipelineBase */ public abstract void addToPipLine(RecordReceiver lineReceiver); /** * 正式写入数据到redis */ public void syscData() { if (records >= batchSize) { RedisWriterHelper.syscData(pipelined); records = 0; } } public void syscAllData() { RedisWriterHelper.syscData(pipelined); } /** * 关闭资源 */ public void close() { RedisWriterHelper.syscData(pipelined); RedisWriterHelper.close(redisClient); } }
lijufeng2016/DataX
rediswriter/src/main/java/com/alibaba/datax/plugin/writer/rediswriter/RedisWriteAbstract.java
214,303
package com.magictool.web.convert; import org.springframework.beans.BeanUtils; import java.util.ArrayList; import java.util.List; import java.util.function.Supplier; /** * 集合类型实体类bean的转换工具 * @author lijf */ public class BeanConvert extends BeanUtils { /** * 集合数据的拷贝,需字段类型对应 * @param sources: 数据源类 * @param target: 目标类::new * @return List<T> */ public static <S, T> List<T> copyList(List<S> sources, Supplier<T> target) { List<T> list = new ArrayList<>(sources.size()); for (S source : sources) { T t = target.get(); copyProperties(source, t); list.add(t); } return list; } /** * 范型不同集合类转换 * @param list 需要被转换的集合 * @param clazz 需要转换成的类(如:User.class) * @return List<T> */ public static <T> List<T> copyList(List<?> list, Class<T> clazz) { List<T> result = new ArrayList<>(list.size()); for (Object source : list) { T target; try { target = clazz.getDeclaredConstructor().newInstance(); } catch (Exception e) { throw new RuntimeException(); } BeanUtils.copyProperties(source, target); result.add(target); } return result; } }
james-ljf/magic-tool
src/main/java/com/magictool/web/convert/BeanConvert.java
214,304
/******************************************************************************* * Copyright (c) 2020 Red Hat, Inc. * Distributed under license by Red Hat, Inc. All rights reserved. * This program is made available under the terms of the * Eclipse Public License v2.0 which accompanies this distribution, * and is available at https://www.eclipse.org/legal/epl-v20.html * * Contributors: * Red Hat, Inc. - initial API and implementation ******************************************************************************/ package org.jboss.tools.intellij.quarkus.utils; import com.intellij.remoterobot.RemoteRobot; import com.intellij.remoterobot.fixtures.ComponentFixture; import com.intellij.remoterobot.fixtures.ContainerFixture; import com.intellij.remoterobot.fixtures.dataExtractor.RemoteText; import com.intellij.remoterobot.utils.Keyboard; import com.intellij.remoterobot.utils.WaitForConditionTimeoutException; import org.apache.commons.io.FileUtils; import org.jboss.tools.intellij.quarkus.fixtures.dialogs.IdeFatalErrorsDialogFixture; import org.jboss.tools.intellij.quarkus.fixtures.dialogs.TipOfTheDayDialogFixture; import org.jboss.tools.intellij.quarkus.fixtures.dialogs.WelcomeFrameDialogFixture; import org.jboss.tools.intellij.quarkus.fixtures.mainIdeWindow.CustomHeaderMenuBarFixture; import org.jboss.tools.intellij.quarkus.fixtures.mainIdeWindow.IdeStatusBarFixture; import org.jboss.tools.intellij.quarkus.fixtures.mainIdeWindow.LinuxIdeMenuBarFixture; import org.jboss.tools.intellij.quarkus.fixtures.popups.SearchEverywherePopupFixture; import javax.imageio.ImageIO; import java.awt.AWTException; import java.awt.image.BufferedImage; import java.awt.Rectangle; import java.awt.Robot; import java.awt.Toolkit; import java.awt.event.KeyEvent; import java.io.File; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.nio.file.Files; import java.nio.file.Paths; import java.time.Duration; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.List; import java.util.Locale; import static com.intellij.remoterobot.search.locators.Locators.byXpath; import static com.intellij.remoterobot.stepsProcessing.StepWorkerKt.step; import static com.intellij.remoterobot.utils.RepeatUtilsKt.waitFor; import static org.jboss.tools.intellij.quarkus.utils.HelperUtils.listOfRemoteTextToString; /** * Static utilities that assist and simplify manipulation with the IDE and with the project * * @author [email protected] */ public class GlobalUtils { public static String projectPath = ""; public static RemoteRobot getRemoteRobotConnection(int port) throws InterruptedException { RemoteRobot remoteRobot = new RemoteRobot("http://127.0.0.1:" + port); for (int i = 0; i < 60; i++) { try { remoteRobot.find(WelcomeFrameDialogFixture.class); } catch (Exception ex) { Thread.sleep(1000); } } return remoteRobot; } public static void closeTheTipOfTheDayDialogIfItAppears(RemoteRobot remoteRobot) { step("Close the 'Tip of the Day' Dialog", () -> { try { final TipOfTheDayDialogFixture tipOfTheDayDialogFixture = remoteRobot.find(TipOfTheDayDialogFixture.class, Duration.ofSeconds(20)); tipOfTheDayDialogFixture.button("Close").click(); } catch (WaitForConditionTimeoutException e) { e.printStackTrace(); } }); } public static void waitUntilTheProjectImportIsComplete(RemoteRobot remoteRobot) { step("Wait until the project import is complete", () -> { waitFor(Duration.ofSeconds(300), Duration.ofSeconds(5), "The project import did not finish in 5 minutes.", () -> didTheProjectImportFinish(remoteRobot)); }); } public static void maximizeTheIdeWindow(RemoteRobot remoteRobot) { step("Maximize the IDE window", () -> { ComponentFixture cf = remoteRobot.find(ComponentFixture.class, byXpath("//div[@class='IdeFrameImpl']")); cf.runJs("const horizontal_offset = component.getWidth()/2;\n" + "robot.click(component, new Point(horizontal_offset, 10), MouseButton.LEFT_BUTTON, 2);"); }); } public static void waitUntilAllTheBgTasksFinish(RemoteRobot remoteRobot) { step("Wait until all the background tasks finish", () -> { waitFor(Duration.ofSeconds(300), Duration.ofSeconds(15), "The background tasks did not finish in 5 minutes.", () -> didAllTheBgTasksFinish(remoteRobot)); }); } public static void checkForExceptions(RemoteRobot remoteRobot) { step("Check for exceptions and other errors", () -> { try { final WelcomeFrameDialogFixture welcomeFrameDialogFixture = remoteRobot.find(WelcomeFrameDialogFixture.class, Duration.ofSeconds(10)); welcomeFrameDialogFixture.ideErrorsIcon().click(); } catch (WaitForConditionTimeoutException e) { e.printStackTrace(); return; } final IdeFatalErrorsDialogFixture ideFatalErrorsDialogFixture = remoteRobot.find(IdeFatalErrorsDialogFixture.class, Duration.ofSeconds(10)); String exceptionNumberLabel = ideFatalErrorsDialogFixture.numberOfExcetionsJBLabel().findAllText().get(0).getText(); int numberOfExceptions = Integer.parseInt(exceptionNumberLabel.substring(5)); for (int i = 0; i < numberOfExceptions; i++) { String exceptionStackTrace = HelperUtils.listOfRemoteTextToString(ideFatalErrorsDialogFixture.exceptionDescriptionJTextArea().findAllText()); if (i + 1 < numberOfExceptions) { ideFatalErrorsDialogFixture.nextExceptionButton().click(); } } ideFatalErrorsDialogFixture.button("Clear all").click(); }); } public static void closeTheProject(RemoteRobot remoteRobot) { step("Close the project that is currently open", () -> { ComponentFixture cf = remoteRobot.find(ComponentFixture.class, byXpath("//div[@class='IdeFrameImpl']")); if (remoteRobot.isMac()) { cf.runJs("robot.click(component, new Point(15, 10), MouseButton.LEFT_BUTTON, 1);"); } else if (remoteRobot.isWin()) { CustomHeaderMenuBarFixture chmb = remoteRobot.find(CustomHeaderMenuBarFixture.class, Duration.ofSeconds(10)); chmb.mainMenuItem("File").click(); List<ContainerFixture> allHeavyWeightWindows = remoteRobot.findAll(ContainerFixture.class, byXpath("//div[@class='HeavyWeightWindow']")); ContainerFixture lastHeavyWeightWindow = allHeavyWeightWindows.get(allHeavyWeightWindows.size() - 1); ComponentFixture closeProjectButtonFixture = lastHeavyWeightWindow.find(ComponentFixture.class, byXpath("//div[@accessiblename='Close Project' and @text='Close Project']")); closeProjectButtonFixture.click(); } else { LinuxIdeMenuBarFixture limb = remoteRobot.find(LinuxIdeMenuBarFixture.class, Duration.ofSeconds(10)); limb.mainMenuItem("File").click(); List<ContainerFixture> allHeavyWeightWindows = remoteRobot.findAll(ContainerFixture.class, byXpath("//div[@class='HeavyWeightWindow']")); ContainerFixture lastHeavyWeightWindow = allHeavyWeightWindows.get(allHeavyWeightWindows.size() - 1); ComponentFixture closeProjectButtonFixture = lastHeavyWeightWindow.find(ComponentFixture.class, byXpath("//div[@accessiblename='Close Project' and @text='Close Project']")); closeProjectButtonFixture.click(); } final WelcomeFrameDialogFixture welcomeFrameDialogFixture = remoteRobot.find(WelcomeFrameDialogFixture.class, Duration.ofSeconds(10)); welcomeFrameDialogFixture.runJs("const horizontal_offset = component.getWidth()/2;\n" + "robot.click(component, new Point(horizontal_offset, 10), MouseButton.LEFT_BUTTON, 1);"); }); } public static void clearTheWorkspace(RemoteRobot remoteRobot) { step("Delete all the projects in the workspace", () -> { // delete all the projects' links from the 'Welcome to IntelliJ IDEA' dialog int numberOfLinks = getNumberOfProjectLinks(remoteRobot); for (int i = 0; i < numberOfLinks; i++) { final WelcomeFrameDialogFixture welcomeFrameDialogFixture = remoteRobot.find(WelcomeFrameDialogFixture.class, Duration.ofSeconds(10)); ComponentFixture cf = welcomeFrameDialogFixture.find(ComponentFixture.class, byXpath("//div[@accessiblename='Recent Projects' and @class='MyList']")); cf.runJs("const horizontal_offset = component.getWidth()-22;\n" + "robot.click(component, new Point(horizontal_offset, 22), MouseButton.LEFT_BUTTON, 1);"); } // delete all the files and folders in the IdeaProjects folder try { String pathToDirToMakeEmpty = System.getProperty("user.home") + File.separator + "IdeaProjects"; boolean doesTheProjectDirExists = Files.exists(Paths.get(pathToDirToMakeEmpty)); if (doesTheProjectDirExists) { FileUtils.cleanDirectory(new File(pathToDirToMakeEmpty)); } else { Files.createDirectory(Paths.get(pathToDirToMakeEmpty)); } } catch (IOException e) { e.printStackTrace(); } }); } public static void quitIntelliJFromTheWelcomeDialog(RemoteRobot remoteRobot) { step("Quit IntelliJ Idea from the 'Welcome To IntelliJ IDEA' dialog", () -> { WelcomeFrameDialogFixture welcomeFrameDialogFixture = remoteRobot.find(WelcomeFrameDialogFixture.class); if (remoteRobot.isMac()) { welcomeFrameDialogFixture.runJs("robot.click(component, new Point(15, 10), MouseButton.LEFT_BUTTON, 1);"); } else if (remoteRobot.isWin()) { welcomeFrameDialogFixture.runJs("const horizontal_offset = component.getWidth()-24;\n" + "robot.click(component, new Point(horizontal_offset, 18), MouseButton.LEFT_BUTTON, 1);"); } else { welcomeFrameDialogFixture.runJs("const horizontal_offset = component.getWidth()-18;\n" + "robot.click(component, new Point(horizontal_offset, 18), MouseButton.LEFT_BUTTON, 1);"); } }); } public static IdeaVersion getTheIntelliJVersion(RemoteRobot remoteRobot) { WelcomeFrameDialogFixture welcomeFrameDialogFixture = remoteRobot.find(WelcomeFrameDialogFixture.class); List<ComponentFixture> jLabels = welcomeFrameDialogFixture.findAll(ComponentFixture.class, byXpath("//div[@class='JLabel']")); IdeaVersion ideaVersion = IdeaVersion.UNIDENTIFIED; for (ComponentFixture jLabel : jLabels) { String labelText = listOfRemoteTextToString(jLabel.findAllText()).toLowerCase(Locale.ROOT); if (labelText.contains("20")) { if (labelText.contains("2020.1")) { ideaVersion = IdeaVersion.V2020_1; } else if (labelText.contains("2020.2")) { ideaVersion = IdeaVersion.V2020_2; } break; } } return ideaVersion; } public enum IdeaVersion { V2020_1, V2020_2, UNIDENTIFIED } public static void takeScreenshot() { String screenshotLocation = "./build/screenshots/"; String screenshotFilename = getTimeNowAsString("yyyy_MM_dd_HH_mm_ss"); String filetype = "png"; String screenshotPathname = screenshotLocation + screenshotFilename + "." + filetype; try { BufferedImage screenshotBufferedImage = getScreenshotAsBufferedImage(); boolean doesTheScreenshotDirExists = Files.exists(Paths.get(screenshotLocation)); if (!doesTheScreenshotDirExists) { Files.createDirectory(Paths.get(screenshotLocation)); } File screenshotFile = new File(screenshotPathname); ImageIO.write(screenshotBufferedImage, filetype, screenshotFile); } catch (AWTException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } private static BufferedImage getScreenshotAsBufferedImage() throws AWTException { Rectangle fullscreenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize()); BufferedImage screenshot = new Robot().createScreenCapture(fullscreenRect); return screenshot; } private static String getTimeNowAsString(String format) { DateTimeFormatter dtf = DateTimeFormatter.ofPattern(format); LocalDateTime now = LocalDateTime.now(); return dtf.format(now); } private static boolean didTheProjectImportFinish(RemoteRobot remoteRobot) { try { remoteRobot.find(ComponentFixture.class, byXpath("//div[@class='EngravedLabel']")); } catch (WaitForConditionTimeoutException e) { return true; } return false; } private static boolean didAllTheBgTasksFinish(RemoteRobot remoteRobot) { for (int i = 0; i < 5; i++) { final IdeStatusBarFixture ideStatusBarFixture = remoteRobot.find(IdeStatusBarFixture.class); List<RemoteText> inlineProgressPanelContent = ideStatusBarFixture.inlineProgressPanel().findAllText(); if (!inlineProgressPanelContent.isEmpty()) { return false; } try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } return true; } private static int getNumberOfProjectLinks(RemoteRobot remoteRobot) { final WelcomeFrameDialogFixture welcomeFrameDialogFixture = remoteRobot.find(WelcomeFrameDialogFixture.class, Duration.ofSeconds(10)); try { ComponentFixture cf = welcomeFrameDialogFixture.find(ComponentFixture.class, byXpath("//div[@accessiblename='Recent Projects' and @class='MyList']")); int numberOfProjectsLinks = cf.findAllText().size() / 2; // 2 items per 1 project link (project path and project name) return numberOfProjectsLinks; } catch (WaitForConditionTimeoutException e) { // the list with accessible name 'Recent Projects' is not available -> 0 links in the 'Welcome to IntelliJ IDEA' dialog return 0; } } public static void waitUntilIntelliJStarts(int port) { waitFor(Duration.ofSeconds(600), Duration.ofSeconds(3), "The IntelliJ Idea did not start in 10 minutes.", () -> isIntelliJUIVisible(port)); } private static boolean isIntelliJUIVisible(int port) { return isHostOnIpAndPortAccessible("127.0.0.1", port); } private static boolean isHostOnIpAndPortAccessible(String ip, int port) { SocketAddress sockaddr = new InetSocketAddress(ip, port); Socket socket = new Socket(); try { socket.connect(sockaddr, 10000); } catch (IOException IOException) { return false; } return true; } public static void invokeCmdUsingTheSearchEverywherePopup(RemoteRobot remoteRobot, String cmdToInvoke) { step("Invoke a command using the Search Everywhere popup", () -> { Keyboard keyboard = new Keyboard(remoteRobot); if (remoteRobot.isMac()) { keyboard.hotKey(KeyEvent.VK_META, KeyEvent.VK_O); } else { keyboard.hotKey(KeyEvent.VK_CONTROL, KeyEvent.VK_N); } final SearchEverywherePopupFixture searchEverywherePopupFixture = remoteRobot.find(SearchEverywherePopupFixture.class, Duration.ofSeconds(10)); searchEverywherePopupFixture.popupTab("All").click(); searchEverywherePopupFixture.searchField().click(); keyboard.enterText(cmdToInvoke); waitFor(Duration.ofSeconds(30), Duration.ofSeconds(1), "The search in the Search Everywhere popup did not finish in 30 seconds.", () -> didTheSearchInTheSearchEverywherePopupFinish(remoteRobot, cmdToInvoke)); keyboard.hotKey(KeyEvent.VK_ENTER); }); } private static boolean didTheSearchInTheSearchEverywherePopupFinish(RemoteRobot remoteRobot, String cmdToInvoke) { final SearchEverywherePopupFixture searchEverywherePopupFixture = remoteRobot.find(SearchEverywherePopupFixture.class, Duration.ofSeconds(10)); String searchResultsString = listOfRemoteTextToString(searchEverywherePopupFixture.searchResultsJBList().findAllText()); return searchResultsString.toLowerCase().contains(cmdToInvoke.toLowerCase()); } }
adietish/intellij-quarkus
src/it/java/org/jboss/tools/intellij/quarkus/utils/GlobalUtils.java
214,305
package com.magictool.web.util; import lombok.extern.slf4j.Slf4j; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; /** * Future类获取结果工具 * @author lijf */ @Slf4j public class FutureResultUtils { /** * 获取结果方法 * @param future Future类 * @param timeout 设置获取结果的超时时间 * @param <T> T * @return T */ public static <T> T getResultQuietly(Future<T> future, int timeout){ try { if (future != null){ if (timeout > 0){ return future.get(timeout, TimeUnit.MILLISECONDS); }else { return future.get(); } } }catch (Exception e){ log.warn("获取结果超时!", e); } return null; } }
james-ljf/magic-tool
src/main/java/com/magictool/web/util/FutureResultUtils.java
214,306
package com.magictool.web.util; import io.jsonwebtoken.Claims; import io.jsonwebtoken.JwtBuilder; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import java.util.Date; import java.util.Map; /** * 用于生成和验证 token 的工具类 * @author lijf */ public class JwtUtils { /** * token 过期时间 */ public static final long TOKEN_EXPIRED_TIME = 1000 * 60 * 60 * 24L; /** * 签发ID */ public static final String ISSUE_ID = "admin"; /** * userId 标识 */ public static final String USER_ID = "userId"; /** * 加密/解密 密钥 */ private static final String JWT_SECRET = "HS256/MD5"; /** * 创建token * @param claims 载荷 * @param time token时长 * @return String */ public static String createJwt(Map<String, Object> claims, Long time) { // 指定签名的时候使用的签名算法 SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; Date now = new Date(System.currentTimeMillis()); long nowMillis = System.currentTimeMillis(); JwtBuilder builder = Jwts.builder() .setClaims(claims) .setId(ISSUE_ID) .setIssuedAt(now) .signWith(signatureAlgorithm, JWT_SECRET); if (time >= 0) { long expMillis = nowMillis + time; Date exp = new Date(expMillis); builder.setExpiration(exp); } return builder.compact(); } /** * 通过 token 获取 userId * * @param token token * @return userId */ public static String getUserId(String token){ Claims claims = verifyJwt(token); return claims.get(USER_ID) + ""; } /** * 验证Token,如果返回null说明token无效或过期 * * @param token token令牌 * @return Claims */ public static Claims verifyJwt(String token) { Claims claims; try { claims = Jwts.parser() .setSigningKey(JWT_SECRET) .parseClaimsJws(token).getBody(); } catch (Exception e) { claims = null; } return claims; } /** * 生成token * * @param data 载荷 * @return String */ public static String generateToken(Map<String, Object> data) { return createJwt(data, TOKEN_EXPIRED_TIME); } }
james-ljf/magic-tool
src/main/java/com/magictool/web/util/JwtUtils.java
214,310
/* * SPDX-FileCopyrightText: 2021 Atos * SPDX-License-Identifier: EUPL-1.2+ */ package net.atos.client.zgw.zrc.model; public class VerblijfsAdres { /** * De unieke identificatie van het OBJECT * - required * -maxLength: 100 */ private String aoaIdentificatie; /** * - required * - maxLength: 80 */ private String wplWoonplaatsNaam; /** * Een door het bevoegde gemeentelijke orgaan aan een OPENBARE RUIMTE toegekende benaming * - required * - maxLength: 80 */ private String gorOpenbareRuimteNaam; /** * - maxLength: 7 */ private String aoaPostcode; /** * - required * - maximum: 99999 * - minimum: 0 */ private Integer aoaHuisnummer; /** * - maxLength: 1 */ private String aoaHuisletter; /** * - maxLength: 4 */ private String aoaHuisnummertoevoeging; /** * maxLength: 1000 */ private String inpLocatiebeschrijving; public String getAoaIdentificatie() { return aoaIdentificatie; } public void setAoaIdentificatie(final String aoaIdentificatie) { this.aoaIdentificatie = aoaIdentificatie; } public String getWplWoonplaatsNaam() { return wplWoonplaatsNaam; } public void setWplWoonplaatsNaam(final String wplWoonplaatsNaam) { this.wplWoonplaatsNaam = wplWoonplaatsNaam; } public String getGorOpenbareRuimteNaam() { return gorOpenbareRuimteNaam; } public void setGorOpenbareRuimteNaam(final String gorOpenbareRuimteNaam) { this.gorOpenbareRuimteNaam = gorOpenbareRuimteNaam; } public String getAoaPostcode() { return aoaPostcode; } public void setAoaPostcode(final String aoaPostcode) { this.aoaPostcode = aoaPostcode; } public Integer getAoaHuisnummer() { return aoaHuisnummer; } public void setAoaHuisnummer(final Integer aoaHuisnummer) { this.aoaHuisnummer = aoaHuisnummer; } public String getAoaHuisletter() { return aoaHuisletter; } public void setAoaHuisletter(final String aoaHuisletter) { this.aoaHuisletter = aoaHuisletter; } public String getAoaHuisnummertoevoeging() { return aoaHuisnummertoevoeging; } public void setAoaHuisnummertoevoeging(final String aoaHuisnummertoevoeging) { this.aoaHuisnummertoevoeging = aoaHuisnummertoevoeging; } public String getInpLocatiebeschrijving() { return inpLocatiebeschrijving; } public void setInpLocatiebeschrijving(final String inpLocatiebeschrijving) { this.inpLocatiebeschrijving = inpLocatiebeschrijving; } }
NL-AMS-LOCGOV/zaakafhandelcomponent
src/main/java/net/atos/client/zgw/zrc/model/VerblijfsAdres.java
214,313
package domain; import java.io.Serializable; import java.time.LocalDate; import java.time.format.DateTimeFormatter; import java.util.ArrayList; import java.util.List; import org.springframework.format.annotation.NumberFormat; import com.fasterxml.jackson.annotation.JsonProperty; import jakarta.persistence.Entity; import jakarta.persistence.GeneratedValue; import jakarta.persistence.GenerationType; import jakarta.persistence.Id; import jakarta.persistence.OneToMany; import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotEmpty; import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.Size; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @Entity @Getter @Setter @NoArgsConstructor @EqualsAndHashCode(exclude = "verplijfplaatsen") @ToString public class Animal implements Serializable { private static final long serialVersionUID = 1L; @Id private String identificatiecode; @JsonProperty("animal_name") @NotBlank private String name; private String img; private String breed; @NotBlank private String gender; private LocalDate dateOfBirth; private String ageEstimation; private double medicalCost; @OneToMany private List<Verblijfplaats> verplijfplaatsen; private List<Boolean> kanMet = new ArrayList<>(List.of(false, false, false, false, false, false)); public Animal(String identificatiecode, String name, String img, String breed, String gender, LocalDate dateOfBirth, double medicalCost, List<Verblijfplaats> verplijfplaatsen, List<Boolean> kanMet) { this.identificatiecode = identificatiecode; this.name = name; this.img = img; this.breed = breed.substring(0, 1).toUpperCase() + breed.substring(1);; this.gender = gender; this.dateOfBirth = dateOfBirth; this.medicalCost = medicalCost; this.verplijfplaatsen = verplijfplaatsen; this.kanMet = kanMet; for (Verblijfplaats verblijfplaats : verplijfplaatsen) { verblijfplaats.setBewooner(this.identificatiecode); } } }
bramvc15/AnimalSchelter
src/main/java/domain/Animal.java
214,314
package com.magictool.web.util; import java.awt.*; import java.awt.image.BufferedImage; import java.util.HashMap; import java.util.Map; import java.util.Random; /** * 生成验证码图片 * * @author lijf */ public class VerifyUtils { private static final Random RANDOM = new Random(); /** * 获取map后需要根据key获取图片和验证码,图片需要用BufferedImage接收。 * * @return 验证码 */ public static Map<String, Object> generateVerify() { //创建一张图片 BufferedImage verifyPic = new BufferedImage(120, 40, BufferedImage.TYPE_3BYTE_BGR); //通过图片获取画笔 Graphics2D g = verifyPic.createGraphics(); //准备一个字母+数字的字典 String letters = "23456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; //规定验证码的位数 int verifyLength = 4; //生成随机验证码 StringBuilder verifyCode = new StringBuilder(); //循环取值 for (int i = 0; i < verifyLength; i++) { verifyCode.append(letters.charAt((RANDOM.nextInt() * letters.length()))); } //将图片的底板由黑变白 g.setColor(Color.white); g.fillRect(0, 0, 120, 40); //将验证码画在图片之上 g.setFont(new Font("微软雅黑", Font.BOLD, 24)); for (int i = 0; i < verifyLength; i++) { //随机产生一个角度 double theta = Math.random() * Math.PI / 4 * ((RANDOM.nextInt()*2) == 0 ? 1 : -1); //产生偏转 g.rotate(theta, 24 + i * 22d, 20); //每画一个字幕之前都随机给一个颜色 g.setColor(new Color((RANDOM.nextInt() * 256), (RANDOM.nextInt() * 256), (RANDOM.nextInt() * 256))); g.drawString(verifyCode.charAt(i) + "", 20 + i * 22, 26); //回正 g.rotate(-theta, 24 + i * 22d, 20); } //加入干扰线 for (int i = 0; i < 5; i++) { //给随机颜色 g.setColor(new Color((RANDOM.nextInt() * 256), (RANDOM.nextInt() * 256), (RANDOM.nextInt() * 256))); //画线 g.drawLine((RANDOM.nextInt() * 120), (RANDOM.nextInt() * 40), (RANDOM.nextInt() * 120), (RANDOM.nextInt() * 40)); } //设置边框颜色 g.setColor(Color.black); //给验证码一个外边框 g.drawRect(0, 0, 118, 38); //将验证码和图片一起存入map Map<String, Object> data = new HashMap<>(); data.put("verifyCode", verifyCode.toString()); data.put("verifyPic", verifyPic); return data; } }
james-ljf/magic-tool
src/main/java/com/magictool/web/util/VerifyUtils.java
214,316
package jnum.devel.sourcecounts; import jnum.Unit; import jnum.Util; import jnum.data.Histogram; class Schechter extends RegularTemplate { @Override public void init(Histogram mapHistogram, double maxFlux, int bins) { super.init(mapHistogram, maxFlux, bins); double S1 = 0.2*maxFlux; double N0 = guessN(S1); double[] initparms = { N0, 2.0 * dF, S1, -3.0, noiseScaling, 0.0 }; startSize = new double[] { 0.1*N0, 0.1*dF, 0.3*dF, 0.1, 0.1, 0.1 }; init(initparms); } @Override public double getCountsFor(double[] tryparm, int i) { double N0 = tryparm[0]; double S0 = bounded ? tryparm[1] : 0.0; double S1 = tryparm[2]; double p = tryparm[3]; double F = templates[i].flux; return getFillFraction(i, S0, p-F/S1) * N0 * Math.pow(F/S1, p) * Math.exp(-F/S1); } @Override public double getCountsErrFor(double[] tryparm, int i) { return getStandardError(0, 0.1*parameter[0]) * getCountsFor(tryparm, i); } @Override public double evaluate(double[] tryparm) { double S0 = tryparm[1]; double chi2 = super.evaluate(tryparm); if(S0 < dF) return (1.0 + Math.pow((S0/dF-1.0), 2.0)) * chi2; return chi2; } @Override public double getBackground(double[] tryparm) { if(bounded) { double N0 = tryparm[0]; double S0 = tryparm[1]; double S1 = tryparm[2]; double p = tryparm[3]; double delta = S0 < dF ? Math.pow(dF, 2.0 + p) - Math.pow(S0, 2.0 + p) : 0.0; delta *= N0 * Math.pow(S1, -p) / (2.0 - p); return delta + super.getBackground(tryparm); } return super.getBackground(tryparm); } @Override public double minimize(int n) { double chi2 = super.minimize(n); double N = parameter[0]/dF * Unit.mJy * Unit.deg2 / mapArea; double dN = N/parameter[0] * getStandardError(0, 0.01*parameter[0]); double S0 = parameter[1] / Unit.Jy; double dS0 = getStandardError(1, 0.1*parameter[1]) / Unit.Jy; double S1 = parameter[2] / Unit.Jy; double dS1 = getStandardError(2, 0.01*parameter[2]) / Unit.Jy; double alpha = parameter[3]; double dalpha = getStandardError(3, 0.001); System.err.println("N' = " + Util.e3.format(N) + " +- " + Util.e1.format(dN) + " #/mJy/deg2"); if(bounded) System.err.println("S0 = " + Util.e3.format(S0) + " +- " + Util.e1.format(dS0) + " Jy"); System.err.println("S1 = " + Util.e3.format(S1) + " +- " + Util.e1.format(dS1) + " Jy"); System.err.println("p = " + Util.f3.format(alpha) + " +- " + Util.f3.format(dalpha)); return chi2; } @Override public int getNoiseScaleIndex() { return 4; } @Override public int getOffsetIndex() { return 5; } }
attipaci/jnum
src/jnum/devel/sourcecounts/Schechter.java
214,318
package synchronised; import java.util.stream.IntStream; /** Konkurrierender Zugriff auf gemeinsame Ressource: Synchronisierung über Objekt */ public class ObjSync implements Runnable { private final Object waechter = new Object(); // gemeinsames Sperr-Objekt private int val = 0; /** Starte die Demo */ public static void main(String... args) { ObjSync x = new ObjSync(); // Zwei Threads auf dem *selben* Runnable => konkurrierender Zugriff auf val new Thread(x).start(); new Thread(x).start(); } private void incrVal() { synchronized (waechter) { ++val; // Zugriff auf gemeinsame Ressource System.out.println(Thread.currentThread().getId() + ": " + val); } } @Override public void run() { IntStream.range(0, 5).forEach(i -> incrVal()); } }
Programmiermethoden-CampusMinden/Prog2-Lecture
lecture/threads/src/synchronised/ObjSync.java
214,319
/* * $Id$ * * Copyright 2009 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.jdesktop.swingx.demos.autocomplete; import java.util.Arrays; import java.util.List; /** * Class containing the known {@code Airports} in the demo universe. * * @author Karl George Schaefer */ public final class Airports { public static final Airport SCHOENEFELD = new Airport("Berlin - Sch\u00F6nefeld", "EDDB", "SXF"); public static final Airport WICKEDE = new Airport("Dortmund - Wickede", "EDLW", "DTM"); public static final Airport RHEIN_MAIN = new Airport("Frankfurt - Rhein Main", "EDDF", "FRA"); public static final Airport LANGENHAGEN = new Airport("Hannover - Langenhagen", "EDDV", "HAJ"); public static final Airport FUHLSBEETTEL = new Airport("Hamburg - Fuhlsb\u00FCttel", "EDDH", "HAM"); public static final Airport KONRAD_ADENAUER = new Airport("K\u00F6ln/Bonn - Konrad Adenauer", "EDDK", "CGN"); public static final Airport HALLE = new Airport("Leipzig/Halle", "EDDP", "LEJ"); public static final Airport FRANZ_JOSEF_STRAUSS = new Airport("M\u00FCnchen - Franz Josef Strauss", "EDDM", "MUC"); public static final Airport NUERNBERG = new Airport("N\u00F6rnberg", "EDDN", "NUE"); public static final Airport ECHTERDINGEN = new Airport("Stuttgart - Echterdingen", "EDDS", "STR"); public static final List<Airport> ALL_AIRPORTS = Arrays.asList( SCHOENEFELD, WICKEDE, RHEIN_MAIN, LANGENHAGEN, FUHLSBEETTEL, KONRAD_ADENAUER, HALLE, FRANZ_JOSEF_STRAUSS, NUERNBERG, ECHTERDINGEN ); private Airports() { //does nothing } }
tmyroadctfig/swingx
swingx-demos/swingx-demos-content/src/main/java/org/jdesktop/swingx/demos/autocomplete/Airports.java
214,320
boolean gefunden = false; int last = (array.length-1); if (array[last]==x) { gefunden=true; } else { int tmp = array[last]; array[last]=x; int i=0; while(array[i] != x) i++; gefunden = (i < last); array[last] = tmp; }
janfaessler/FHNW-Informatik-Zusammenfassungen
Grundlagen/Programmieren/algd1/suche_waechter.java
214,325
package building; import map.Player; import tools.MiscUtils; public class Townhall extends Building { // durch das Verbessern deines Rathauses schaltest du neue Gebäude (z.B. // Verteidigungen, Fallen) und vieles mehr frei. // progress gibt den "technischen Fortschritt" an int progress = 0; // maximales Level/Progress des Townhalls private int maxlevel = 2; String info = "Das hier ist das Herz deines Dorfs. Das Verbessern schaltet neue Gebäude frei." + " Man sollte das Rathaus mit Verteidigungsgebäuden umgeben, denn der Gegner kann dein Rathaus einnehmen!"; public Townhall(int xPosition, int yPosition) { super(); buildtime = 0; this.xPosition = xPosition; this.yPosition = yPosition; buildingrange = 2; healthpoints = 100; picture = MiscUtils.loadImages("src/gui/res/building")[1]; } public void upgrade(Player player) { // Wood und Stone vom player int wood = player.getWood(); int stone = player.getStone(); progress += 1; // Je nachdem welchen Progress der Townhall schon hat, größere Preise für // weitere Verbesserung if (this.progress < this.maxlevel) { //// Verbesserung 1 if (progress == 1) { if (wood >= 1 && stone >= 1) { // Kosten des Upgrades: 1 wood, 1 Stone player.setWood(wood - 1); player.setStone(stone - 1); // 2 Runden Bauzeit des Upgrades, mehr Lebenspunkte durch Verbesserung buildtime = 2; healthpoints = 200; } else { progress -= 1; // Fehlermeldung, unzureichende Ressourcen für das Upgrade } //// Verbesserung 2 } else if (progress == 2) { if (wood >= 2 && stone >= 2) { // Kosten des Upgrades: 2 wood, 2 Stone player.setWood(wood - 2); player.setStone(stone - 2); // 2 Runden Bauzeit des Upgrades, mehr Lebenspunkte durch Verbesserung buildtime = 2; healthpoints = 200; } else { progress -= 1; // Fehlermeldung, unzureichende Ressourcen für das Upgrade } } } } public void generateFigther() { throw new UnsupportedOperationException(); } public void generateBuilder() { throw new UnsupportedOperationException(); } public void generateFigther2() { // aller echter main character throw new UnsupportedOperationException(); } @Override public void buildableterrains() { buildableterrains.add("water"); } }
CZG-KoR/TheGame
src/building/Townhall.java
214,327
/* * c't-Sim - Robotersimulator für den c't-Bot * * This program is free software; you can redistribute it * and/or modify it under the terms of the GNU General * Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your * option) any later version. * This program is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the implied * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * You should have received a copy of the GNU General Public * License along with this program; if not, write to the Free * Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307, USA. * */ package ctSim.view.gui; import java.awt.Dimension; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import javax.swing.AbstractAction; import javax.swing.BoxLayout; import javax.swing.InputMap; import javax.swing.JComponent; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.KeyStroke; import ctSim.model.ThreeDBot; import ctSim.model.bots.Bot; import ctSim.model.bots.ctbot.CtBotSimTest; import ctSim.model.bots.ctbot.RealCtBot; /** * @author Felix Beckwermert * @author Hendrik Krauß */ public class BotViewer extends JScrollPane { /** UID */ private static final long serialVersionUID = - 7367493564649395707L; /** Buisitors */ private Class[] buisitors; /** zugehöriger Bot */ public final Bot bot; /** * @param bot Bot, zu dem der Viewer gehört */ public BotViewer(Bot bot) { super(VERTICAL_SCROLLBAR_AS_NEEDED, HORIZONTAL_SCROLLBAR_NEVER); this.bot = bot; /* buisitors nach Bot-Art anlegen */ Bot botinstance = null; if (bot instanceof ThreeDBot) { /* simulierter Bot */ botinstance = ((ThreeDBot) bot).getSimBot(); } else if (bot instanceof RealCtBot) { /* echter Bot */ botinstance = bot; } else { throw new AssertionError("Unbekannter Bot-Typ"); } if (botinstance instanceof CtBotSimTest) { /* Test-Bots haben kein LCD, LOG, RemoteCall, ABL, Mausbild */ buisitors = new Class[] { Tables.Position.class, Tables.Sensors.class, Tables.Actuators.class, }; } else { buisitors = new Class[] { Tables.Position.class, Tables.GlobalPosition.class, Leds.class, AndEverything.class, Tables.Sensors.class, Tables.Actuators.class, MousePictureViewer.class, }; } /* Panelbreite soll mindestens so groß sein, dass alle Elemente darin komplett sichtbar sind */ this.setMinimumSize(new Dimension(220, this.getHeight())); setBorder(null); JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); for (Class<?> b : buisitors) { try { GuiBotBuisitor buisitor = (GuiBotBuisitor) b.newInstance(); bot.accept(buisitor); if (buisitor.shouldBeDisplayed()) { panel.add(buisitor); } } catch (IllegalAccessException e) { /** * Kommt nur vor, wenn ein BotBuisitor keinen Konstruktor hat, der public und parameterlos * ist. Wäre ein Compile-time-Fehler; nur wegen Verwendung von Reflection sehen wir das erst * zur Laufzeit. */ throw new AssertionError(e); } catch (InstantiationException e) { // dito throw new AssertionError(e); } } setViewportView(panel); /* Key-Handler */ InputMap inputMap = getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW); KeyStroke key = KeyStroke.getKeyStroke(KeyEvent.VK_E, Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()); inputMap.put(key, "close"); getActionMap().put("close", new AbstractAction() { private static final long serialVersionUID = -7639062234107576185L; public void actionPerformed(ActionEvent e) { BotViewer.this.bot.dispose(); } }); } }
tsandmann/ct-sim
ctSim/view/gui/BotViewer.java
214,330
package ch.swaechter.smbjwrapper; import ch.swaechter.smbjwrapper.streams.SmbInputStream; import ch.swaechter.smbjwrapper.streams.SmbOutputStream; import com.hierynomus.msdtyp.AccessMask; import com.hierynomus.msfscc.fileinformation.FileStandardInformation; import com.hierynomus.mssmb2.SMB2CreateDisposition; import com.hierynomus.mssmb2.SMB2ShareAccess; import com.hierynomus.protocol.commons.buffer.Buffer; import com.hierynomus.protocol.commons.buffer.Buffer.BufferException; import com.hierynomus.protocol.transport.TransportException; import com.hierynomus.smbj.share.File; import java.io.InputStream; import java.io.OutputStream; import java.util.EnumSet; /** * This class represents a SMB file. * * @author Simon Wächter */ public final class SmbFile extends SmbItem { /** * Create a new SMB file based on the SMB connection and the path name. * * @param smbConnection SMB connection * @param pathName Path name */ public SmbFile(SmbConnection smbConnection, String pathName) { super(smbConnection, pathName); } /** * Create a new file. */ public void createFile() { File file = getDiskShare().openFile(getPath(), EnumSet.of(AccessMask.GENERIC_ALL), null, SMB2ShareAccess.ALL, SMB2CreateDisposition.FILE_OVERWRITE_IF, null); file.close(); } /** * Delete the current file. */ public void deleteFile() { getDiskShare().rm(getPath()); } /** * Copy the current file to another file on the same server share via server side copy. This does not work as soon * the files are on different shares (In that case copy the input/output streams). For more information check out * this Samba article: https://wiki.samba.org/index.php/Server-Side_Copy * * @param destinationSmbFile Other file on the same server share * @throws BufferException Buffer related exception * @throws TransportException Transport related exception */ public void copyFileViaServerSideCopy(SmbFile destinationSmbFile) throws Buffer.BufferException, TransportException { try ( File sourceFile = getDiskShare().openFile(getPath(), EnumSet.of(AccessMask.GENERIC_READ), null, EnumSet.of(SMB2ShareAccess.FILE_SHARE_READ, SMB2ShareAccess.FILE_SHARE_DELETE), SMB2CreateDisposition.FILE_OPEN, null); File destinationFile = getDiskShare().openFile(destinationSmbFile.getPath(), EnumSet.of(AccessMask.GENERIC_ALL), null, SMB2ShareAccess.ALL, SMB2CreateDisposition.FILE_OVERWRITE_IF, null); ) { sourceFile.remoteCopyTo(destinationFile); } } /** * Get the input stream of the file that can be used to download the file. * * @return Input stream of the SMB file */ public InputStream getInputStream() { File file = getDiskShare().openFile(getPath(), EnumSet.of(AccessMask.GENERIC_READ), null, SMB2ShareAccess.ALL, SMB2CreateDisposition.FILE_OPEN, null); return new SmbInputStream(file); } /** * Get the output stream of the file that can be used to upload content to this file. * * @return Output stream of the SMB file */ public OutputStream getOutputStream() { return getOutputStream(false); } /** * Get the output stream of the file that can be used to upload and append content to this file. * * @param appendContent Append content or overwrite it * @return Output stream of the SMB file */ public OutputStream getOutputStream(boolean appendContent) { SMB2CreateDisposition mode = !appendContent ? SMB2CreateDisposition.FILE_OVERWRITE_IF : SMB2CreateDisposition.FILE_OPEN_IF; File file = getDiskShare().openFile(getPath(), EnumSet.of(AccessMask.GENERIC_ALL), null, SMB2ShareAccess.ALL, mode, null); return new SmbOutputStream(file, appendContent); } /** * Get the file size of the SMB item. * * @return File size of the SMB items in bytes */ public long getFileSize() { FileStandardInformation fileStandardInformation = getDiskShare().getFileInformation(getPath()).getStandardInformation(); return fileStandardInformation.getEndOfFile(); } /** * {@inheritDoc} */ public SmbFile renameTo(String newFileName, boolean replaceIfExist) { try (File file = getDiskShare().openFile(getPath(), EnumSet.of(AccessMask.GENERIC_ALL), null, SMB2ShareAccess.ALL, SMB2CreateDisposition.FILE_OPEN, null)) { String newFilePath = buildProperItemPath(getParentPath().getPath(), newFileName); file.rename(newFilePath, replaceIfExist); return new SmbFile(getSmbConnection(), newFilePath); } } /** * Check if the current and the given objects are equals. * * @param object Given object to compare against * @return Status of the check */ @Override public boolean equals(Object object) { if (object instanceof SmbFile) { SmbFile smbFile = (SmbFile) object; return getSmbPath().equals(smbFile.getSmbPath()); } else { return false; } } }
swaechter/smbjwrapper
src/main/java/ch/swaechter/smbjwrapper/SmbFile.java
214,332
//-----BEGIN DISCLAIMER----- /******************************************************************************* * Copyright (c) 2019 JCrypTool Team and Contributors * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ //-----END DISCLAIMER----- package org.jcryptool.games.numbershark.strategies; /* * ============================================================================ Berechnung der optimalen Punktzahlen * beim Zahlenhai-Spiel ============================================================================ Copyright 2010 by * Volker van Nek, volkervannek at googlemail dot com This is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License, http://www.gnu.org/copyleft/gpl.html. This software has NO * WARRANTY, not even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * ============================================================================ Der folgende Algorithmus ist geeignet, * die optimale Punktzahl beim Taxman-Game bzw. Zahlenhai mit g Zahlen zu bestimmen. Schritt 1: Solange es Zahlen * groesser g/2 gibt, die genau einen aktiven echten Teiler besitzen, nimm von diesen die groesste. Schritt 2: Solange * es ueberhaupt noch Zahlen gibt, fertige fuer jede dieser Zahlen eine Kopie der aktiven Zahlenmenge an, nimm die Zahl * aus der jeweiligen Kopie und gehe mit der Kopie zurueck zu Schritt 1. * ============================================================================ Die Klasse T01 implementiert diesen * Algorithmus etwas effizienter: 1. Die durch Schritt 2 erzeugte Anzahl an Verzweigungen des Suchbaums wird auf 5 * verschiedene Weisen reduziert: a) Wurde an einer anderen Stelle der Suche die noch zu betrachtende Menge an aktiven * Zahlen bereits einmal untersucht, wird die Suche in diesem Zweig abgebrochen. b) Es kann fuer jeden Zweig * abgeschaetzt werden, wieviel der Hai hier mindestens erhaelt. Liegt dieser Wert bereits ueber einer oberen Schranke, * wird die Suche in diesem Zweig abgebrochen. c) Hat eine Zahl noch mehr als zwei aktive echte Teiler, so wird diese * Zahl an diesem Punkt noch nicht ausgewaehlt, wenn unter diesen echten Teilern einer ist, der einen der anderen teilt. * d) Hat eine Zahl noch mehr als einen aktiven echten Teiler, so wird statt dieser Zahl der kleinste aktive Teiler * ausgewaehlt. Dieser Teiler wird dabei jedoch nicht in die Zug-Sequenz uebernommen. e) Erreicht ein Zweig eine * Punktzahl, die um g hoeher liegt als die optimale Punktzahl fuer g-1, so wird die Suche abgebrochen. 2. Statt Kopien * der aktiven Zahlenmenge anzufertigen, werden mit Hilfe einer Rueckverfolgung die jeweiligen Veraenderungen an der * Zahlenmenge wieder rueckgaengig gemacht. ============================================================================ * Start des Programms: Zwei Kommandozeilenparameter werden als Intervallgrenzen von und bis verwendet. Beispiel: java * ZahlenhaiBestwerte 1 159 Laufzeit des Programms: Die Laufzeiten sind sowohl von der Anzahl der Zahlen als auch von * der Anzahl der Verzweigungen des Suchbaums und von den Permutationsmoeglichkeiten in der Zug-Sequenz zur optimalen * Punktzahl abhaengig. Die Laufzeiten steigen nicht kontinuierlich an. Abhaengig sind die Zeiten natuerlich auch davon, * ob auf die Berechnung des Vorgaengers zurueck gegriffen werden kann oder ob die Suche nach Erreichen der maximal * moeglichen Punktzahl abgebrochen werden kann. Ab 224 sollten die Rechnungen nicht mehr mit den Standardeinstellungen * durchgefuehrt werden, da Java nach Erreichen der maximalen Heap-Kapazitaet recht viel Zeit zur Speicherbereinigung * benoetigt und das Programm eventuell sogar mit einer Fehlermeldung abbricht. Die GC-Option -XX:+UseConcMarkSweepGC * hat sich bei Rechnungen mit hoher RAM-Beanspruchung als guenstig erwiesen. Mit Hilfe dieser Option benoetigt z.B. die * 330 nur 530 MB Speicher, ohne jedoch 1.1 GB. Allerdings ist Java mit dem Standard-Kollektor i.A. deutlich schneller. * Durch Anwendung von Multithreading erzielt das Programm, von den ersten 223 abgesehen, wesentlich geringere * Laufzeiten. Die hoehere Auslastung des Rechners wirkt sich hier positiv aus. Die Reihenfolge der den einzelnen * Threads zugewiesenen Rechenzeiten scheint bei jeder Rechnung stets ein klein wenig unterschiedlich zu sein. Der Baum * wird daher nicht immer gleich durchlaufen, die Datenbank ist unterschiedlich gross und die Rechenzeiten weichen etwas * voneinander ab. Ueber den globalen Parameter G_MT laesst sich das Multithreading abstellen bzw. definieren, ab * welcher Zahl Multithreading verwendet werden soll. Es hat sich gezeigt, dass dieses Programm auf der 64-Bit-VM * deutlich schneller laeuft und auch, dass die Java-Version 7 gegenueber der Version 6 deutliche Zeitvorteile erzielt. * (Zeitwerte in Klammern: Zeit bis zum Erreichen einer Eingabesequenz zum Bestwert.) Testrechner 1: Ubuntu 10.04, 64 * Bit VM 1.7.0, 4 GB RAM, 2 x 2.4 GHz VM-Optionen (wie 224 falls nicht anders notiert) 1 - 159 in 1 ( 1) s keine 160 - * 223 in 3 ( 1) s keine 224 - 259 in 472 ( 92) s -Xms1g -Xmx2g -Xss6m 260 in 271 ( 103) s 261 - 329 in 343 ( 85) s 330 * u 331 in 415 ( 3) s 332 - 339 in 101 ( 28) s 340 u 341 in 529 ( 378) s 342 in 1443 (1042) s -Xms2g -Xmx3g -Xss12m 343 * in 91 ( 91) s 344 in 4283 (2278) s -XX:+UseConcMarkSweepGC -Xms2g -Xmx3840m -Xss12m 345 - 347 in 156 ( 156) s 348 u * 349 in 6099 (2436) s wie 344 350 in ---- (----) s 351 in ---- (----) s 352 u 353 in ---- (----) s 354 - 356 in 1414 * (1414) s 357 in 3637 ( 576) s wie 344 358 - 359 in 54 ( 54) s Testrechner 2: Ubuntu 10.04, 64 Bit VM 1.6.0_18, 34 GB * RAM, 4 x 2.6 GHz 350 in 20745 s -XX:+UseConcMarkSweepGC -Xms28g -Xmx32g -Xss64m 351 in 17638 s wie 350 352 u 353 in * 27218 s wie 350 Die Suchbaeume: Der groesste auf dem Testrechner 1 berechnete Baum gehoert zur 348. Das Programm * musste 9.3 Mrd. Knoten besuchen, um den optimalen Punktwert zu beweisen, was einer Verarbeitung von 1.4 Mio. Knoten/s * entspricht. (Aufgrund der recht grossen Anzahl an Knoten verwendet das Programm pro Baum bzw. Thread nur ein * Arbeitsobjekt (Objekt-Typ D). Der Baum existiert lediglich in der Idee des Programms.) Die Datenbank enthielt 80 Mio. * Eintraege, wobei bei der 348 die meisten Eintraege (Objekte vom Typ R) inkl. der Metadaten ein Volumen von jeweils 56 * Byte beanspruchen. Die 352 benoetigte auf dem Testrechner 2 ein Volumen von ueber 26 GB. */ import java.util.Arrays; import java.util.LinkedList; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.eclipse.core.runtime.IProgressMonitor; public class ZahlenhaiBestwerte { private static String[][] output = null; private static int stoppedAt; static final boolean isCancelled = false; private static int von = 2; private static int bis = 0; /* * VOLLSTAENDIG bestimmt, ob der Suchbaum vollstaendig durchlaufen werden soll (true) oder ob nur bis zum Erreichen * einer Eingabesequenz zum Bestwert gerechnet werden soll (false): */ static final boolean VOLLSTAENDIG = true; /* * Je nach Hardware kann mit G_MT die Grenze definiert werden, ab der mit Multithreading gerechnet werden soll. Ab * der ersten Verzweigung laufen dann die einzelnen Zweige jeweils in einem eigenen Thread. Es werden zwei * Moeglichkeiten des Multithreadings angeboten: Eine, bei der alle Verzweigungen parallel abgearbeitet werden, und * eine, bei der nur AZ_KERNE viele Threads gleichzeiteig laufen. Auf letztere Weise wird bei nur wenigen * Prozessor-Kernen eine fast sequentielle Reihenfolge eingehalten. Die Zahlen in G_SEMI_SEQUENTIELL sind die, bei * denen sich diese Art des Durchlaufs auf dem Testrechner 1 als guenstiger erwies. */ static final int G_MT = 220, // auf den Testrechner 1 zugeschnitten AZ_KERNE = Runtime.getRuntime().availableProcessors(); // Anzahl Kerne static final short[] G_SEMI_SEQUENTIELL = { // opt. fuer Testrechner 1 220, 222, 224, 225, 228, 232, 234, 261, 264, 266, 268, 270, 272, 273, 275, 276, 279, 280, 282, 284, 285, 286, 288, 290, 292, 294, 296, 297, 300, 304, 306, 308, 312, 315, 320, 322, 324, 328, 333, 338, 344, 348, 357 }; // Teste, ob g zu denen gehoert, die semisequentiell abgearbeitet werden: static boolean semiseq(int g) { for (short n : G_SEMI_SEQUENTIELL) if (g == n) return true; return false; } public static void main(final int von1, final int bis1, IProgressMonitor monitor) throws InterruptedException { folge2 = new int[0]; azR2 = new int[2]; rest0 = new int[0]; int schlaf, t; try { von = von1; bis = bis1; } catch (Exception e) { System.out.println("Das Programm benoetigt zwei ganzzahlige " + "Intervallgrenzen. Beispiel:\njava ZahlenhaiBestwerte 10 20"); } if (von < 1) { if (bis < 1) return; von = 1; } if (von == 1 && bis > 0) { System.out.println("1:1:0:[1]:0ms"); von++; } output = new String[bis + 1 - von][5]; for (g = von; g <= bis; g++) { if (!monitor.isCanceled()) { start = System.currentTimeMillis(); berechne(); if (g >= G_MT) { schlaf = (g * g * g) >> 16; // Pause von g abhaengig while (azVZW > 0) Thread.sleep(schlaf); xs.shutdown(); } stop = System.currentTimeMillis(); t = (int) (stop - start); String zeit = t < 1000 ? t + "ms" : (t / 1000) + "s"; output[g - von][4] = zeit; stoppedAt = g; } } } static int azVZW; // Zaehler fuer Anzahl an Thread-Instanzen static int azDB; static int g, // groesste Zahl g2, // g/2 g64, // (effektiv + 16 + 63)/64 haiMax, // obere Schranke fuer hai max, // gesuchter Maximalwert bw, // der aktuelle Bestwert az0, // Anzahl Zahlen in letzter Eingabe-Sequenz pts1g, // Punkte nach schritt1B pts1g0; // Punkte nach schritt1B im letzten Durchlauf static L folge1; // Eingabe-Sequenz nach schritt1B static int[] folge2, // Eingabe-Sequenz ab Schritt 2 rest0, // speichert Rest nach schritt1B fuer naechstes g azR2; static R[] db; // Datenbank fuer Reste bzw inaktive Zahlen, Index = ds.aktiv static boolean abbruch, // Cut im Fall T(g) = T(g-1) + g semiseq; static long start, stop; // fuer die Zeitmessung static L pp; // pp = pseudoprimes Futter bei g static int azP, azPP, // Anzahl der Primzahlen bzw. PP groesser g/2 effektiv, // Summe der effektiv waehlbaren Zahlen nach Schritt 1B effektiv2, // Index fuer Teilung der Datenbank effektiv2plus79; // dto. static ExecutorService xs; static L vzw1; // s.u.: static final short[] PRIM; // Primzahlen // s.u.: static final int[][] U_SCHRANKE; // untere Schranken fuer Punkte // eine nuetzliche Abkuerzung: static class L extends LinkedList<Integer> { private static final long serialVersionUID = -2507500531472253381L; } /* * Nach der Auswahl der groessten Primzahl in Schritt 1A werden saemtliche restliche Primzahlen groesser g/2 und * alle Pseudoprimzahlen aus dem Spiel genommen. Wesentlich ist hierfuer die vorherige Markierung durch die Methode * markierePP(T[]) (ebenfalls in Schritt 1A). Die Suche reduziert sich dann nach Schritt 1B auf die im Hinblick auf * die optimale Punktzahl effektiv waehlbaren Zahlen. */ /* * pseudoprim() berechnet saemtliche Pseudoprimzahlen (nicht prime Zahlen, die in keiner optimalen Zugfolge * enthalten sein koennen). Berechnung: Hat g die Primfaktorzerlegung g = p * q mit p,q > 2 und bezeichne p' bzw. q' * die jeweils naechst kleinere Primzahl und sei f = p' * q' > g/2. Dann ist f pseudoprim bzgl. g. Weiter ist f * pseudoprim bzgl. nachfolgender g solange f > g/2. (Zur Ueberpruefung der Konsistenz der Folge opt(g) der * optimalen Punktzahlen kann die folgende Beziehung verwendet werden: Ist g die kleinste Zahl bzgl. derer f eine * Pseudoprimzahl ist, so gilt opt(g) = opt(g-1) + g - p' * q' S. Kommentare unten in int[][] U_SCHRANKE.) */ static L pseudoprim() { L[] pp = new L[g + 1]; pp[0] = new L(); for (int i = 1; i <= g; i++) { pp[i] = (L) pp[i - 1].clone(); if (i % 2 == 0) pp[i].remove(new Integer(i / 2)); L t = tmOhne1uN(i); // Teilermenge von N ohne 1 und ohne N if (t.size() == 1) { int p = t.get(0); if (p > 2) { int q = primDavor(p), f = q * q; if (f > i / 2) pp[i].add(f); } } else if (t.size() == 2) { int p1 = t.get(0), p2 = t.get(1); if (p1 > 2 && istPrim(p2)) { int q1 = primDavor(p1), q2 = primDavor(p2), f = q1 * q2; if (f > i / 2) pp[i].add(f); } } } return pp[g]; } // letzte Primzahl vor N: static int primDavor(final int N) { // Voraussetzung: N > 2 int i = 0; for (int p : PRIM) if (p >= N) break; else i++; return PRIM[i - 1]; } // (selbstredend): static boolean istPrim(final int N) { for (int p : PRIM) if (p == N) return true; else if (p > N) return false; return false; // Compiler-Dummy } // Anzahl der Primzahlen groesser g/2: static int prim2() { int az = 0; for (int n = g; n > g / 2; n--) if (istPrim(n)) az++; return az; } /* * Die Primzahlen groesser g/2 und alle Pseudoprimzahlen werden markiert und in Schritt 1B (zu diesem Zeitpunkt ist * die groesste Primzahl bereits nicht mehr dabei) nach entsprechender Gutschrift fuer den Hai aus dem Spiel * entfernt: */ static void markierePP(T[] tab) { for (int i = g; i > g2; i--) if (istPrim(i) || pp.contains(i)) { tab[i].az = -1; tab[i].aktiv = null; tab[i].tm = null; tab[i].indizes = null; } } /* * Um die Anzahl erweiterte Teilermenge (Menge ECHTER aktiver Teiler ungleich 1): Um eine effiziente Verwaltung der * Teilermengen zu ermoeglichen, wird noch ein Array hinzu gefuegt, das sich merkt, ob der entsprechende Teiler * aktiv ist, und eins, das den Array-Index der Teiler speichert. */ static class T { int az, // Anzahl INKL. der Zahl selbst az1; // zu Beginn und OHNE int[] tm; // Teilermenge OHNE die Zahl selbst byte[] aktiv; // Zahl aktiv=1 oder nicht=0 short[] indizes; // die Indizes der Zahlen in tm T(int[] tm) { // Konstruktor fuer den Start der Suche az1 = tm.length; az = az1 + 1; this.tm = tm; aktiv = new byte[az1]; if (az1 > 0) { int gT = tm[az1 - 1]; indizes = new short[gT + 1]; } for (int i = 0; i < az1; i++) { aktiv[i] = 1; indizes[tm[i]] = (short) i; } } T(int az, int az1, int[] tm, byte[] aktiv, short[] indizes) { this.az = az; this.az1 = az1; this.tm = tm; this.aktiv = aktiv; this.indizes = indizes; } T kopie() { return new T(az, az1, tm == null ? null : Arrays.copyOf(tm, tm.length), aktiv == null ? null : Arrays.copyOf(aktiv, aktiv.length), indizes == null ? null : Arrays.copyOf(indizes, indizes.length)); } void einfg(final int N) { aktiv[indizes[N]] = 1; az++; } void entf(final int N) { aktiv[indizes[N]] = 0; az--; } int kleinste() { // nicht alle Eintraege 0 int i = 0; for (;; i++) if (aktiv[i] > 0) break; return tm[i]; } int groesste() { // nicht alle Eintraege 0 int i = az1 - 1; for (;; i--) if (aktiv[i] > 0) break; return tm[i]; } } // Ende class T // der gute alte Gauss (fuer berechne()): static int summe(final int K) { return K * (K + 1) / 2; } // Start der Rechnung: static void berechne() { azDB = 0; max = U_SCHRANKE[g][0]; // hier: bester bisher bekannter Wert haiMax = g * (g + 1) / 2 - max; // obere Grenze fuer den Hai; Summenformel az0 = U_SCHRANKE[g - 1][1]; g2 = g / 2; pp = pseudoprim(); azPP = pp.size(); azP = prim2(); bw = 0; semiseq = semiseq(g); folge1 = new L(); // Zahlen in den Schritten 1A und 1B schritt1A(); } /* * In Schritt 1A: Erzeuge das Array mit den Teilermengen aller Zahlen. Der Array-Index entspricht dabei der * jeweiligen Zahl. */ static T[] tabelle() { T[] tab = new T[g + 1]; for (int n = 1; n <= g; n++) { tab[n] = new T(tm(n)); } return tab; } // Teilermenge von N ohne 1 und ohne N als Array: static int[] tm(final int N) { L tm = tmOhne1uN(N); final int S = tm.size(); int[] a = new int[S]; if (S == 0) return a; int i = 0; for (int z : tm) a[i++] = z; return a; } // Teilermenge von N ohne 1 und ohne N als Liste: static L tmOhne1uN(final int N) { L tm = new L(); for (int i = N / 2; i > 1; i--) if (N % i == 0) tm.push(i); return tm; } // Schritte 1A und 1B sind der erste Durchlauf von Schritt 1: static void schritt1A() { abbruch = false; T[] tab = tabelle(); int pts, hai = 1, i = g; // Sonderbehandlung der groessten Primzahl: while (tab[i].az != 1) i--; // 1 bereits weg pts = i; // groesste Primzahl folge1.add(i); markierePP(tab); // setzt u.a. tab[i].az = -1; tab[i].az = -2; // Korrektur (new D(hai, pts, null, tab, 1, g - 2)).schritt1B(); } /* * entf(int,T[]) und reaktiviere(int,T[],int) werden zur Aenderung und Rueckaenderung des Arbeitsobjekts D verwendet * (Methoden schritt1B(), setze(int) und schritt1()). */ // entferne n aus saemtlichen Teilermengen: static void entf(final int N, T[] tab) { if (tab[N].az > 0) tab[N].az = 0; // d.h. if az == 1 // (N wird aus tab[N] als letztes entfernt) for (int i = N << 1; i <= g; i += N) if (tab[i].az > 0) tab[i].entf(N); } /* * Der Teiler R wird in der gesamten Tabelle wieder reaktiviert, nur nicht in tab[N] (dort Sonderbehandlung): */ static void reaktiviere(final int R, T[] tab, final int N) { if (tab[R].az == 0 && R != N) tab[R].az = 1; for (int i = R << 1; i <= g; i += R) if (tab[i].az > 0 && i != N) tab[i].einfg(R); } /* * D ist das Arbeitsobjekt, dass entweder selbst oder als Kopie in einem eigenstaendigen Thread per Backtracking * durch den Suchbaum geschickt wird. Im Wesentlichen beschreiben seine Methoden den Suchvorgang. */ /* * Datenstruktur D, die es erlaubt, in Schritt 1 schnell die noch aktiven Zahlen der Teilermenge einer Zahl i und * deren Anzahl zu bestimmen: Wesentlich ist hierfuer T[] tab. tab[i] haelt diese Information bereit. */ static class D { int hai, pts, // Hai-Punkte, Spieler-Punkte az, aktiv; // Anzahl bisher gewaehlter Zahlen bzw. aktiver Zahlen int[] seq2; // Eingabe-Sequenz ab Schritt 2; seq2[0] speichert Anzahl T[] tab; // Tabelle mit der Teilermenge jeder Zahl D(int hai, int pts, int[] seq2, T[] tab, int az, int aktiv) { this.hai = hai; this.pts = pts; this.seq2 = seq2; this.tab = tab; this.az = az; this.aktiv = aktiv; } D kopie() { T[] tabKopie = new T[tab.length]; for (int i = 0; i < tab.length; i++) tabKopie[i] = tab[i] == null ? null : tab[i].kopie(); return new D(hai, pts, Arrays.copyOf(seq2, seq2.length), tabKopie, az, aktiv); } void schritt1B() { T tabN, tabT; for (int n = g, t; n > g2; n--) { tabN = tab[n]; if (tabN.az == -1) { tabN.az = -2; hai += n; aktiv--; } else if (tabN.az == 2) { t = tabN.kleinste(); tabT = tab[t]; hai += t; pts += n; tabN.az = -2; folge1.add(n); az++; entf(t, tab); tabT.az = -2; tabT.aktiv = null; tabT.tm = null; tabT.indizes = null; // n > g/2 muss nur in ds.tab[n] geloescht werden: tabN.aktiv = null; tabN.tm = null; tabN.indizes = null; aktiv -= 2; n = g + 1; } } /* * Nach dem ersten Durchlauf des Schritts 1 gibt es 3 Moeglichkeiten: 1. Die Suche ist bereits fertig. 2. * g-1 hatte an dieser Stelle den gleichen 'Rest'. 3. Die Suche geht weiter. */ int[] rest = new int[aktiv]; int k = 0; for (int i = 2; i <= g; i++) if (tab[i].az > 0) rest[k++] = i; // hatte g-1 den gleichen Rest? : int eq = 0; if (java.util.Arrays.equals(rest, rest0)) eq = 1; rest0 = rest; // fuer g+1 pts1g0 = pts1g; pts1g = pts; // dto. // 1. Die Suche ist bereits fertig: if (aktiv == 0) { max = pts; folge2 = new int[0]; haiMax = g * (g + 1) / 2 - max; // falls max anfaenglich nicht stimmte ausgabe(""); return; } // 2. g-1 hatte an dieser Stelle den gleichen Rest: else if (eq == 1) { max = pts; max += U_SCHRANKE[g - 1][0] - pts1g0; U_SCHRANKE[g][0] = max; // fuer g+1 U_SCHRANKE[g][1] = az + (folge2.length == 0 ? 0 : folge2[0]); haiMax = g * (g + 1) / 2 - max; ausgabe(":rest"); return; } // 3. Die Suche geht weiter: seq2 = new int[1 + aktiv / 2]; // seq2[0] speichert Anzahl effektiv = aktiv; // effektiv waehlbar ab der ersten Verzweigung effektiv2 = effektiv / 2; effektiv2plus79 = effektiv2 + 79; // 79 = 16 + 63 db = new R[aktiv]; // Datenbank g64 = (effektiv + 79) / 64; // 79 = 16 + 63 azR2[0] = (effektiv2 + 16) / 64; azR2[1] = (effektiv2 + 16) % 64; if (g < G_MT) schritt2(); // kein Multithreading else if (semiseq) schritt2SemiSequentiell(); else schritt2Parallel(); } /* * Die erste Verzweigung des Suchbaums: Jeder Zweig wird in einem eigenen Thread abgearbeitet. */ void schritt2SemiSequentiell() { short[] vzw = verzweigungen(this); vzw1 = new L(); for (short i : vzw) { if (i == 0) break; azVZW++; vzw1.add((int) i); } xs = Executors.newFixedThreadPool(AZ_KERNE); for (int k = 0, n; k < AZ_KERNE; k++) { n = vzw1Pop(); if (n > 0) xs.execute(new VZW(n, kopie())); } } void schritt2Parallel() { short[] vzw = verzweigungen(this); for (short i : vzw) { if (i == 0) break; azVZW++; } xs = Executors.newFixedThreadPool(azVZW); for (short i : vzw) { if (i == 0) break; xs.execute(new VZW(i, kopie())); } } // Die weiteren Verzweigungen des Suchbaums: void schritt2() { if (abbruch) return; for (short i : verzweigungen(this)) { if (i == 0) break; setze(i); } } // n wird ausgewaehlt, die Datenstruktur ds entsprechend angepasst: void setze(final int N) { if (abbruch) return; T tabN = tab[N]; final int AZ = tabN.az; // Merker fuer Ruecksetzung; az ist 1 oder 2 int t = 0; // unten im Fall az = 2 der echte Teiler von N tabN.az = 0; // verhindert das Loeschen in tabN.tm if (AZ > 1) { t = tabN.kleinste(); hai += t; entf(t, tab); pts += N; seq2[++seq2[0]] = N; az++; } else hai += N; entf(N, tab); // N <= g/2 muss auch geloescht werden aktiv -= AZ; schritt1(); // Backtracking: die Aenderungen werden wieder rueckgaengig gemacht: aktiv += AZ; reaktiviere(N, tab, N); if (AZ > 1) { pts -= N; seq2[seq2[0]--] = 0; az--; hai -= t; reaktiviere(t, tab, N); tabN.einfg(t); } else hai -= N; tabN.az = AZ; } /* * Der Teil, der dem Algorithmus seine hohe Geschwindigkeit verleiht: Die Suche ohne Verzweigung: */ void schritt1() { boolean ende = true; T tabN; for (int n = g, t; n > g2; n--) { tabN = tab[n]; if (tabN.az < 1) continue; // Haifutter darf es (bei opt. Punktzahlen) hier nicht mehr geben: else if (tabN.az == 1) return; else if (tabN.az == 2) { t = tabN.kleinste(); tabN.az = 0; hai += t; entf(t, tab); // n > g2 muss nur in dsTabN geloescht werden pts += n; seq2[++seq2[0]] = n; az++; aktiv -= 2; ende = false; schritt1(); // Backtracking: tabN.einfg(t); tabN.az = 2; hai -= t; pts -= n; seq2[seq2[0]--] = 0; az--; reaktiviere(t, tab, n); aktiv += 2; break; } } if (ende) { if (pts > bw) bestwerte(); // evtl. Ausgabe; if (pts > bw) kostet // .. hier weniger Zeit als in synchronized bestwerte() // Fertig? if (aktiv == 0) return; // Soll dieser Zweig weiter verfolgt werden? if (!moeglich(this)) return; long[] rest; // effektiv : die nach Schritt 1B noch effektiv waehlbaren Zahlen if (aktiv < effektiv2) { // weniger AKTIVE Zahlen als effektiv/2 int s = (effektiv2plus79 + (aktiv << 1)) >> 6, m; if (s >= g64) rest = restAktiv1(this); else if ((m = 1 + (aktiv + 1) / 7) > s) // + 1 = - 5 + 6 rest = restAktiv2(s, this); else rest = restAktiv9(m, this); } else { // weniger INAKTIVE (ausgewaehlte) Zahlen int r = effektiv - aktiv, s = (effektiv2plus79 + (r << 1)) >> 6, m; if (s >= g64) rest = restInaktiv1(this); else if ((m = 1 + (r + 1) / 7) > s) rest = restInaktiv2(s, this); else rest = restInaktiv9(m, this); } if (dbEinfuegen(rest, aktiv)) schritt2(); } } /* * Hier wird der maximale Wert (Thread-geschuetzt) hochgeschraubt und die zugehoerige Zugfolge ausgegeben, ggf. * auch die weitere Suche abgebrochen: */ synchronized void bestwerte() { if (pts > bw) { // Thread-geschuetzte Wiederholung dieser Frage bw = pts; if (pts >= max) { haiMax -= pts - max; // falls max zu niedrig angesetzt wurde max = pts; U_SCHRANKE[g][0] = max; // Vorbereitung fuer naechstes g U_SCHRANKE[g][1] = az; // dto. folge2 = seq2.clone(); if (!VOLLSTAENDIG || max == U_SCHRANKE[g - 1][0] + g) { ausgabe(":cut"); abbruch = true; } else ausgabe(""); // else { // stop = System.currentTimeMillis(); // ausgabe(":"+((stop-start)/1000)+"s"); // } } } } } // Ende class D /* * Es wird berechnet, was der Hai in diesem Zweig mindestens bekommt. Liegt dieser Wert bereits zu hoch, wird false * zurueck gegeben. Zusaetzlich wird beurteilt, ob ueberhaupt noch genuegend Zahlen zur Auswahl stehen. */ static boolean moeglich(final D DS) { // haiMax-Version int hai = DS.hai, s = DS.aktiv, s2 = s / 2, // mehr Zahlen kann der Spieler nicht bekommen az1 = U_SCHRANKE[g - 1][1] - DS.az; // braucht er mindestens noch if (s2 < az1) return false; if (s2 == az1) s -= s2; else s -= ++az1; // diesmal evtl. eine Zahl mehr final T[] TAB = DS.tab; for (int i = 2, n = 0; n < s; i++) if (TAB[i].az > 0) { hai += i; n++; } if (hai > haiMax) return false; return true; } /* * Die folgenden restXYZ-Methoden bilden die Spielsituation isomorph und platzsparend in ein long[] ab. Betrachtet * wird dabei nur der effektive Rest (nach Schritt 1B). ds.pts wird aus Speicherplatzgruenden (Java verwaltet * Objekte in 8-Byte-Schritten) mit in dieses Array gesteckt. */ /* * Hier wird geprueft, ob die jeweilige Zahl aktiv ist (aktiv = 1, nicht aktiv = 0) und das entsprechende Bit * festgehalten: */ static long[] restAktiv1(final D DS) { long[] rest = new long[g64]; final int G = g; final T[] TAB = DS.tab; int i = 2, r = 0, r1 = 16; // 16 Bit ganz rechts fuer ds.pts for (; i <= G; i++) { if (TAB[i].az < 0) continue; // i.A. in der Ueberzahl if (TAB[i].az > 0) rest[r] |= 1; // aktiv if (r1 < 63) { rest[r] <<= 1; r1++; } else { r1 = 0; r++; } } rest[0] <<= 16; rest[0] |= DS.pts; // Punkte return rest; } /* * Hier wird geprueft, ob die jeweilige Zahl nicht aktiv ist (aktiv = 0, nicht aktiv = 1) und das entsprechende Bit * festgehalten: */ static long[] restInaktiv1(final D DS) { long[] rest = new long[g64]; final int G = g; final T[] TAB = DS.tab; int i = 2, r = 0, r1 = 16; for (; i <= G; i++) { if (TAB[i].az < 0) continue; if (TAB[i].az == 0) rest[r] |= 1; if (r1 < 63) { rest[r] <<= 1; r1++; } else { r1 = 0; r++; } } rest[0] <<= 16; rest[0] |= DS.pts; // Punkte return rest; } /* * Sind NUR NOCH WENIGE Zahlen AKTIV, so ist die Wahrscheinlichkeit hoch, dass zwei aufeinander folgende (effektive) * Zahlen nicht aktiv sind. In diesem Fall wird im vorderen Teil des Arrays (hinter ds.pts) eine 1 festgehalten. * Andernfalls wird hier eine Null eingetragen und beide Zahlen werden im hinteren Teil wie in der Methode * restAktiv1 als 0 oder 1 entsprechend notiert. D.h. hier werden INaktive Zahlen zusammengefasst und aktive * differenziert dargestellt. */ static long[] restAktiv2(final int DIM, final D DS) { long[] rest = new long[DIM]; rest[0] = DS.pts; final int G = g; final T[] TAB = DS.tab; int i = 2, x = 0, y = 0, m, r = azR2[0], r1 = azR2[1], s = 0, s1 = 16; aussen: while (i <= G) { while (TAB[i].az < 0) if (i < G) i++; else break aussen; if (i == G) break; m = 1; x = y = 0; if (TAB[i++].az > 0) { m = 0; x = 1; } while (TAB[i].az < 0) if (i < G) i++; else break aussen; if (TAB[i++].az > 0) { m = 0; y = 1; } if (m == 0) { if (x > 0) rest[r] |= (1L << r1); if (r1 < 63) r1++; else { r1 = 0; r++; } if (y > 0) rest[r] |= (1L << r1); if (r1 < 63) r1++; else { r1 = 0; r++; } } else rest[s] |= (1L << s1); if (s1 < 63) s1++; else { s1 = 0; s++; } } if (i <= g && TAB[i].az > 0) rest[r] |= (1L << r1); return rest; } /* * Sind noch viele (effektiv waehlbare) Zahlen aktiv (WENIGE INAKTIV), so ist die Wahrscheinlichkeit hoch, dass zwei * aufeinander folgende (effektive) Zahlen aktiv sind. ... (s.o.) D.h. hier werden aktive Zahlen zusammengefasst und * INaktive differenziert dargestellt. */ static long[] restInaktiv2(final int DIM, final D DS) { long[] rest = new long[DIM]; rest[0] = DS.pts; final int G = g; final T[] TAB = DS.tab; int i = 2, x = 0, y = 0, m, r = azR2[0], r1 = azR2[1], s = 0, s1 = 16; aussen: while (i <= G) { while (TAB[i].az < 0) if (i < G) i++; else break aussen; if (i == G) break; m = 1; x = y = 0; if (TAB[i++].az == 0) { m = 0; x = 1; } while (TAB[i].az < 0) if (i < G) i++; else break aussen; if (TAB[i++].az == 0) { m = 0; y = 1; } if (m == 0) { if (x > 0) rest[r] |= (1L << r1); if (r1 < 63) r1++; else { r1 = 0; r++; } if (y > 0) rest[r] |= (1L << r1); if (r1 < 63) r1++; else { r1 = 0; r++; } } else rest[s] |= (1L << s1); if (s1 < 63) s1++; else { s1 = 0; s++; } } if (i <= g && TAB[i].az == 0) rest[r] |= (1L << r1); return rest; } /* * Hier werden alle aktiven Zahlen als 9-Bit-Zahlen festgehalten (Methode fuer nur wenige aktive Zahlen): */ static long[] restAktiv9(final int DIM, final D DS) { long[] rest = new long[DIM]; final int G = g; final T[] TAB = DS.tab; int i = 2, r = 0, r1 = 2; for (; i <= G; i++) { if (TAB[i].az > 0) { // aktiv rest[r] |= i; if (r1 < 6) { rest[r] <<= 9; r1++; } else { r1 = 0; r++; } } } rest[0] <<= 16; rest[0] |= DS.pts; return rest; } /* * Hier werden alle nicht aktiven Zahlen als 9-Bit-Zahlen festgehalten (Methode fuer nur wenige nicht aktive * Zahlen): */ static long[] restInaktiv9(final int DIM, final D DS) { long[] rest = new long[DIM]; final int G = g; final T[] TAB = DS.tab; int i = 2, r = 0, r1 = 2; for (; i <= G; i++) { if (TAB[i].az == 0) { // nicht aktiv rest[r] |= i; if (r1 < 6) { rest[r] <<= 9; r1++; } else { r1 = 0; r++; } } } rest[0] <<= 16; rest[0] |= DS.pts; return rest; } /* * Aus den Zahlen, die Schritt 1(B) uebrig laesst, werden hier die Zahlen zur Verzweigung des Suchbaums bestimmt: * Dieser Test unterscheidet grundsaetzlich zwischen Zahlen mit genau einem aktiven echten Teiler und Zahlen mit * mehr als einem aktiven echten Teiler. Bei mehr als einem Teiler kann man statt der Zahl den kleinsten aktiven * Teiler auswaehlen. So lassen sich mehrere Zweige zusammenfassen. Der Fall einer Zahl mit genau zwei aktiven * echten Teilern wird zuerst behandelt und dabei der kleinste und auch der groesste (echte aktive) Teiler * festgehalten. Im anschliessenden Fall der Zahlen mit genau einem aktiven echten Teiler duerfen Zahl und Teiler * nicht mit einem zuvor notierten groessten und kleinsten Teiler uebereinstimmen. */ static short[] verzweigungen(final D DS) { short[] res = new short[DS.aktiv]; int[] ket = new int[DS.aktiv >> 1], // kleine echte Teiler nres = new int[DS.aktiv >> 2]; // was nicht in res soll final T[] TAB = DS.tab; // int ir = 0, ik = 0, inr = 0, az, t1, t2; int ir = 0, ik = 0, inr = 0, t1, t2; for (int i = g; i > 3; i--) if (TAB[i].az == 3) { t2 = TAB[i].groesste(); if (TAB[t2].az > 1) nres[inr++] = t2; // d.h. t2 % t1 = 0 t1 = TAB[i].kleinste(); if (enthaelt(ket, t1, ik) || enthaelt(ket, t2, ik)) continue; ket[ik++] = t1; } for (int i = g2; i > 3; i--) // die 2er der unteren Haelfte // if ((az = TAB[i].az) == 2 && !enthaelt(nres, i, inr)) if ((TAB[i].az) == 2 && !enthaelt(nres, i, inr)) res[ir++] = (short) i; for (int i = g; i > 3; i--) // if ((az = TAB[i].az) > 3 && kandidat(i, TAB)) { if ((TAB[i].az) > 3 && kandidat(i, TAB)) { t1 = TAB[i].kleinste(); if (!enthaelt(ket, t1, ik)) ket[ik++] = t1; } // erst die Zahlen, dann die kleinen Teiler: for (int k = 0, r = ir; k < ik; k++) res[r++] = (short) ket[k]; return res; } // ist N in A ? static boolean enthaelt(final int[] A, final int N, final int ENDE) { for (int i = 0; i < ENDE; i++) if (A[i] == N) return true; return false; } /* * Eine Zahl mit mehr als zwei aktiven echten Teilern, die unter diesen einen hat, der einen anderen teilt, muss * diesmal nicht in die Auswahl genommen werden. kandidat gibt dann false zurueck. Dieser Test nutzt die Tatsache, * dass die Teilermenge einer Zahl die Teilermengen ihrer Teiler vollstaendig enhaelt. */ static boolean kandidat(final int K, final T[] TAB) { for (int i : TAB[K].tm) if (i != 0 && TAB[i].az > 1) return false; return true; } static class VZW extends D implements Runnable { int vzw; VZW(int vzw, D ds) { super(ds.hai, ds.pts, ds.seq2, ds.tab, ds.az, ds.aktiv); this.vzw = vzw; } @Override public void run() { // stop = System.currentTimeMillis(); // System.out.print(vzw+":"+((stop-start)/1000)+"s:"); setze(vzw); runterzaehlen(); if (semiseq) { int n = vzw1Pop(); if (n > 0) xs.execute(new VZW(n, kopie())); } } } // Ende class VZW // Thread-geschuetztes Herunterzaehlen des globalen Instanzen-Zaehlers: static synchronized void runterzaehlen() { azVZW--; } // Thread-geschuetzter Zugriff auf die globale Liste vzw1: static synchronized int vzw1Pop() { if (vzw1.isEmpty()) return -1; return vzw1.remove(); } /* * Es wird versucht, den Rest in die Datenbank einzufuegen. Dies gelingt nur, wenn der Rest noch nicht vorhanden ist * oder wenn der Zwischenstand mehr Punkte aufweist. In beiden Faellen wird true zurueck gegeben: * (Thread-geschuetzter Zugriff auf die Datenbank) */ static synchronized boolean dbEinfuegen(final long[] REST, final int AKTIV) { if (db[AKTIV] == null) { db[AKTIV] = new R(REST); // Wurzel anlegen return true; } return db[AKTIV].dbEinfuegen(REST); } /* * Die verbleibenden noch aktiven Zahlen ('Reste') werden um die bisher erreichten Punkte und um rekursive * Referenzen erweitert. R[] db implementiert eine Datenbank fuer Reste, so dass eine identische Aufgabe nicht ein * zweites Mal gerechnet werden muss. Der Index des Arrays entspricht dabei der Laenge des Rest-Arrays. db[i] * erhaelt die Struktur eines Binaerbaums und die Methoden dbEinfuegen(..) greifen - da diese Baeume aufgrund der * praktisch zufaelligen Reihenfolge an Zahlen recht gut ausbalanciert sind - mit einer Laufzeit vom Typ O(log(N)) * auf db[i] zu. (Die Verwendung eines AVL- oder Rot-Schwarz-Baums bringt hier keinen Vorteil.) */ static class R { // erweiterter Rest long[] rest; // die uebrig gebliebenen Zahlen, rest[0] = Punkte R links, rechts; R(long[] rest) { this.rest = rest; links = rechts = null; } // Einfuegen in Baum mit existierender Wurzel: boolean dbEinfuegen(final long[] REST) { long v = vergleiche(rest, REST); if (v > 0) { if (rechts == null) rechts = new R(REST); else return rechts.dbEinfuegen(REST); } else if (v < 0) { if (links == null) links = new R(REST); else return links.dbEinfuegen(REST); } else if ((rest[0] & 65535L) < (REST[0] & 65535L)) { rest[0] &= -65536L; // 16 Bits rechts nullen rest[0] |= (REST[0] & 65535L); } // (0x000000000000ffffL = 65535, 0xffffffffffff0000L = -65536L) else return false; return true; } } // 'compareTo' fuer zwei Reste: static long vergleiche(final long[] A, final long[] B) { if ((A[0] & -65536L) - (B[0] & -65536L) != 0) // 16 Bits rechts .. return (A[0] & -65536L) - (B[0] & -65536L); // .. = ds.pts for (int i = 1; i < B.length; i++) if (A[i] - B[i] != 0) return A[i] - B[i]; return 0; } /* * Der senkrechte Strich dient in der Ausgabe als Information ueber das Ende der ersten Ausfuehrung des Schritts 1: */ static void ausgabe(final String ARG) { // ggf. den Beduerfnissen anpassen String s = ""; for (int i : folge1) s += i + ",";/* * if (folge2.length == 0) s += "]"+ARG; */ if (folge2.length != 0) { int i = 1; // folge2[0] speichert Anzahl for (; i < folge2[0]; i++) s += folge2[i] + ","; s += folge2[i] + ","; } s = s.substring(0, s.length() - 1); output[g - von][0] = "" + g; output[g - von][1] = "" + max; output[g - von][2] = "" + haiMax; output[g - von][3] = "" + s; } static final short[] PRIM = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509 }; /* * Werte, die die moeglich-Methode verwendet: Je naeher die Werte den tatsaechlichen Bestwerten sind, um so * schneller kann die Methode moeglich() alle unbrauchbare Zweige abschneiden. (Die hier aufgefuehrten stimmen * natuerlich mit den Bestwerten ueberein.) */ static final int[][] U_SCHRANKE = { /* 0,0 */{ 0, 0 }, // /* g, haiMax */ {max, seq-Laenge} /* 1,1 */{ 0, 1 }, /* 2,1 */{ 2, 1 }, // prim /* 3,3 */{ 3, 1 }, // prim /* 4,3 */{ 7, 2 }, // 2*2 /* 5,6 */{ 9, 2 }, // prim /* 6,6 */{ 15, 3 }, // 2*3 /* 7,11 */{ 17, 3 }, // prim /* 8,15 */{ 21, 3 }, /* 9,15 */{ 30, 4 }, /* 10,15 */{ 40, 5 }, // 2*5 /* 11,22 */{ 44, 5 }, // prim /* 12,28 */{ 50, 5 }, /* 13,39 */{ 52, 5 }, // prim /* 14,39 */{ 66, 6 }, // 2*7 /* 15,39 */{ 81, 7 }, /* 16,47 */{ 89, 7 }, /* 17,60 */{ 93, 7 }, // prim /* 18,60 */{ 111, 8 }, /* 19,77 */{ 113, 8 }, // prim /* 20,86 */{ 124, 8 }, /* 21,87 */{ 144, 9 }, /* 22,87 */{ 166, 10 }, // 2*11 /* 23,106 */{ 170, 10 }, // prim /* 24,118 */{ 182, 10 }, /* 25,127 */{ 198, 10 }, /* 26,127 */{ 224, 11 }, // 2*13 /* 27,127 */{ 251, 12 }, /* 28,127 */{ 279, 13 }, /* 29,150 */{ 285, 13 }, // prim /* 30,164 */{ 301, 13 }, /* 31,193 */{ 303, 13 }, // prim /* 32,209 */{ 319, 13 }, /* 33,209 */{ 352, 14 }, /* 34,209 */{ 386, 15 }, // 2*17 /* 35,212 */{ 418, 16 }, /* 36,224 */{ 442, 16 }, /* 37,255 */{ 448, 16 }, // prim /* 38,255 */{ 486, 17 }, // 2*19 /* 39,277 */{ 503, 17 }, /* 40,295 */{ 525, 17 }, /* 41,332 */{ 529, 17 }, // prim /* 42,332 */{ 571, 18 }, /* 43,373 */{ 573, 18 }, // prim /* 44,373 */{ 617, 19 }, // 2*22 (22: PP bis 43) /* 45,375 */{ 660, 20 }, /* 46,375 */{ 706, 21 }, // 2*23 /* 47,418 */{ 710, 21 }, // prim /* 48,442 */{ 734, 21 }, /* 49,467 */{ 758, 21 }, /* 50,467 */{ 808, 22 }, // 2*25 (25: PP bis 49) /* 51,493 */{ 833, 22 }, /* 52,493 */{ 885, 23 }, // 2*26 (26: PP bis 51) /* 53,540 */{ 891, 23 }, // prim /* 54,545 */{ 940, 24 }, /* 55,559 */{ 981, 24 }, /* 56,579 */{ 1017, 24 }, /* 57,613 */{ 1040, 24 }, /* 58,613 */{ 1098, 25 }, // 2*29 /* 59,666 */{ 1104, 25 }, // prim /* 60,693 */{ 1137, 25 }, /* 61,752 */{ 1139, 25 }, // prim /* 62,752 */{ 1201, 26 }, // 2*31 /* 63,752 */{ 1264, 27 }, /* 64,784 */{ 1296, 27 }, /* 65,817 */{ 1328, 27 }, /* 66,817 */{ 1394, 28 }, // 2*33 (33: PP bis 65) /* 67,878 */{ 1400, 28 }, // prim /* 68,878 */{ 1468, 29 }, // 2*34 (34: PP bis 67) /* 69,916 */{ 1499, 29 }, /* 70,919 */{ 1566, 30 }, /* 71,986 */{ 1570, 30 }, // prim /* 72,986 */{ 1642, 31 }, /* 73,105 */{ 1644, 31 }, // prim /* 74,105 */{ 1718, 32 }, // 2*37 /* 75,105 */{ 1793, 33 }, /* 76,105 */{ 1869, 34 }, // 2*38 (38: PP bis 75) /* 77,1089 */{ 1914, 34 }, /* 78,1090 */{ 1991, 35 }, /* 79,1163 */{ 1997, 35 }, // prim /* 80,1199 */{ 2041, 35 }, /* 81,1216 */{ 2105, 36 }, /* 82,1216 */{ 2187, 37 }, // 2*41 /* 83,1295 */{ 2191, 37 }, // prim /* 84,1307 */{ 2263, 37 }, /* 85,1346 */{ 2309, 37 }, /* 86,1346 */{ 2395, 38 }, // 2*43 /* 87,1392 */{ 2436, 38 }, /* 88,1420 */{ 2496, 38 }, /* 89,1503 */{ 2502, 38 }, // prim /* 90,1543 */{ 2552, 38 }, /* 91,1598 */{ 2588, 38 }, /* 92,1598 */{ 2680, 39 }, // 2*46 (46: PP bis 91) /* 93,1656 */{ 2715, 39 }, /* 94,1656 */{ 2809, 40 }, // 2*47 /* 95,1707 */{ 2853, 40 }, /* 96,1755 */{ 2901, 40 }, /* 97,1844 */{ 2909, 40 }, // prim /* 98,1844 */{ 3007, 41 }, /* 99,1844 */{ 3106, 42 }, /* 100,188 */{ 3164, 42 }, /* 101,198 */{ 3168, 42 }, // prim /* 102,198 */{ 3270, 43 }, // 2*51 (51: PP bis 101) /* 103,208 */{ 3272, 43 }, // prim /* 104,212 */{ 3332, 43 }, /* 105,213 */{ 3434, 44 }, /* 106,213 */{ 3540, 45 }, // 2*53 /* 107,223 */{ 3544, 45 }, // prim /* 108,223 */{ 3652, 46 }, /* 109,234 */{ 3654, 46 }, // prim /* 110,234 */{ 3764, 47 }, // 2*55 (55: PP bis 109) /* 111,240 */{ 3813, 47 }, /* 112,240 */{ 3925, 48 }, /* 113,251 */{ 3929, 48 }, // prim /* 114,251 */{ 4043, 49 }, /* 115,256 */{ 4101, 49 }, /* 116,256 */{ 4217, 50 }, // 2*58 (58: PP bis 115) /* 117,256 */{ 4334, 51 }, /* 118,256 */{ 4452, 52 }, // 2*59 /* 119,263 */{ 4506, 52 }, /* 120,266 */{ 4593, 53 }, /* 121,269 */{ 4689, 53 }, /* 122,269 */{ 4811, 54 }, // 2*61 /* 123,276 */{ 4860, 54 }, /* 124,276 */{ 4984, 55 }, // 2*62 (62: PP bis 123) /* 125,276 */{ 5109, 56 }, /* 126,281 */{ 5191, 56 }, /* 127,292 */{ 5205, 56 }, // prim /* 128,295 */{ 5301, 57 }, /* 129,303 */{ 5348, 57 }, /* 130,303 */{ 5478, 58 }, // 2*65 (65: PP bis 129) /* 131,316 */{ 5482, 58 }, // prim /* 132,3206 */{ 5572, 58 }, /* 133,3291 */{ 5620, 58 }, /* 134,3291 */{ 5754, 59 }, // 2*67 /* 135,3336 */{ 5844, 59 }, /* 136,3388 */{ 5928, 59 }, /* 137,3519 */{ 5934, 59 }, // prim /* 138,3519 */{ 6072, 60 }, /* 139,3656 */{ 6074, 60 }, // prim /* 140,3706 */{ 6164, 60 }, /* 141,3792 */{ 6219, 60 }, /* 142,3792 */{ 6361, 61 }, // 2*71 /* 143,3869 */{ 6427, 61 }, /* 144,3917 */{ 6523, 61 }, /* 145,3986 */{ 6599, 61 }, /* 146,3986 */{ 6745, 62 }, // 2*73 /* 147,3986 */{ 6892, 63 }, /* 148,3986 */{ 7040, 64 }, // 2*74 (74: PP bis 147) /* 149,4125 */{ 7050, 64 }, // prim /* 150,4188 */{ 7137, 64 }, /* 151,4337 */{ 7139, 64 }, // prim /* 152,4405 */{ 7223, 64 }, /* 153,4405 */{ 7376, 65 }, /* 154,4405 */{ 7530, 66 }, // 2*77 (77: PP bis 153) /* 155,4492 */{ 7598, 66 }, /* 156,4558 */{ 7688, 66 }, /* 157,4709 */{ 7694, 66 }, // prim /* 158,4709 */{ 7852, 67 }, // 2*79 /* 159,4803 */{ 7917, 67 }, /* 160,4875 */{ 8005, 67 }, /* 161,4970 */{ 8071, 67 }, /* 162,4970 */{ 8233, 68 }, /* 163,5127 */{ 8239, 68 }, // prim /* 164,5127 */{ 8403, 69 }, /* 165,5127 */{ 8568, 70 }, /* 166,5127 */{ 8734, 71 }, // 2*83 /* 167,5290 */{ 8738, 71 }, // prim /* 168,5290 */{ 8906, 72 }, /* 169,5411 */{ 8954, 72 }, /* 170,5411 */{ 9124, 73 }, /* 171,5411 */{ 9295, 74 }, /* 172,5411 */{ 9467, 75 }, /* 173,5578 */{ 9473, 75 }, // prim /* 174,5578 */{ 9647, 76 }, /* 175,5578 */{ 9822, 77 }, /* 176,5591 */{ 9985, 78 }, /* 177,5697 */{ 10056, 78 }, /* 178,5697 */{ 10234, 79 }, // 2*89 /* 179,5870 */{ 10240, 79 }, // prim /* 180,5889 */{ 10401, 80 }, /* 181,6068 */{ 10403, 80 }, // prim /* 182,6110 */{ 10543, 80 }, /* 183,6228 */{ 10608, 80 }, /* 184,6276 */{ 10744, 81 }, /* 185,6369 */{ 10836, 81 }, /* 186,6369 */{ 11022, 82 }, /* 187,6446 */{ 11132, 82 }, /* 188,6446 */{ 11320, 83 }, /* 189,6508 */{ 11447, 83 }, /* 190,6508 */{ 11637, 84 }, /* 191,6689 */{ 11647, 84 }, // prim /* 192,6741 */{ 11787, 85 }, /* 193,6932 */{ 11789, 85 }, // prim /* 194,6932 */{ 11983, 86 }, // 2*97 /* 195,6946 */{ 12164, 87 }, /* 196,6974 */{ 12332, 87 }, /* 197,7167 */{ 12336, 87 }, // prim /* 198,7230 */{ 12471, 87 }, /* 199,7427 */{ 12473, 87 }, // prim /* 200,7452 */{ 12648, 88 }, /* 201,7574 */{ 12727, 88 }, // rest /* 202,7574 */{ 12929, 89 }, // rest 2*101 /* 203,7689 */{ 13017, 89 }, // rest /* 204,7764 */{ 13146, 89 }, /* 205,7875 */{ 13240, 89 }, // rest /* 206,7875 */{ 13446, 90 }, // rest 2*103 /* 207,7875 */{ 13653, 91 }, /* 208,7904 */{ 13832, 92 }, /* 209,8023 */{ 13922, 92 }, // rest /* 210,8089 */{ 14066, 92 }, /* 211,8288 */{ 14078, 92 }, // rest prim /* 212,8288 */{ 14290, 93 }, // cut 2*106 (106=2*53 PP bis 211) /* 213,8422 */{ 14369, 93 }, // rest /* 214,8422 */{ 14583, 94 }, // rest /* 215,8545 */{ 14675, 94 }, // rest /* 216,8602 */{ 14834, 94 }, /* 217,8747 */{ 14906, 94 }, // rest /* 218,8747 */{ 15124, 95 }, // rest 2*109 /* 219,8889 */{ 15201, 95 }, // rest /* 220,8964 */{ 15346, 95 }, /* 221,9107 */{ 15424, 95 }, // rest 13*17-11*13:+78 /* 222,9107 */{ 15646, 96 }, // cut 2*111 (111=3*37 PP bis 221) /* 223,9318 */{ 15658, 96 }, // rest prim:+12 /* 224,9373 */{ 15827, 96 }, /* 225,9473 */{ 15952, 96 }, /* 226,9473 */{ 16178, 97 }, // rest 2*113 +226 /* 227,9696 */{ 16182, 97 }, // rest prim:+4 /* 228,9798 */{ 16308, 97 }, /* 229,10025 */{ 16310, 97 }, // rest prim:+2 /* 230,10025 */{ 16540, 98 }, // cut /* 231,10025 */{ 16771, 99 }, // cut /* 232,10117 */{ 16911, 99 }, /* 233,10346 */{ 16915, 99 }, // rest prim:+4 /* 234,10427 */{ 17068, 99 }, /* 235,10556 */{ 17174, 99 }, // rest 5*47-3*43=+106 /* 236,10556 */{ 17410, 100 }, // cut 2*118 (PP bis 235) +236 /* 237,10702 */{ 17501, 100 }, // rest 3*79-2*73:+91 /* 238,10702 */{ 17739, 101 }, // cut 2*119 (PP bis 237) +238 /* 239,10935 */{ 17745, 101 }, // rest prim:+6 /* 240,11043 */{ 17877, 101 }, /* 241,11283 */{ 17879, 101 }, // rest prim:+2 /* 242,11282 */{ 18121, 102 }, // cut 2*121:+242 /* 243,11282 */{ 18364, 103 }, // cut /* 244,11282 */{ 18608, 104 }, // cut 2*122:+244 /* 245,11282 */{ 18853, 105 }, // cut /* 246,11282 */{ 19099, 106 }, // cut 2*123:+246 /* 247,11469 */{ 19159, 106 }, // rest 13*19-11*17:+60 /* 248,11585 */{ 19291, 106 }, /* 249,11743 */{ 19382, 106 }, // rest 3*83-2*79:+91 /* 250,11842 */{ 19533, 106 }, /* 251,12083 */{ 19543, 106 }, // prim:+10 /* 252,12083 */{ 19795, 107 }, // cut:+252 /* 253,12216 */{ 19915, 107 }, // rest 11*23-7*19:+120 /* 254,12216 */{ 20169, 108 }, // 2*127:+254 /* 255,12216 */{ 20424, 109 }, // cut:+255 /* 256,12344 */{ 20552, 109 }, // +128 /* 257,12595 */{ 20558, 109 }, // prim:+6 /* 258,12595 */{ 20816, 110 }, // cut 2*129:+258 /* 259,12750 */{ 20920, 110 }, // rest 7*37-5*31:+104 /* 260,12855 */{ 21075, 110 }, /* 261,12855 */{ 21336, 111 }, // cut /* 262,12855 */{ 21598, 112 }, // rest 2*131:+262 /* 263,13112 */{ 21604, 112 }, // prim:+6 /* 264,13121 */{ 21859, 113 }, /* 265,13262 */{ 21983, 113 }, // rest /* 266,13262 */{ 22249, 114 }, // cut:+266 /* 267,13428 */{ 22350, 114 }, // rest /* 268,13428 */{ 22618, 115 }, // cut:+268 /* 269,13691 */{ 22624, 115 }, // prim:+6 /* 270,13691 */{ 22894, 116 }, // cut:+270 /* 271,13960 */{ 22896, 116 }, // prim:+2 /* 272,13986 */{ 23142, 117 }, /* 273,13997 */{ 23404, 118 }, /* 274,13997 */{ 23678, 119 }, // rest:2*137:+274 /* 275,13997 */{ 23953, 120 }, // cut:+275 /* 276,14111 */{ 24115, 120 }, /* 277,14382 */{ 24121, 120 }, // prim:+6, /* 278,14382 */{ 24399, 121 }, // rest:2*139:+278 /* 279,14382 */{ 24678, 122 }, // cut /* 280,14406 */{ 24934, 123 }, /* 281,14683 */{ 24938, 123 }, // prim:+4, /* 282,14683 */{ 25220, 124 }, // cut /* 283,14964 */{ 25222, 124 }, // prim:+2, /* 284,14964 */{ 25506, 125 }, // cut /* 285,14964 */{ 25791, 126 }, // cut /* 286,14964 */{ 26077, 127 }, // cut /* 287,15149 */{ 26179, 127 }, /* 288,15221 */{ 26395, 127 }, /* 289,15390 */{ 26515, 127 }, /* 290,15390 */{ 26805, 128 }, /* 291,15568 */{ 26918, 128 }, /* 292,15568 */{ 27210, 129 }, /* 293,15851 */{ 27220, 129 }, // prim:+10 /* 294,15851 */{ 27514, 130 }, /* 295,16010 */{ 27650, 130 }, /* 296,16134 */{ 27822, 130 }, /* 297,16212 */{ 28041, 130 }, /* 298,16212 */{ 28339, 131 }, /* 299,16421 */{ 28429, 131 }, /* 300,16459 */{ 28691, 132 }, /* 301,16664 */{ 28787, 132 }, /* 302,16664 */{ 29089, 133 }, /* 303,16858 */{ 29198, 133 }, /* 304,16930 */{ 29430, 134 }, /* 305,17107 */{ 29558, 134 }, /* 306,17175 */{ 29796, 134 }, /* 307,17468 */{ 29810, 134 }, // prim:+14 /* 308,17555 */{ 30031, 134 }, /* 309,17757 */{ 30138, 134 }, /* 310,17757 */{ 30448, 135 }, /* 311,18064 */{ 30452, 135 }, // prim:+4 /* 312,18109 */{ 30719, 136 }, /* 313,18420 */{ 30721, 136 }, // prim:+2 /* 314,18420 */{ 31035, 137 }, // rest /* 315,18522 */{ 31248, 137 }, /* 316,18522 */{ 31564, 138 }, // cut /* 317,18835 */{ 31568, 138 }, // prim:+4 /* 318,18835 */{ 31886, 139 }, // cut /* 319,18996 */{ 32044, 139 }, // rest /* 320,19071 */{ 32289, 140 }, /* 321,19277 */{ 32404, 140 }, // rest /* 322,19277 */{ 32726, 141 }, // cut /* 323,19498 */{ 32828, 141 }, // rest:+102 (221 neue PP: 323-221=102) /* 324,19576 */{ 33074, 141 }, /* 325,19579 */{ 33396, 142 }, /* 326,19579 */{ 33722, 143 }, // cut:+326 (2*163;prim) /* 327,19793 */{ 33835, 143 }, // 214 neue PP /* 328,19941 */{ 34015, 143 }, /* 329,20156 */{ 34129, 143 }, // rest:+114 (215 neue PP: 329-215=114) /* 330,20261 */{ 34354, 143 }, /* 331,20578 */{ 34368, 143 }, // prim:+14 /* 332,20578 */{ 34700, 144 }, // cut:+332 (2*166 PP seit 267) /* 333,20578 */{ 35033, 145 }, // cut:+333 /* 334,20578 */{ 35367, 146 }, // rest/cut:+334 (334=2*167;prim) /* 335,20761 */{ 35519, 146 }, // rest:+152 (183 neue PP: 335-183=152) /* 336,20842 */{ 35774, 146 }, /* 337,21173 */{ 35780, 146 }, // prim:+6 /* 338,21173 */{ 36118, 147 }, // cut 2*13*13:+338 PP (17*17=289) /* 339,21391 */{ 36239, 147 }, // rest:+121 (218 neue PP: 339-218=121) /* 340,21521 */{ 36449, 147 }, /* 341,21724 */{ 36587, 147 }, // rest:+138 (203 ist neue PP: 341-203=138) /* 342,21826 */{ 36827, 147 }, /* 343,21826 */{ 37170, 148 }, // cut: +343 /* 344,21990 */{ 37350, 148 }, /* 345,21990 */{ 37695, 149 }, // cut: +345 /* 346,21990 */{ 38041, 150 }, // rest/cut:+346:(2*173; prim) /* 347,22327 */{ 38051, 150 }, // rest, prim:+10 /* 348,22465 */{ 38261, 150 }, /* 349,22812 */{ 38263, 150 }, // rest, prim:+2 /* 350,22962 */{ 38463, 150 }, /* 351,23061 */{ 38715, 150 }, /* 352,23173 */{ 38955, 150 }, /* 353,23522 */{ 38959, 150 }, // rest, prim:+4 /* 354,23522 */{ 39313, 151 }, // cut: +354 (2*177; PP bis 353) /* 355,23723 */{ 39467, 151 }, // rest:+154 (201 neue PP: 355-201=154) /* 356,23723 */{ 39823, 152 }, // cut: +356 (2*178; PP bis 355) /* 357,23736 */{ 40167, 153 }, /* 358,23736 */{ 40525, 154 }, // rest/cut: +358 (2*179; prim) /* 359,24089 */{ 40531, 154 }, // rest, prim:+6 /* * --------------------------------------------------------------------------- Alle folgenden Punktzahlen * wurden mit Hilfe einer unzulaessigen Vereinfachung berechnet u. sind daher nicht 100 % sicher. */ /* 360,24249 */{ 40731, 154 }, /* 361,24538 */{ 40803, 154 }, // rest:+72 (289 neue PP: 361-289=72) /* 362,24538 */{ 41165, 155 }, // rest/cut: +362 (2*181; prim) /* 363,24538 */{ 41528, 156 }, // cut: +363 /* 364,24661 */{ 41769, 156 }, /* 365,24874 */{ 41921, 156 }, // rest:+152 (213 neue PP: 365-213=152) /* 366,24874 */{ 42287, 157 }, // cut: +366 (2*183; PP bis 365) /* 367,25233 */{ 42295, 157 }, // rest, prim:+8 /* 368,25271 */{ 42625, 158 }, /* 369,25271 */{ 42994, 159 }, // cut: +369 /* 370,25271 */{ 43364, 160 }, // cut: +370 (2*185; PP bis 369) /* 371,25506 */{ 43500, 160 }, // rest:+136 (235 ist neue PP: 371-235=136) /* 372,25680 */{ 43698, 160 }, /* 373,26047 */{ 43704, 160 }, // rest, prim:+6 /* 374,26047 */{ 44078, 161 }, // cut: +378 (2*187; PP bis 373) /* 375,26172 */{ 44328, 161 }, /* 376,26344 */{ 44532, 161 }, /* 377,26597 */{ 44656, 161 }, // rest:+124 (253 ist neue PP: 377-253=124) /* 378,26597 */{ 45034, 162 }, // cut: +378 /* 379,26970 */{ 45040, 162 } // rest, prim:+6 }; /* * Die vorliegende Version des Programms ist auf optimale Punkte bis 65535 beschraenkt. */ public static int getStoppedAt() { return stoppedAt; } public static String[][] getOutput() { return output; } public static void setOutput(String[][] output) { ZahlenhaiBestwerte.output = output; } }
jcryptool/crypto
org.jcryptool.games.numbershark/src/org/jcryptool/games/numbershark/strategies/ZahlenhaiBestwerte.java
214,335
/* * Ki-Tax: System for the management of external childcare subsidies * Copyright (C) 2017 City of Bern Switzerland * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package ch.dvbern.ebegu.api.dtos; import java.time.LocalDate; import java.time.LocalDateTime; import java.util.LinkedHashSet; import java.util.Set; import javax.annotation.Nullable; import javax.validation.constraints.NotNull; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import ch.dvbern.ebegu.enums.AntragStatusDTO; import ch.dvbern.ebegu.enums.AntragTyp; import ch.dvbern.ebegu.enums.Eingangsart; import ch.dvbern.ebegu.enums.FinSitStatus; import ch.dvbern.ebegu.enums.GesuchBetreuungenStatus; import ch.dvbern.lib.date.converters.LocalDateTimeXMLConverter; import ch.dvbern.lib.date.converters.LocalDateXMLConverter; /** * DTO fuer Faelle */ @XmlRootElement(name = "gesuch") @XmlAccessorType(XmlAccessType.FIELD) public class JaxGesuch extends JaxAbstractDTO { private static final long serialVersionUID = -1217019901364130097L; @NotNull private JaxFall fall; @NotNull private JaxGesuchsperiode gesuchsperiode; @Nullable @XmlJavaTypeAdapter(LocalDateXMLConverter.class) private LocalDate eingangsdatum = null; @Nullable @XmlJavaTypeAdapter(LocalDateXMLConverter.class) private LocalDate eingangsdatumSTV = null; @Nullable @XmlJavaTypeAdapter(LocalDateXMLConverter.class) private LocalDate freigabeDatum = null; @NotNull private AntragStatusDTO status; @NotNull private AntragTyp typ; @NotNull private Eingangsart eingangsart; @Nullable private JaxGesuchstellerContainer gesuchsteller1; @Nullable private JaxGesuchstellerContainer gesuchsteller2; @NotNull private Set<JaxKindContainer> kindContainers = new LinkedHashSet<>(); @Nullable private JaxFamiliensituationContainer familiensituationContainer; @Nullable private JaxEinkommensverschlechterungInfoContainer einkommensverschlechterungInfoContainer; @Nullable private String bemerkungen; @Nullable private String bemerkungenSTV; @Nullable private String bemerkungenPruefungSTV; private int laufnummer; private boolean geprueftSTV; private boolean hasFSDokument; @Nullable private FinSitStatus finSitStatus; private boolean gesperrtWegenBeschwerde; @Nullable @XmlJavaTypeAdapter(LocalDateXMLConverter.class) private LocalDate datumGewarntNichtFreigegeben; @Nullable @XmlJavaTypeAdapter(LocalDateXMLConverter.class) private LocalDate datumGewarntFehlendeQuittung; @Nullable @XmlJavaTypeAdapter(LocalDateTimeXMLConverter.class) private LocalDateTime timestampVerfuegt; private boolean gueltig; @Nullable @XmlJavaTypeAdapter(LocalDateXMLConverter.class) private LocalDate fristverlaengerung; private boolean dokumenteHochgeladen; @NotNull private GesuchBetreuungenStatus gesuchBetreuungenStatus = GesuchBetreuungenStatus.ALLE_BESTAETIGT; public static long getSerialVersionUID() { return serialVersionUID; } @Nullable public JaxGesuchstellerContainer getGesuchsteller1() { return gesuchsteller1; } public void setGesuchsteller1(@Nullable final JaxGesuchstellerContainer gesuchsteller1) { this.gesuchsteller1 = gesuchsteller1; } @Nullable public JaxGesuchstellerContainer getGesuchsteller2() { return gesuchsteller2; } public void setGesuchsteller2(@Nullable final JaxGesuchstellerContainer gesuchsteller2) { this.gesuchsteller2 = gesuchsteller2; } public Set<JaxKindContainer> getKindContainers() { return kindContainers; } public void setKindContainers(final Set<JaxKindContainer> kindContainers) { this.kindContainers = kindContainers; } @Nullable public JaxFamiliensituationContainer getFamiliensituationContainer() { return familiensituationContainer; } public void setFamiliensituationContainer(@Nullable JaxFamiliensituationContainer familiensituationContainer) { this.familiensituationContainer = familiensituationContainer; } @Nullable public JaxEinkommensverschlechterungInfoContainer getEinkommensverschlechterungInfoContainer() { return einkommensverschlechterungInfoContainer; } public void setEinkommensverschlechterungInfoContainer(@Nullable final JaxEinkommensverschlechterungInfoContainer einkommensverschlechterungInfoContainer) { this.einkommensverschlechterungInfoContainer = einkommensverschlechterungInfoContainer; } @Nullable public String getBemerkungen() { return bemerkungen; } public void setBemerkungen(@Nullable String bemerkungen) { this.bemerkungen = bemerkungen; } @Nullable public String getBemerkungenSTV() { return bemerkungenSTV; } public void setBemerkungenSTV(@Nullable String bemerkungenSTV) { this.bemerkungenSTV = bemerkungenSTV; } @Nullable public String getBemerkungenPruefungSTV() { return bemerkungenPruefungSTV; } public void setBemerkungenPruefungSTV(@Nullable String bemerkungenPruefungSTV) { this.bemerkungenPruefungSTV = bemerkungenPruefungSTV; } public int getLaufnummer() { return laufnummer; } public void setLaufnummer(int laufnummer) { this.laufnummer = laufnummer; } public boolean isGeprueftSTV() { return geprueftSTV; } public void setGeprueftSTV(boolean geprueftSTV) { this.geprueftSTV = geprueftSTV; } public boolean isHasFSDokument() { return hasFSDokument; } public void setHasFSDokument(boolean hasFSDokument) { this.hasFSDokument = hasFSDokument; } public boolean isGesperrtWegenBeschwerde() { return gesperrtWegenBeschwerde; } public void setGesperrtWegenBeschwerde(boolean gesperrtWegenBeschwerde) { this.gesperrtWegenBeschwerde = gesperrtWegenBeschwerde; } @Nullable public LocalDate getDatumGewarntNichtFreigegeben() { return datumGewarntNichtFreigegeben; } public void setDatumGewarntNichtFreigegeben(@Nullable LocalDate datumGewarntNichtFreigegeben) { this.datumGewarntNichtFreigegeben = datumGewarntNichtFreigegeben; } @Nullable public LocalDate getDatumGewarntFehlendeQuittung() { return datumGewarntFehlendeQuittung; } public void setDatumGewarntFehlendeQuittung(@Nullable LocalDate datumGewarntFehlendeQuittung) { this.datumGewarntFehlendeQuittung = datumGewarntFehlendeQuittung; } @Nullable public LocalDateTime getTimestampVerfuegt() { return timestampVerfuegt; } public void setTimestampVerfuegt(@Nullable LocalDateTime timestampVerfuegt) { this.timestampVerfuegt = timestampVerfuegt; } public boolean isGueltig() { return gueltig; } public void setGueltig(boolean gueltig) { this.gueltig = gueltig; } @Nullable public LocalDate getFristverlaengerung() { return fristverlaengerung; } public void setFristverlaengerung(@Nullable LocalDate fristverlaengerung) { this.fristverlaengerung = fristverlaengerung; } public GesuchBetreuungenStatus getGesuchBetreuungenStatus() { return gesuchBetreuungenStatus; } public void setGesuchBetreuungenStatus(GesuchBetreuungenStatus gesuchBetreuungenStatus) { this.gesuchBetreuungenStatus = gesuchBetreuungenStatus; } public JaxFall getFall() { return fall; } public void setFall(JaxFall fall) { this.fall = fall; } public JaxGesuchsperiode getGesuchsperiode() { return gesuchsperiode; } public void setGesuchsperiode(JaxGesuchsperiode gesuchsperiode) { this.gesuchsperiode = gesuchsperiode; } @Nullable public LocalDate getEingangsdatum() { return eingangsdatum; } public void setEingangsdatum(@Nullable LocalDate eingangsdatum) { this.eingangsdatum = eingangsdatum; } @Nullable public LocalDate getEingangsdatumSTV() { return eingangsdatumSTV; } public void setEingangsdatumSTV(@Nullable LocalDate eingangsdatumSTV) { this.eingangsdatumSTV = eingangsdatumSTV; } @Nullable public LocalDate getFreigabeDatum() { return freigabeDatum; } public void setFreigabeDatum(@Nullable LocalDate freigabeDatum) { this.freigabeDatum = freigabeDatum; } public AntragStatusDTO getStatus() { return status; } public void setStatus(AntragStatusDTO status) { this.status = status; } public AntragTyp getTyp() { return typ; } public void setTyp(AntragTyp typ) { this.typ = typ; } public Eingangsart getEingangsart() { return eingangsart; } public void setEingangsart(Eingangsart eingangsart) { this.eingangsart = eingangsart; } public boolean isDokumenteHochgeladen() { return dokumenteHochgeladen; } public void setDokumenteHochgeladen(boolean dokumenteHochgeladen) { this.dokumenteHochgeladen = dokumenteHochgeladen; } @Nullable public FinSitStatus getFinSitStatus() { return finSitStatus; } public void setFinSitStatus(@Nullable FinSitStatus finSitStatus) { this.finSitStatus = finSitStatus; } }
StadtBern/Ki-Tax
ebegu-rest/src/main/java/ch/dvbern/ebegu/api/dtos/JaxGesuch.java
214,338
/* * 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.graphics.impl; import de._13ducks.cor.game.client.ClientCore; import de._13ducks.cor.game.NetPlayer; import de._13ducks.cor.graphics.input.CoRInputMode; import de._13ducks.cor.graphics.Overlay; import org.newdawn.slick.Color; import org.newdawn.slick.Graphics; import org.newdawn.slick.UnicodeFont; import org.newdawn.slick.geom.Polygon; /** * Der Team-Selektor. * Erscheint/Verschwindet auf T * Ermöglicht das Wählen/Verändern von Teams im laufenden Spiel (sofern diese nicht gesperrt wurden!) * * @author tfg */ public class TeamSelector implements Overlay { /** * Konfig-Parameter. * Hintergrundfarbe des Chatfensters. */ private final Color COL_BACKGROUND = new org.newdawn.slick.Color(65, 65, 65, 160); /** * Konfig-Parameter. * Farbe der Grenzlinie des Chatfensters. */ private final Color COL_BACKGROUND2 = Color.black; /** * Konfig-Parameter. * Farbe des Hintergrunds des Content- und Eingabebereichs */ private final Color COL_CONTENT_AREA = new org.newdawn.slick.Color(50, 50, 50, 160); /** * Wie vieldes Fensters sind NICHT echter Inhalt. * Bedingt unter anderem die Rundung des Chatfensters, da diese den freien Bereich bedingt * Bezieht sich auf die Y-GesamtGröße */ private final float WINDOW_OVER_CONTENT = 0.015f; /** * Konfig-Parameter. * */ private final Color COL_TEXT = new org.newdawn.slick.Color(255, 255, 200); /** * Die verwendete Schriftgröße. Die Größe wird selbstständig angepasst (beim init) */ private UnicodeFont font; private int oriX; private int oriY; private int contentSizeX; private int contentSizeY; private int seqY; private int gap; public boolean active = false; private ClientCore.InnerClient rgi; // Muss am Anfang einmalig berechnet werden. int players = 0; @Override public void renderOverlay(Graphics g, int fullResX, int fullResY) { if (active) { // Einmalig die Spielerzahl berechnen if (players == 0) { for (int i = 1; i < rgi.game.playerList.size(); i++) { if (rgi.game.playerList.get(i).nickName.equals("")) { break; } else { players++; } } // Dein eigenen nicht contentSizeX = (int) (0.90 * fullResX); gap = (int) (WINDOW_OVER_CONTENT * fullResY); seqY = font.getLineHeight(); contentSizeY = (players - 1) * seqY; oriX = (fullResX / 2) - ((contentSizeX + 2 * gap) / 2); oriY = (fullResY / 2) - ((contentSizeY + 3 * gap + seqY) / 2); } // Großer Kasten mit Rahmen g.setColor(COL_BACKGROUND); g.fillRoundRect(oriX, oriY, contentSizeX + 2 * gap, contentSizeY + 3 * gap + seqY, gap); g.setColor(COL_BACKGROUND2); g.drawRoundRect(oriX, oriY, contentSizeX + 2 * gap, contentSizeY + 3 * gap + seqY, gap); // Obere Box g.setColor(COL_CONTENT_AREA); g.fillRect(oriX + gap, oriY + gap, contentSizeX, seqY); g.setColor(COL_BACKGROUND2); g.drawRect(oriX + gap, oriY + gap, contentSizeX, seqY); // Untere Box g.setColor(COL_CONTENT_AREA); g.fillRect(oriX + gap, oriY + seqY + 2 * gap, contentSizeX, contentSizeY); g.setColor(COL_BACKGROUND2); g.drawRect(oriX + gap, oriY + seqY + 2 * gap, contentSizeX, contentSizeY); // Inhalt des Titels g.setColor(COL_TEXT); g.setFont(font); g.drawString("ALLIES", oriX + gap + ((contentSizeX / 2) - (font.getWidth("ALLIES")) / 2), oriY + gap); // Spieler int index = 0; for (int i = 1; i <= players; i++) { if (i == rgi.game.getOwnPlayer().playerId) { continue; } else { index++; } NetPlayer player = rgi.game.playerList.get(i); // Farb-Kasten g.setColor(player.color); g.fillRect(oriX + gap + (0.1f * seqY), ((index - 1) * seqY) + oriY + seqY + 2 * gap + (0.1f * seqY), (0.8f * seqY), (0.8f * seqY)); // Name, ungekürzt (erstmal) g.setColor(COL_TEXT); g.drawString(player.nickName, oriX + gap + 15 + (0.8f * seqY), ((index - 1) * seqY) + oriY + seqY + 2 * gap); // Ally-Kasten g.drawRect((float) (oriX + gap + contentSizeX - (0.4f * seqY) - (1.6 * seqY)), ((index - 1) * seqY) + oriY + seqY + 2 * gap + (0.1f * seqY), (0.8f * seqY), (0.8f * seqY)); // Vis-Kasten g.drawRect((float) (oriX + gap + contentSizeX - (0.1f * seqY) - (0.8 * seqY)), ((index - 1) * seqY) + oriY + seqY + 2 * gap + (0.1f * seqY), (0.8f * seqY), (0.8f * seqY)); // Status eintragen: if (rgi.game.areAllies(rgi.game.getOwnPlayer(), player)) { g.fillRect((float) (oriX + gap + contentSizeX - (0.4f * seqY) - (1.6 * seqY)) + 2, ((index - 1) * seqY) + oriY + seqY + 2 * gap + (0.1f * seqY) + 2, (0.8f * seqY) - 3, (0.8f * seqY) - 3); } else if (rgi.game.wasInvited(player)) { // Halb Polygon poly = new Polygon(); poly.addPoint((float) (oriX + gap + contentSizeX - (0.4f * seqY) - (1.6 * seqY)) + 2 + ((0.8f * seqY) - 3), ((index - 1) * seqY) + oriY + seqY + 2 * gap + (0.1f * seqY) + 2 + ((0.8f * seqY) - 3)); poly.addPoint((float) (oriX + gap + contentSizeX - (0.4f * seqY) - (1.6 * seqY)) + 2, ((index - 1) * seqY) + oriY + seqY + 2 * gap + (0.1f * seqY) + 2); poly.addPoint((float) (oriX + gap + contentSizeX - (0.4f * seqY) - (1.6 * seqY)) + 2, ((index - 1) * seqY) + oriY + seqY + 2 * gap + (0.1f * seqY) + 2 + ((0.8f * seqY) - 3)); poly.addPoint((float) (oriX + gap + contentSizeX - (0.4f * seqY) - (1.6 * seqY)) + 2 + ((0.8f * seqY) - 3), ((index - 1) * seqY) + oriY + seqY + 2 * gap + (0.1f * seqY) + 2 + ((0.8f * seqY) - 3)); g.fill(poly); } if (rgi.game.shareSight(rgi.game.getOwnPlayer(), player)) { g.fillRect((float) (oriX + gap + contentSizeX - (0.1f * seqY) - (0.8 * seqY)) + 2, ((index - 1) * seqY) + oriY + seqY + 2 * gap + (0.1f * seqY) + 2, (0.8f * seqY) - 3, (0.8f * seqY) - 3); } } } } public void setFont(UnicodeFont f) { font = f; } public void toggle() { active = !active; if (active) { // AN? rgi.rogGraphics.inputM.addAndReplaceSpecialMode(new CoRInputMode(false) { @Override public void mouseMoved(int oldx, int oldy, int newx, int newy) { } @Override public void mouseKlicked(int button, int x, int y, int clickCount) { if (button == 0) { // Herausfinden, ob was von Bedeutung angeklickt wurde (ein Kasten im Team-Fenster) checkKlick(x, y); } else { // Abbrechen toggle(); } } @Override public void startMode() { } @Override public void endMode() { if (active) { //active = false; } } }); } else { // AUS: rgi.rogGraphics.inputM.removeSpecialMode(); } } /** * Wertet klicks ins Fenster aus * @param x * @param y */ private void checkKlick(int x, int y) { if (active) { int index = 0; for (int i = 1; i <= players; i++) { if (i == rgi.game.getOwnPlayer().playerId) { continue; } else { index++; } NetPlayer player = rgi.game.getPlayer(i); // Ally? int x1ally = (int) (oriX + gap + contentSizeX - (0.4f * seqY) - (1.6 * seqY)); int y1ally = (int) (((index - 1) * seqY) + oriY + seqY + 2 * gap + (0.1f * seqY)); int x2ally = (int) (x1ally + (0.8f * seqY)); int y2ally = (int) (y1ally + (0.8f * seqY)); // Vis-Kasten? int x1vis = (int) (oriX + gap + contentSizeX - (0.1f * seqY) - (0.8 * seqY)); int y1vis = (int) ((index - 1) * seqY + oriY + seqY + 2 * gap + (0.1f * seqY)); int x2vis = (int) (x1vis + (0.8f * seqY)); int y2vis = (int) (y1vis + (0.8f * seqY)); if (x > x1ally && x < x2ally && y > y1ally && y < y2ally) { // Ally setzen // Es geht nur, wenn wirs nicht selber sind if (!player.equals(rgi.game.getOwnPlayer())) { // Will man setzen oder un-setzen? boolean activAlly = !rgi.game.areAllies(player, rgi.game.getOwnPlayer()); if (activAlly) { // Team-Setzen muss erst bestätigt werden. Ist dies bereits die Antwort auf die Bestätigung? if (rgi.game.wasInvited(player)) { // Ja, jetzt setzen rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 51, rgi.game.getOwnPlayer().playerId, player.playerId, 2, 0)); } else { // Anfragen rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 51, rgi.game.getOwnPlayer().playerId, player.playerId, 1, 0)); rgi.chat.addMessage("You invited " + player.nickName, -2); } } else { // Ally/Anfrage löschen rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 51, rgi.game.getOwnPlayer().playerId, player.playerId, 4, 0)); } } } else if (x > x1vis && x < x2vis && y > y1vis && y < y2vis) { // Vis setzen if (!player.equals(rgi.game.getOwnPlayer())) { // Setzen oder löschen? if (rgi.game.shareSight(player, rgi.game.getOwnPlayer())) { // Löschen rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 51, rgi.game.getOwnPlayer().playerId, player.playerId, 5, 0)); } else { // Vis lässt sich nur setzen, wenn wir verbündet sind. if (rgi.game.areAllies(player, rgi.game.getOwnPlayer())) { // Sicht setzen rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 51, rgi.game.getOwnPlayer().playerId, player.playerId, 3, 0)); } } } } } } } public TeamSelector(ClientCore.InnerClient inner) { rgi = inner; } }
tfg13/Centuries-of-Rage
src/de/_13ducks/cor/graphics/impl/TeamSelector.java
214,340
/** * Copyright 2002 DFKI GmbH. * All Rights Reserved. Use is subject to license terms. * * This file is part of MARY TTS. * * MARY TTS is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package marytts.language.de.preprocess; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * An expansion pattern implementation for specialChar patterns. * * @author Marc Schr&ouml;der */ public class SpecialCharEP extends ExpansionPattern { private final String[] _knownTypes = { "specialChar" }; /** * Every subclass has its own list knownTypes, an internal string representation of known types. These are possible values of * the <code>type</code> attribute to the <code>say-as</code> element, as defined in MaryXML.dtd. If there is more than one * known type, the first type (<code>knownTypes[0]</code>) is expected to be the most general one, of which the others are * specializations. */ private final List<String> knownTypes = Arrays.asList(_knownTypes); public List<String> knownTypes() { return knownTypes; } /** Helper class for the specialCharNames map */ class SCEntry { /** The expanded form of this special character. */ protected String expand; /** * Determines whether a symbol, when found in a token, will cause the token to be split into its parts. */ protected boolean splitAt; /** * Determines whether it will be pronounced when found as a single token after all other expansion patterns have been * applied. */ protected boolean pronounce; protected SCEntry(String expand, boolean splitAt, boolean pronounce) { this.expand = expand; this.splitAt = splitAt; this.pronounce = pronounce; } } /** Only needed to fill specialCharNames */ private Map<String, SCEntry> createSpecialCharNames() { HashMap<String, SCEntry> m = new HashMap<String, SCEntry>(); m.put(",", new SCEntry("Komma", false, false)); m.put("\\", new SCEntry("Backslash['bEk-slES]", true, true)); m.put("!", new SCEntry("Ausrufezeichen", false, false)); m.put("#", new SCEntry("Numerical[nu:-'mE-rI_k@l]", true, true)); m.put("$", new SCEntry("Dollar", false, true)); m.put(Character.valueOf((char) 167).toString(), new SCEntry("Paragraph", true, true)); m.put("%", new SCEntry("Prozent", false, true)); m.put(Character.valueOf((char) 8364).toString(), new SCEntry("Euro", false, true)); m.put("&", new SCEntry("und", true, true)); m.put("'", new SCEntry("Hochkomma", true, false)); m.put("*", new SCEntry("Stern", true, true)); m.put("+", new SCEntry("plus", true, true)); m.put("-", new SCEntry("Bindestrich", false, false)); m.put("/", new SCEntry("Slash['slES]", true, false)); m.put("=", new SCEntry("gleich", true, true)); m.put("?", new SCEntry("Fragezeichen", true, false)); m.put("^", new SCEntry("Dach", true, false)); m.put("_", new SCEntry("Unterstrich", true, false)); m.put("`", new SCEntry("Hochkomma", true, false)); m.put("{", new SCEntry("geschweifte Klammer auf", true, false)); m.put("|", new SCEntry("senkrechter Strich", true, false)); m.put("}", new SCEntry("geschweifte Klammer zu", true, false)); m.put("~", new SCEntry("Tilde", true, true)); m.put("(", new SCEntry("Klammer auf", true, false)); m.put(")", new SCEntry("Klammer zu", true, false)); m.put("[", new SCEntry("eckige Klammer auf", true, false)); m.put("]", new SCEntry("eckige Klammer zu", true, false)); m.put("@", new SCEntry("at['Et]", false, true)); m.put(":", new SCEntry("Doppelpunkt", false, false)); m.put(";", new SCEntry("Semikolon", true, false)); m.put("\"", new SCEntry("Anführungszeichen", true, false)); m.put("<", new SCEntry("kleiner als", true, true)); m.put(">", new SCEntry("größer als", true, true)); m.put(".", new SCEntry("Punkt", false, false)); return m; }; private final Map<String, SCEntry> specialCharNames = createSpecialCharNames(); protected final String sMatchingChars = createMatchingChars(); // protected final String sMatchingChars = // "[\\,\\\\\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~\\(\\)\\[\\]\\@\\:\\;\\\"\\<\\>\\.]"; protected final String sMatchingCharsSimpleString = createMatchingCharsSimpleString(); // protected final String sMatchingCharsSimpleString = ",\\!#$%&'*+-/=?^_`{|}~()[]@:;\"<>."; private final String sSplitAtChars = createSplitAtChars(); private final String sSplitAtCharsSimpleString = createSplitAtCharsSimpleString(); /** * Only needed to fill sMatchingChars from specialCharNames * * @return sb.toString */ private String createMatchingChars() { StringBuilder sb = new StringBuilder("["); for (Iterator<String> it = specialCharNames.keySet().iterator(); it.hasNext();) { sb.append("\\" + (String) it.next()); } sb.append("]"); return sb.toString(); } /** * Only needed to fill sMatchingCharsSimpleString from _specialCharNames[] * * @return sb.toString */ private String createMatchingCharsSimpleString() { StringBuilder sb = new StringBuilder(); for (Iterator<String> it = specialCharNames.keySet().iterator(); it.hasNext();) { sb.append((String) it.next()); } return sb.toString(); } /** * Only needed to fill sSplitAtChars from _specialCharNames[] * * @return sb.toString */ private String createSplitAtChars() { StringBuilder sb = new StringBuilder("["); for (Iterator<String> it = specialCharNames.keySet().iterator(); it.hasNext();) { String sc = (String) it.next(); if (((SCEntry) specialCharNames.get(sc)).splitAt) { sb.append("\\" + sc); } } sb.append("]"); return sb.toString(); } /** * Only needed to fill sSplitAtCharsSimpleString from _specialCharNames[] * * @return sb.toString */ private String createSplitAtCharsSimpleString() { StringBuilder sb = new StringBuilder(); for (Iterator<String> it = specialCharNames.keySet().iterator(); it.hasNext();) { String sc = (String) it.next(); if (((SCEntry) specialCharNames.get(sc)).splitAt) { sb.append(sc); } } return sb.toString(); } private final Pattern reMatchingChars = Pattern.compile(sMatchingChars); public Pattern reMatchingChars() { return reMatchingChars; } private final Pattern reSplitAtChars = Pattern.compile(sSplitAtChars); /** * A regular expression matching the characters at which a token should be split into parts before any preprocessing patterns * are applied. * * @return reSplitAtChars */ protected Pattern getRESplitAtChars() { return reSplitAtChars; } /** * A string containing the characters at which a token should be split into parts before any preprocessing patterns are * applied. * * @return sSplitAtCharsSimpleString */ protected String splitAtChars() { return sSplitAtCharsSimpleString; } /** * Every subclass has its own logger. The important point is that if several threads are accessing the variable at the same * time, the logger needs to be thread-safe or it will produce rubbish. */ // private Logger logger = MaryUtils.getLogger("SpecialCharEP"); public SpecialCharEP() { super(); } protected int canDealWith(String s, int type) { return match(s, type); } protected int match(String s, int type) { switch (type) { case 0: if (matchSpecialChar(s)) return 0; break; } return -1; } protected List<Element> expand(List<Element> tokens, String s, int type) { if (tokens == null) throw new NullPointerException("Received null argument"); if (tokens.isEmpty()) throw new IllegalArgumentException("Received empty list"); Document doc = ((Element) tokens.get(0)).getOwnerDocument(); // we expect type to be one of the return values of match(): List<Element> expanded = null; switch (type) { case 0: expanded = expandSpecialChar(doc, s); break; } if (expanded != null && !expanded.isEmpty()) replaceTokens(tokens, expanded); return expanded; } /** * Tell whether String <code>s</code> is a specialChar. * * @param s * s * @return reMatchingChars.matcher(s).matches */ public boolean matchSpecialChar(String s) { return reMatchingChars.matcher(s).matches(); } protected boolean doPronounce(String specialChar) { SCEntry entry = (SCEntry) specialCharNames.get(specialChar); if (entry == null) return false; return entry.pronounce; } protected List<Element> expandSpecialChar(Document doc, String s) { ArrayList<Element> exp = new ArrayList<Element>(); if (doPronounce(s)) { String specialCharName = expandSpecialChar(s); exp.addAll(makeNewTokens(doc, specialCharName, true, s)); } // if not to be pronounced, return an empty list return exp; } protected String expandSpecialChar(String s) { SCEntry entry = (SCEntry) specialCharNames.get(s); if (entry == null) return null; return entry.expand; } }
marytts/marytts
marytts-languages/marytts-lang-de/src/main/java/marytts/language/de/preprocess/SpecialCharEP.java
214,341
/** * Copyright 2002 DFKI GmbH. * All Rights Reserved. Use is subject to license terms. * * This file is part of MARY TTS. * * MARY TTS is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, version 3 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package marytts.language.it.preprocess; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import marytts.util.MaryUtils; import org.apache.logging.log4j.Logger; import org.w3c.dom.Document; import org.w3c.dom.Element; /** * An expansion pattern implementation for specialChar patterns. * * @author Marc Schr&ouml;der */ public class SpecialCharEP extends ExpansionPattern { private final String[] _knownTypes = { "specialChar" }; /** * Every subclass has its own list knownTypes, an internal string representation of known types. These are possible values of * the <code>type</code> attribute to the <code>say-as</code> element, as defined in MaryXML.dtd. If there is more than one * known type, the first type (<code>knownTypes[0]</code>) is expected to be the most general one, of which the others are * specialisations. */ private final List<String> knownTypes = Arrays.asList(_knownTypes); public List<String> knownTypes() { return knownTypes; } /** Helper class for the specialCharNames map */ class SCEntry { /** The expanded form of this special character. */ protected String expand; /** * Determines whether a symbol, when found in a token, will cause the token to be split into its parts. */ protected boolean splitAt; /** * Determines whether it will be pronounced when found as a single token after all other expansion patterns have been * applied. */ protected boolean pronounce; protected SCEntry(String expand, boolean splitAt, boolean pronounce) { this.expand = expand; this.splitAt = splitAt; this.pronounce = pronounce; } } /** * Only needed to fill specialCharNames * * @return m */ private Map<String, SCEntry> createSpecialCharNames() { HashMap<String, SCEntry> m = new HashMap<String, SCEntry>(); m.put("$", new SCEntry("dollaro", false, true)); m.put("@", new SCEntry("chiocciola", true, true)); /* * m.put("'", new SCEntry("apostrofoXXX", false, true)); m.put(":", new SCEntry("duepuntiXXX", true, true)); */ /* * m.put(",", new SCEntry("Komma", false, false)); m.put("\\", new SCEntry("Backslash['bEk-slES]", true, true)); * m.put("!", new SCEntry("Ausrufezeichen", false, false)); m.put("#", new SCEntry("Numerical[nu:-'mE-rI_k@l]", true, * true)); m.put("$", new SCEntry("Dollar", false, true)); m.put(Character.valueOf((char)167).toString(), new * SCEntry("Paragraph", true, true)); m.put("%", new SCEntry("Prozent", false, true)); m.put(new * Character((char)8364).toString(), new SCEntry("Euro", false, true)); m.put("&", new SCEntry("und", true, true)); * m.put("'", new SCEntry("Hochkomma", true, false)); m.put("*", new SCEntry("Stern", true, true)); m.put("+", new * SCEntry("plus", true, true)); m.put("-", new SCEntry("Bindestrich", false, false)); m.put("/", new * SCEntry("Slash['slES]", true, false)); m.put("=", new SCEntry("gleich", true, true)); m.put("?", new * SCEntry("Fragezeichen", true, false)); m.put("^", new SCEntry("Dach", true, false)); m.put("_", new * SCEntry("Unterstrich", true, false)); m.put("`", new SCEntry("Hochkomma", true, false)); m.put("{", new * SCEntry("geschweifte Klammer auf", true, false)); m.put("|", new SCEntry("senkrechter Strich", true, false)); * m.put("}", new SCEntry("geschweifte Klammer zu", true, false)); m.put("~", new SCEntry("Tilde", true, true)); * m.put("(", new SCEntry("Klammer auf", true, false)); m.put(")", new SCEntry("Klammer zu", true, false)); m.put("[", new * SCEntry("eckige Klammer auf", true, false)); m.put("]", new SCEntry("eckige Klammer zu", true, false)); m.put("@", new * SCEntry("at['Et]", false, true)); m.put(":", new SCEntry("Doppelpunkt", false, false)); m.put(";", new * SCEntry("Semikolon", true, false)); m.put("\"", new SCEntry("Anführungszeichen", true, false)); m.put("<", new * SCEntry("kleiner als", true, true)); m.put(">", new SCEntry("größer als", true, true)); m.put(".", new SCEntry("Punkt", * false, false)); */ return m; }; private final Map<String, SCEntry> specialCharNames = createSpecialCharNames(); protected final String sMatchingChars = createMatchingChars(); // protected final String sMatchingChars = // "[\\,\\\\\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~\\(\\)\\[\\]\\@\\:\\;\\\"\\<\\>\\.]"; protected final String sMatchingCharsSimpleString = createMatchingCharsSimpleString(); // protected final String sMatchingCharsSimpleString = ",\\!#$%&'*+-/=?^_`{|}~()[]@:;\"<>."; private final String sSplitAtChars = createSplitAtChars(); private final String sSplitAtCharsSimpleString = createSplitAtCharsSimpleString(); /** * Only needed to fill sMatchingChars from specialCharNames * * @return sb.toString */ private String createMatchingChars() { StringBuilder sb = new StringBuilder("["); for (Iterator<String> it = specialCharNames.keySet().iterator(); it.hasNext();) { sb.append("\\" + it.next()); } sb.append("]"); return sb.toString(); } /** Only needed to fill sMatchingCharsSimpleString from _specialCharNames[] */ private String createMatchingCharsSimpleString() { StringBuilder sb = new StringBuilder(); for (Iterator<String> it = specialCharNames.keySet().iterator(); it.hasNext();) { Iterator<String> it2 = it; sb.append(it2.next()); } return sb.toString(); } /** * Only needed to fill sSplitAtChars from _specialCharNames[] * * @return sb.toString */ private String createSplitAtChars() { StringBuilder sb = new StringBuilder("["); for (Iterator<String> it = specialCharNames.keySet().iterator(); it.hasNext();) { String sc = it.next(); if (((SCEntry) specialCharNames.get(sc)).splitAt) { sb.append("\\" + sc); } } sb.append("]"); return sb.toString(); } /** * Only needed to fill sSplitAtCharsSimpleString from _specialCharNames[] * * @return sb.toString */ private String createSplitAtCharsSimpleString() { StringBuilder sb = new StringBuilder(); for (Iterator<String> it = specialCharNames.keySet().iterator(); it.hasNext();) { String sc = it.next(); if (((SCEntry) specialCharNames.get(sc)).splitAt) { sb.append(sc); } } return sb.toString(); } private final Pattern reMatchingChars = Pattern.compile(sMatchingChars); public Pattern reMatchingChars() { return reMatchingChars; } private final Pattern reSplitAtChars = Pattern.compile(sSplitAtChars); /** * A regular expression matching the characters at which a token should be split into parts before any preprocessing patterns * are applied. * * @return reSplitAtChars */ protected Pattern getRESplitAtChars() { return reSplitAtChars; } /** * A string containing the characters at which a token should be split into parts before any preprocessing patterns are * applied. * * @return sSplitAtCharsSimpleString */ protected String splitAtChars() { return sSplitAtCharsSimpleString; } /** * Every subclass has its own logger. The important point is that if several threads are accessing the variable at the same * time, the logger needs to be thread-safe or it will produce rubbish. */ private Logger logger = MaryUtils.getLogger("SpecialCharEP"); public SpecialCharEP() { super(); } protected int canDealWith(String s, int type) { return match(s, type); } protected int match(String s, int type) { switch (type) { case 0: if (matchSpecialChar(s)) return 0; break; } return -1; } protected List<Element> expand(List<Element> tokens, String s, int type) { if (tokens == null) throw new NullPointerException("Received null argument"); if (tokens.isEmpty()) throw new IllegalArgumentException("Received empty list"); Document doc = ((Element) tokens.get(0)).getOwnerDocument(); // we expect type to be one of the return values of match(): List<Element> expanded = null; switch (type) { case 0: expanded = expandSpecialChar(doc, s); break; } if (expanded != null && !expanded.isEmpty()) replaceTokens(tokens, expanded); return expanded; } /** * Tell whether String <code>s</code> is a specialChar. * * @param s * the string * @return reMatchingChars.matcher(s).matches() */ public boolean matchSpecialChar(String s) { return reMatchingChars.matcher(s).matches(); } protected boolean doPronounce(String specialChar) { SCEntry entry = (SCEntry) specialCharNames.get(specialChar); if (entry == null) return false; return entry.pronounce; } protected List<Element> expandSpecialChar(Document doc, String s) { ArrayList<Element> exp = new ArrayList<Element>(); if (doPronounce(s)) { String specialCharName = expandSpecialChar(s); exp.addAll(makeNewTokens(doc, specialCharName, true, s)); } // if not to be pronounced, return an empty list return exp; } protected String expandSpecialChar(String s) { SCEntry entry = (SCEntry) specialCharNames.get(s); if (entry == null) return null; return entry.expand; } }
marytts/marytts
marytts-languages/marytts-lang-it/src/main/java/marytts/language/it/preprocess/SpecialCharEP.java
214,342
/* * This file is part of JPARSEC library. * * (C) Copyright 2006-2009 by T. Alonso Albi - OAN (Spain). * * Project Info: http://conga.oan.es/~alonso/jparsec/jparsec.html * * JPARSEC library is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * JPARSEC library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.asterope.ephem; /** * Class that performs some simple calculations about star properties. * * @author T. Alonso Albi - OAN (Spain) * @version 1.0 */ public class Star { /** * Calculate luminosity ratio L1/L2. * * @param m1 Absolute magnitude of body 1. * @param m2 Absolute magnitude of body 2. * @return Luminosity ratio. */ public static double luminosityRatio(double m1, double m2) { double lum = Math.pow(10.0, (m2 - m1) / 2.5); return lum; } /** * Computes the combined apparent magnitude of two objects. * @param m1 Magnitude of body 1. * @param m2 Magnitude of body 2. * @return The combined magnitude. */ public static double combinedMagnitude(double m1, double m2) { if (m1 > m2) { double t = m1; m1 = m2; m2 = t; } double lum = Star.luminosityRatio(m1, m2); double m = m2 - 2.5 * Math.log10(1.0 + lum); return m; } /** * Obtain absolute magnitude. * * @param ap_mag Apparent magnitude. * @param dist Distance in parsec. * @return Absolute magnitude. */ public static double absoluteMagnitude(double ap_mag, double dist) { double abs_mag = ap_mag + 5 - 5 * Math.log(dist) / Math.log(10.0); return abs_mag; } /** * Gets the distance of a star. * * @param ap_mag Apparent magnitude. * @param abs_mag Absolute magnitude. * @return The distance in parsec. */ public static double distance(double ap_mag, double abs_mag) { double dist = Math.pow(10.0, (ap_mag + 5 - abs_mag) / 5.0); return dist; } /** * Obtains the dynamical parallax using Kepler's third law. * * @param a Distance in arcseconds. * @param P Period in years. * @param M Mass of the system in solar masses. * @return Parallax in arcseconds. */ public static double dynamicalParallax(double a, double P, double M) { double par = a / (Math.pow(P * P * M, 1.0 / 3.0)); return par; } /** * Obtains gravitational energy of a body in J. * * @param M Mass in solar masses. * @param r Radius in sola radii * @return Energy in J. */ public static double gravitationalEnergy(double M, double r) { double Eg = 3.0 * EphemConstant.GRAVITATIONAL_CONSTANT * M * M * EphemConstant.SUN_MASS * EphemConstant.SUN_MASS / (5.0 * r * EphemConstant.SUN_RADIUS * 1000.0); return Eg; } /** * Obtains gravitational time scale, or the maximum time a given body could * radiate energy during a contraction phase. * * @param M Mass in solar masses. * @param r Radius in solar radii. * @param L Luminosity in J/s. * @return Time in seconds. */ public static double gravitationalTimeScale(double M, double r, double L) { double t = gravitationalEnergy(M, r) / L; return t; } /** * Obtains Schwartzchild radius for an object of certain mass. If the radius * is lower than this value, then the object is a black hole. * * @param M Mass in solar masses. * @return Radius in solar radii. */ public static double schwartzchildRadius(double M) { double r = 2.0 * EphemConstant.GRAVITATIONAL_CONSTANT * M * EphemConstant.SUN_MASS / (EphemConstant.SPEED_OF_LIGHT * EphemConstant.SPEED_OF_LIGHT); return r / (1000.0 * EphemConstant.SUN_RADIUS); } /** * Obtain wind mass lost ratio in solar masses by year. The effect in * stellar evolution is neglective in most of the cases. * * @param n Proton density in cm^-3 at certain distance from the star. * Typical value of 7 for the sun. * @param v Proton velocity in km/s at the same distance. Typical value of * 500 for the sun. * @param r The distance where n and v and measured in AU. Typical value of * 1 for the sun. * @return Mass lose ratio in solar masses by year. Typical value of 5E-14 * Msol/year for the sun. */ public static double stellarWindMass(double n, double v, double r) { double dm_dt = 4.0 * Math.PI * r * r * EphemConstant.AU * EphemConstant.AU * n * 1.0E15 * EphemConstant.H2_MASS * v / EphemConstant.SUN_MASS; return dm_dt * EphemConstant.SECONDS_PER_DAY * EphemConstant.TROPICAL_YEAR; } /** * Returns the mass of an object using Kepler's third law. * * @param a Distance of a measure in AU. * @param P Oribtal period at that position in years. * @return Mass in solar masses. */ public static double kepler3rdLawOfMasses(double a, double P) { double M = P * P / (a * a * a); return M; } /** * Obtain total flux of a black body at certain temperature. * * @param T Effective temperature. * @return Flux in W/m^2. */ public static double blackBodyFlux(double T) { return EphemConstant.STEFAN_BOLTZMANN_CONSTANT * Math.pow(T, 4.0); } /** * Applies Tully-Fisher relation for obtaining the luminosity of a spiral * galaxy. * * @param v Rotation velocity in km/s in the outer galaxy. * @return Luminosity in solar units. */ public static double tullyFisherRelation(double v) { double beta = 4.55; double L0 = 1.0E10; double k = L0 / Math.pow(220.0, beta); double L = k * Math.pow(v, beta); return L; } /** * Applies Fabber-Jackson relation for obtaining the luminosity of an * elliptical galaxy. * * @param sigma Velocity dispersion in km/s in the inner region. * @return Luminosity in solar units. */ public static double fabberJacksonRelation(double sigma) { double beta = 4.55; double L0 = 1.0E10; double k = L0 / Math.pow(220.0, beta); double L = k * Math.pow(sigma, beta); return L; } /** * Calculates Sechter luminosity function. * * @param L Luminosity in solar units. * @param alfa Slope parameter. * @return Number of objects per rade2Vector of luminosity, dN/dL. */ public static double sechterRelation(double L, double alfa) { double L0 = 1.0E10; double phi0 = 1.0 / gammaFunction(1.0 + alfa); double phi = Math.pow(L / L0, alfa) * Math.exp(-L / L0) * phi0 / L0; return phi; } /** * Obtains gamma function for evaluating Sechter luminosity function. * * @param alfa Slope parameter. Must be integer or half-integer. * @return Value of the function. */ public static double gammaFunction(double alfa) { if (alfa <= 1) return 0.0; double g = 1.0; do { g = g * (alfa - 1.0); alfa = alfa - 1.0; } while (alfa > 1.0); if (alfa == 0.5) g = g * Math.sqrt(Math.PI); return g; } /** * Obtains gravitational redshift. * * @param M Mass in solar masses. * @param R Radio in solar radii. * @return Redshift. */ public static double gravitationalRedshift(double M, double R) { double z = -1.0 + Math .sqrt(1.0 / (1.0 - 2.0 * M * EphemConstant.SUN_MASS * EphemConstant.GRAVITATIONAL_CONSTANT / (R * EphemConstant.SUN_RADIUS * 1000.0 * EphemConstant.SPEED_OF_LIGHT * EphemConstant.SPEED_OF_LIGHT))); return z; } /** * Obtains cosmological redshift. * * @param v Velocity of the source in m/s. * @return Redshift. */ public static double cosmologicalRedshift(double v) { double z = -1.0 + Math.sqrt((EphemConstant.SPEED_OF_LIGHT + v) / (EphemConstant.SPEED_OF_LIGHT - v)); return z; } /** * Obtain wavelength of the peak emission of a black body applying Wien's * approximation. * * @param T Temperature in K. * @return Wavelength in m. */ public static double wienApproximation(double T) { return EphemConstant.WIEN_CONSTANT / T; } /** * Evaluates Planck's function. * * @param T Temperature in K. * @param lambda Wavelength in m. * @return B in Jy/sr. */ public static double blackBody(double T, double lambda) { double nu = EphemConstant.SPEED_OF_LIGHT / lambda; double B = 2.0 * EphemConstant.PLANCK_CONSTANT * Math.pow(nu, 3.0) / (EphemConstant.SPEED_OF_LIGHT * EphemConstant.SPEED_OF_LIGHT); B = B / (Math.exp(EphemConstant.PLANCK_CONSTANT * nu / (EphemConstant.BOLTZMANN_CONSTANT * T)) - 1.0); B = B * EphemConstant.ERG_S_CM2_HZ_TO_JY; return B; } /** * Evaluates Planck's function. * * @param T Temperature in K. * @param nu Frequency in Hz. * @return B in Jy/sr. */ public static double blackBodyNu(double T, double nu) { double B = 2.0 * EphemConstant.PLANCK_CONSTANT * Math.pow(nu, 3.0) / (EphemConstant.SPEED_OF_LIGHT * EphemConstant.SPEED_OF_LIGHT); B = B / (Math.exp(EphemConstant.PLANCK_CONSTANT * nu / (EphemConstant.BOLTZMANN_CONSTANT * T)) - 1.0); B = B * EphemConstant.ERG_S_CM2_HZ_TO_JY; return B; } /** * Evaluates error of Planck's function, taking into account certain error * in the temperature. * * @param T Temperature in K. * @param dT Temperature error in K. * @param lambda Wavelength in m. * @return B error in Jy/sr. */ public static double blackBodyFluxError(double T, double dT, double lambda) { double nu = EphemConstant.SPEED_OF_LIGHT / lambda; double B = 2.0 * EphemConstant.PLANCK_CONSTANT * Math.pow(nu, 3.0) / (EphemConstant.SPEED_OF_LIGHT * EphemConstant.SPEED_OF_LIGHT); B = B / Math.pow(Math.exp(EphemConstant.PLANCK_CONSTANT * nu / (EphemConstant.BOLTZMANN_CONSTANT * T)) - 1.0, 2.0); B = B * Math.exp(EphemConstant.PLANCK_CONSTANT * nu / (EphemConstant.BOLTZMANN_CONSTANT * T)); B *= -dT * EphemConstant.PLANCK_CONSTANT * nu / (EphemConstant.BOLTZMANN_CONSTANT * T * T); B = B * EphemConstant.ERG_S_CM2_HZ_TO_JY; return B; } /** * Obtains surface brightness of an object. * * @param m Magnitude. * @param r Radius in arcseconds. If the object is not circular, an * equivalent value can be given so that the area (PI * r^2) in equal * to the area of the object in the sky. * @return Brightness in mag/arcsecond^2, or 0 if radius is 0. */ public static double getSurfaceBrightness(double m, double r) { double bright = 0.0; if (r <= 0.0) return bright; double area = Math.PI * (r / 60.0) * (r / 60.0); double s1 = m + Math.log(area) / Math.log(Math.pow(100.0, 0.2)); bright = s1 + 8.890756; return bright; } /** * Obtain the luminosity using the mass-luminosity relation for main sequence * stars. * @param mass Mass in solar units. * @return Luminosity in solar units. */ public static double getLuminosityFromMassLuminosityRelation(double mass) { double l = Math.pow(mass, 3.5); return l; } /** * Obtain the luminosity using the mass-luminosity relation for main sequence * stars. * @param luminosity Luminosity in solar units. * @return Mass in solar units. */ public static double getMassFromMassLuminosityRelation(double luminosity) { double m = Math.log(luminosity) / Math.log(3.5); return m; } /** * Obtains approximate star life time for a given mass. * @param mass Star mass in solar units. * @return Lifetime in years. */ public static double getStarLifeTime(double mass) { double lum = getLuminosityFromMassLuminosityRelation(mass); double time = 1.0E10 * mass / lum; return time; } /** * Obtains star radius. * * @param luminosity Luminosity in solar units. * @param temperature Temperature in K. * @return Radius in solar radii. */ public static double getStarRadius(double luminosity, double temperature) { double rs = Math .sqrt(luminosity * EphemConstant.SUN_LUMINOSITY / (4.0 * Math.PI * EphemConstant.STEFAN_BOLTZMANN_CONSTANT * Math .pow(temperature, 4.0))) / (EphemConstant.SUN_RADIUS * 1000.0); return rs; } /** * Obtains star luminosity. * * @param radius Radius in solar untis. * @param temperature Temperature in K. * @return Luminosity in solar units. */ public static double getStarLuminosity(double radius, double temperature) { double luminosity = Math.pow(radius * EphemConstant.SUN_RADIUS * 1000.0, 2.0) * (4.0 * Math.PI * EphemConstant.STEFAN_BOLTZMANN_CONSTANT * Math.pow(temperature, 4.0)); return luminosity / EphemConstant.SUN_LUMINOSITY; } /** * Obtain distance modulus * @param distance Distance in pc. * @return Distance modulus. */ public static double getDistanceModulus(double distance) { double module = -5.0 + 5.0 * Math.log10(distance); return module; } /** * Obtains the surface gravity. * @param mass Mass in solar masses. * @param radius Radius in solar radii. * @return Gravity in m/s^2. */ public static double getSurfaceGravity(double mass, double radius) { double g = EphemConstant.GRAVITATIONAL_CONSTANT * mass * EphemConstant.SUN_MASS / (Math.pow(radius * EphemConstant.SUN_RADIUS * 1000.0, 2.0)); return g; } /** * Obtains the magnitude of a star given the flux on it, the background, and the * same properties (including magnitude) of a comparison star close to it. * @param flux Flux of the star. * @param skyBackground Flux of the background. * @param fluxComparison Flux of a comparison star. * @param skyBackgroundComparison Sky background around comparison star. * @param magComparison Magnitude of a comparison star. * @return Magnitude of the star. */ public static double getStarMagnitude(double flux, double skyBackground, double fluxComparison, double skyBackgroundComparison, double magComparison) { flux = flux - skyBackground; fluxComparison = fluxComparison - skyBackgroundComparison; double mag = 2.5 * Math.log(fluxComparison / flux) / Math.log(10.0) + magComparison; return mag; } /** * Calculates the size of an impact crater. * @param impactorDiameter Diameter of the impactor in m. * @param impactorDensity Density of the impactor in kg/m^3. * @param impactorVelocity Velocity of the impactor in km/s. * @param zenithAngle Zenith angle of the impactor trajectory in degrees. * @return Diameter and depth of the impact crater in m. */ public static double[] impactCrater(double impactorDiameter, double impactorDensity, double impactorVelocity, double zenithAngle) { double IV=impactorVelocity * 1000.0; double VI=Math.PI * impactorDiameter * impactorDiameter * impactorDiameter / 6.0; double GF=Math.pow((Math.sin((90.0 - zenithAngle) * EphemConstant.DEG_TO_RAD)), .33); double MI=impactorDensity * VI; double KE=.5 * MI * IV * IV; double KT=KE / 4.2E+12; // impactor kinetic energy in kT TNT double diameter=2.0 * 18.0 * Math.pow(KT, 0.3) * GF; double depth=9.0 * Math.pow(KT, 0.3) * GF; return new double[] {diameter, depth}; } }
jankotek/asterope-scala-legacy
src/org/asterope/ephem/Star.java
214,343
package de.svws_nrw.core.abschluss.gost; import java.util.List; import java.util.ArrayList; import jakarta.validation.constraints.NotNull; /** * Eine abstrakte Basisklasse für Belegprüfungen auf Abiturdaten eines Schülers. * Eine Belegprüfung muss die abstrakten Methode gemäß ihrer Beschreibung implementieren. * Die Auswertung der Prüfungsergebnisse kann automatisiert über den zugehörigen * AbiturdatenManager erfolgen. */ public abstract class GostBelegpruefung { /** Eine ggf. zuvor durchgeführte Abitur-Belegprüfung, welche in dieser Belegprüfung als Voraussetzung vorhanden sein muss. */ protected final @NotNull GostBelegpruefung@NotNull[] pruefungen_vorher; /** Der Daten-Manager für die Abiturdaten */ protected final @NotNull AbiturdatenManager manager; /** Die Art der Belegprüfung (nur EF.1, Gesamte Oberstufe, evtl. weitere) */ protected final @NotNull GostBelegpruefungsArt pruefungs_art; /** Ein Set von Belegungsfehlern, die bei der Gesamtprüfung entstanden sind. */ private final @NotNull List<@NotNull GostBelegungsfehler> belegungsfehler = new ArrayList<>(); /** * Erstellt eine neue Belegprüfung, welche den angegebenen Daten-Manager verwendet. * * @param manager der Daten-Manager für die Abiturdaten * @param pruefungsArt die Art der durchzuführenden Prüfung (z.B. EF.1 oder GESAMT) * @param pruefungenVorher eine vorher durchgeführte Abiturprüfung */ protected GostBelegpruefung(final @NotNull AbiturdatenManager manager, final @NotNull GostBelegpruefungsArt pruefungsArt, final GostBelegpruefung... pruefungenVorher) { this.pruefungen_vorher = pruefungenVorher; this.manager = manager; this.pruefungs_art = pruefungsArt; } /** * Führt eine Belegprüfung durch. */ public void pruefe() { init(); if (pruefungs_art == GostBelegpruefungsArt.EF1) pruefeEF1(); else if (pruefungs_art == GostBelegpruefungsArt.GESAMT) pruefeGesamt(); } /** * Fügt einen Belegungsfehler zu der Belegprüfung hinzu. Diese Methode wird von den Sub-Klassen * aufgerufen, wenn dort ein Belegungsfehler erkannt wird. * * @param fehler der hinzuzufügende Belegungsfehler */ protected void addFehler(final @NotNull GostBelegungsfehler fehler) { if (!belegungsfehler.contains(fehler)) belegungsfehler.add(fehler); } /** * Gibt die Belegungsfehler zurück, welche bei der Gesamtprüfung aufgetreten sind. * * @return die Belegungsfehler */ public @NotNull List<@NotNull GostBelegungsfehler> getBelegungsfehler() { return belegungsfehler; } /** * Git zurück, ob ein "echter" Belegungsfehler vorliegt und nicht nur eine Warnung oder ein Hinweis. * * @return true, falls ein "echter" Belegungsfehler vorliegt. */ public boolean hatBelegungsfehler() { for (int i = 0; i < belegungsfehler.size(); i++) { final @NotNull GostBelegungsfehler fehler = belegungsfehler.get(i); if (!fehler.istInfo()) return false; } return true; } /** * Initialisiert die Daten für die Belegprüfungen mithilfe des Abiturdaten-Managers */ protected abstract void init(); /** * Führt alle Belegprüfungen für die EF.1 durch. */ protected abstract void pruefeEF1(); /** * Führt alle Belegprüfungen für die gesamte Oberstufe durch. */ protected abstract void pruefeGesamt(); /** * Gibt zurück, ob die angegebenen Belegprüfungsfehler einen "echten" Fehler beinhalten * und nicht nur einen Hinweise / eine Information. * * @param alleFehler die Belegprüfungsfehler und -informationen der durchgeführten Belegprüfungen * * @return true, falls kein "echter" Belegprüfungsfehler aufgetreten ist, sonst false */ public static boolean istErfolgreich(final @NotNull List<@NotNull GostBelegungsfehler> alleFehler) { for (int i = 0; i < alleFehler.size(); i++) { final @NotNull GostBelegungsfehler fehler = alleFehler.get(i); if (!fehler.istInfo()) return false; } return true; } /** * Liefert alle Belegprüfungsfehler der übergebenen Teil-Belegprüfungen zurück. * Doppelte Fehler werden dabei nur einfach zurückgegeben (Set). * * @param pruefungen die durchgeführten Belegprüfungen, deren Fehler zurückgegeben werden sollen. * * @return die Menge der Belegprüfungsfehler */ public static @NotNull List<@NotNull GostBelegungsfehler> getBelegungsfehlerAlle(final @NotNull List<@NotNull GostBelegpruefung> pruefungen) { final @NotNull ArrayList<@NotNull GostBelegungsfehler> fehler = new ArrayList<>(); for (int i = 0; i < pruefungen.size(); i++) { final @NotNull GostBelegpruefung pruefung = pruefungen.get(i); fehler.addAll(pruefung.getBelegungsfehler()); } return fehler; } }
SVWS-NRW/SVWS-Server
svws-core/src/main/java/de/svws_nrw/core/abschluss/gost/GostBelegpruefung.java
214,344
/* * Copyright (c) 2010-2021 Stefan Zoerner * * This file is part of DokChess. * * DokChess 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. * * DokChess 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 DokChess. If not, see <http://www.gnu.org/licenses/>. */ package de.dokchess.xboard.integration; import de.dokchess.engine.DefaultEngine; import de.dokchess.engine.Engine; import de.dokchess.regeln.DefaultSpielregeln; import de.dokchess.regeln.Spielregeln; import de.dokchess.xboard.XBoard; import org.junit.Assert; import org.junit.Rule; import org.junit.Test; import org.junit.rules.Timeout; import java.io.Reader; import java.io.StringReader; import java.io.StringWriter; /** * Starte das XBoard-Protokoll inkl. echter Engine. Mache einen Zug und warte * die Antwort ab. */ public class XBoardIntegTest { @Rule public Timeout timeout = Timeout.seconds(60); @Test public void anspielen() throws InterruptedException { String eingegeben = "xboard\nprotover 2\ne2e4\n"; final StringWriter ausgabe = new StringWriter(); XBoard xBoard = new XBoard(); xBoard.setAusgabe(ausgabe); Spielregeln spielregeln = new DefaultSpielregeln(); Engine engine = new DefaultEngine(spielregeln); xBoard.setEngine(engine); xBoard.setSpielregeln(spielregeln); Reader eingabe = new StringReader(eingegeben); xBoard.setEingabe(eingabe); xBoard.spielen(); String text; boolean running = true; while (running) { synchronized (ausgabe) { text = ausgabe.toString(); } if (text.contains("move ")) { running = false; } Thread.sleep(100); } synchronized (ausgabe) { text = ausgabe.toString(); } Assert.assertTrue(text.contains("move ")); } }
DokChess/dokchess
src/integTest/java/de/dokchess/xboard/integration/XBoardIntegTest.java
214,346
/* * 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.graphics; import de._13ducks.cor.game.client.ClientCore; import de._13ducks.cor.game.Building; import de._13ducks.cor.game.FloatingPointPosition; import java.awt.Dimension; import java.util.*; import java.util.concurrent.locks.ReentrantLock; import org.lwjgl.opengl.Display; import org.newdawn.slick.*; import de._13ducks.cor.map.AbstractMapElement; import de._13ducks.cor.game.Position; import de._13ducks.cor.game.Unit; import de._13ducks.cor.game.server.Server; import de._13ducks.cor.game.server.movement.FreePolygon; import de._13ducks.cor.game.server.movement.Node; import de._13ducks.cor.graphics.debug.GraphicsTimeAnalyser; import de._13ducks.cor.graphics.effects.SkyEffect; import org.newdawn.slick.geom.Polygon; @SuppressWarnings("CallToThreadDumpStack") public class GraphicsContent extends BasicGame { /** * Die Größe eines Feldes Richtung X. * Für Zeichenkoordinatenbestimmungen durch multiplizieren wird aber die Halbe benötigt! */ public static final int FIELD_SIZE_X = 20; /** * Die Größe eines Feldes Richtung Y. * Für Zeichenkoordinatenbestimmungen durch multiplizieren wird aber die Halbe benötigt! */ public static final int FIELD_SIZE_Y = 15; /** * Die halbe Größe eines Feldes in X-Richtung */ public static final int FIELD_HALF_X = FIELD_SIZE_X / 2; /** * Die halbe Größe eines Feldes in Y-Richtung */ public static final double FIELD_HALF_Y = FIELD_SIZE_Y / 2.0; /** * Wie viele Pixel das tatsächlich gezeichnete Feld von den Zeichenkoordinaten entfernt ist. */ public static final int BASIC_FIELD_OFFSET_X = 5; /** * Wie viele Pixel das tatsächlich gezeichnete Feld von den Zeichenkoordinaten entfernt ist. */ public static final double BASIC_FIELD_OFFSET_Y = 17.5; /** * Wie viele Pixel der Zeichenursprung für ein 1x1 Feld von dem Ursprung des Zuordungsfeldes entfernt ist. */ public static final int OFFSET_1x1_X = 3; /** * Wie viele Pixel der Zeichenursprung für ein 1x1 Feld von dem Ursprung des Zuordungsfeldes entfernt ist. */ public static final int OFFSET_1x1_Y = 0; /** * Wie viele Pixel der Zeichenursprung für ein 2x2 Feld von dem Rohkoordinatenfeld entfernt ist. */ public static final int OFFSET_2x2_X = -30; /** * Wie viele Pixel der Zeichenursprung für ein 2x2 Feld von dem Rohkoordinatenfeld entfernt ist. */ public static final int OFFSET_2x2_Y = -35; /** * Wie viele Pixel der Zeichenursprung für ein 2x2 Feld von dem Rohkoordinatenfeld entfernt ist. */ public static final int OFFSET_3x3_X = -40; /** * Wie viele Pixel der Zeichenursprung für ein 2x2 Feld von dem Rohkoordinatenfeld entfernt ist. */ public static final int OFFSET_3x3_Y = -54; /** * Diesen Abstand muss man bei allen Zeichenoperationen reinrechnen, die mit präzisen Pixeln arbeiten. */ public static final int OFFSET_PRECISE_X = 10; /** * Diesen Abstand muss man bei allen Zeichenoperationen reinrechnen, die mit präzisen Pixeln arbeiten. */ public static final int OFFSET_PRECISE_Y = 15; // Diese Klasse repräsentiert den Tatsächlichen GrafikINHALT von RogGraphics und RogMapEditor public GraphicsImage colModeImage; public int modi = -2; // Was gerendert werden soll, spezielle Ansichten für den Editor etc... AbstractMapElement[][] visMap; // Die angezeigte Map public boolean renderCursor = false; public boolean renderPicCursor = false; // Cursor, der ein Bild anzeigt, z.B. ein Haus, das gebaut werden soll public boolean renderFogOfWar = false; public GraphicsImage renderPic; public int sizeX; // Mapgröße public int sizeY; public int positionX; // Position, die angezeigt wird public int positionY; public int viewX; // Die Größe des Angezeigten ausschnitts public int viewY; public int realPixX; // Echte, ganze X-Pixel public int realPixY; // Echte, ganze Y-Pixel private HashMap<String, GraphicsImage> imgMap; // Enthält alle Bilder public HashMap<String, GraphicsImage> coloredImgMap; Image renderBackground = null; // Bodentextur, nur Bild-Auflösung int rBvX; // Position während der letzen Bildberechnung int rBvY; // Position während der letzen Bildberechnung public boolean serverColMode = false; boolean useAntialising = false; // Kantenglättung, normalerweise AUS // NUR IM NORMALEN RENDERMODE public List<Sprite> allList; public static boolean alwaysshowenergybars = false; // Energiebalken immer anzeigen, WC3 lässt grüßen. Date initRun; Dimension framePos = new Dimension(0, 0); // Editor-Rahmen public int epoche = 2; // Null ist keine Epoche, also kein Gescheites Grundbild.. private ClientCore.InnerClient rgi; private static final boolean beautyDraw = true; // Schöner zeichnen durch umsortieren der allList, kostet Leistung public int mouseX; // Die Position der Maus, muss geupdatet werden public int mouseY; // Die Position der Maus, muss geupdatet werden int lastHovMouseX; int lastHovMouseY; public boolean pauseMode = false; // Pause-Modus Color fowGray = new Color(0.0f, 0.0f, 0.0f, 0.4f); long pause; // Zeitpunkt der letzen Pause public boolean saveMode = false; // Sicherer Grafikmodus ohne unsichere, weil zu Große Bilder public boolean coordMode = false; // Modus, der die Koordinaten der Felder mit anzeigt. public boolean idMode = false; // Modus, der die NetIds von Einheiten/Gebäuden und Ressourcen mit anzeigt. public int unitDestMode = 0; // Modus, der die Ziele von Einheiten (Bewegung & Angriff) anzeigt (Aus/Eigene/Fremde/Alle)0123 public byte[][] fowmap; // Fog of War - Map GraphicsFogOfWarPattern fowpatmgr; // Managed und erstellt Fow-Pattern boolean updateBuildingsFow = false; // Lässt den Gebäude-Fow neu erstellen public boolean buildingsChanged = false; public boolean epocheChanged = false; public boolean fowDisabled = false; public int loadStatus = 0; public boolean loadWait = false; public Image duckslogo; public int imgLoadCount = 0; public int imgLoadTotal = 0; CoreGraphics parent; public int initState = -1; // Damit alles Slick laden kann, sonst weigert es sich zu arbeiten :( // Slick ist monoTreaded... // Die Grafik muss also auch manche Input-Events berechnen: public int lastInputEvent = 0; public int lastInputX = 0; public int lastInputY = 0; public int lastInputButton = 0; // Startbildschirm - Error: public boolean launchError = false; public boolean launchScreenGrayed = false; public int lEtype = 0; // Fehler, siehe public int gameDone = 0; // Spiel zu Ende? 1=ja, mit Sieg; 2 = ja mit Niederlage; 3 = nein, aber trotzdem verloren public long endTime; public ReentrantLock allListLock; public ArrayList<Overlay> overlays; public ArrayList<SkyEffect> skyEffects; public GraphicsFireManager fireMan; private Minimap minimap; private IngameMenu ingamemenu; private ResourceCounter resourcecounter; private boolean graphicsDebug = false; private GraphicsTimeAnalyser analyser; public void paintComponent(Graphics g) { //Die echte, letzendlich gültige paint-Methode, sollte nicht direkt aufgerufen werden if (modi == -2) { // 13Ducks-Logo //g.setColor(Color.green); //g.fillRect(10, 10, 10, 10); g.setBackground(Color.white); g.clear(); duckslogo.drawCentered(realPixX / 2, realPixY / 2); // Sobald es einmal gezeichnet wurde können wir weiter laden initState = 12; modi = 0; } else if (modi == -1) { // Ladebildschirm (pre-Game) renderLoadScreen(g); } else if (modi == 3) { if (graphicsDebug) { analyser.startFrame(); } try { if (pauseMode) { // Pause für diesen Frame freischalten: pause = rgi.rogGraphics.getPauseTime(); } // // FoW updaten? // if (!fowDisabled && updateBuildingsFow) { // updateBuildingsFow = false; // this.updateBuildingFoW(); // } g.setAntiAlias(useAntialising); // Alles löschen g.setColor(Color.white); g.fillRect(0, 0, realPixX, realPixY); // Boden und Fix rendern renderBackground(); // Einheiten nach ihrer Y-Enfernung sortieren, erzeugt räumlichen Eindruck. if (beautyDraw) { try { allListLock.lock(); Collections.sort(allList); } catch (Exception ex) { System.out.println("FixMe: SortEX-reg"); } finally { allListLock.unlock(); } } // @TODO: buildingwaypoint als groundeffect rendern renderBuildingWaypoint(); // Input-Modul-Hover holen // if (mouseX != lastHovMouseX || mouseY != lastHovMouseY) { // // Wenn sichs geändert hat neu suchen // // hoveredUnit = identifyUnit(mouseX, mouseY); // lastHovMouseX = mouseX; // lastHovMouseY = mouseY; // } // Das derzeit gehoverte Sprite bestimmen parent.inputM.triggerHovered(); renderSpriteGroundEffects(g); //@TODO: Einheitenziel als groundeffect rendern if (unitDestMode != 0) { renderUnitDest(g); } // Jetzt alle Sprites rendern renderSprites(g); //@TODO: fireeffects als skyeffect rendern //fireMan.renderFireEffects(buildingList, lastDelta, positionX, positionY); renderSpriteSkyEffects(g); // Fog of War rendern, falls aktiv // if (renderFogOfWar) { // renderFogOfWar(g); // } renderSkyEffects(g); if (renderPicCursor) { renderCursor(); } /* if (this.dragSelectionBox) { renderSelBox(g); }*/ if (idMode) { renderIds(g); } // Mouse-Hover rendern if (pauseMode) { renderPause(g); } g.setColor(Color.darkGray); g.setFont(FontManager.getFont0()); //g3.setFont(new UnicodeFont(java.awt.Font.decode("8"))); g.drawString("13 Ducks Entertainment's: Centuries of Rage HD (pre-alpha)", 10, 2); if (serverColMode) { this.renderServerCol(g); } if (coordMode) { renderCoords(g); } // Overlays rendern: renderOverlays(g); } catch (Exception ex) { System.out.println("Error while rendering frame, dropping."); ex.printStackTrace(); } // Pause zurücksetzten pause = 0; if (graphicsDebug) { analyser.endFrame(); } } } /** * Zeichnet alle SkyEffects, die derzeit sichtbar sind. * Schmeißt SkyEffects raus, die fertig sind. * @param g der Grafikkontext */ private void renderSkyEffects(Graphics g) { for (int i = 0; i < skyEffects.size(); i++) { SkyEffect sky = skyEffects.get(i); if (sky.isDone()) { // Löschen skyEffects.remove(i); i--; continue; } if (sky.isVisible(positionX * FIELD_HALF_X, positionY * FIELD_HALF_Y, realPixX, realPixY)) { sky.renderSkyEffect(g, positionX * FIELD_HALF_X, positionY * FIELD_HALF_Y); } } } /** * Zeichnet alle Sprites auf den Bildschirm, falls diese derzeit im sichtbaren Bereich liegen, * gemäß dem FOW gezeichnet werden sollen und sich nicht verstecken. * @param g */ private void renderSprites(Graphics g) { // Sprites sortieren //@TODO: Hier kann eine CucurrentModificationException auftreten. Collections.sort(allList, new Comparator<Sprite>() { @Override public int compare(Sprite o1, Sprite o2) { return o1.getSortPosition().getY() - o2.getSortPosition().getY(); } }); for (int i = 0; i < allList.size(); i++) { Sprite sprite = allList.get(i); if (spriteInSight(sprite)) { //@TODO: FOW-Behandlung einbauen if (sprite.renderInNullFog()) { Position mainPos = sprite.getMainPositionForRenderOrigin(); sprite.renderSprite(g, (mainPos.getX() - positionX) * FIELD_HALF_X, (int) ((mainPos.getY() - positionY) * FIELD_HALF_Y), positionX * FIELD_HALF_X, positionY * FIELD_HALF_Y, rgi.game.getPlayer(sprite.getColorId()).color); } } } } /** * Zeichnet alle Groundeffects aller Sprites auf den Bildschirm, falls diese derzeit im sichtbaren Bereich liegen, * gemäß dem FOW gezeichnet werden sollen und sich nicht verstecken. * @param g */ private void renderSpriteGroundEffects(Graphics g) { for (int i = 0; i < allList.size(); i++) { Sprite sprite = allList.get(i); if (spriteInSight(sprite)) { //@TODO: FOW-Behandlung einbauen if (sprite.renderInNullFog()) { Position mainPos = sprite.getMainPositionForRenderOrigin(); sprite.renderGroundEffect(g, (mainPos.getX() - positionX) * FIELD_HALF_X, (int) ((mainPos.getY() - positionY) * FIELD_HALF_Y), positionX * FIELD_HALF_X, positionY * FIELD_HALF_Y, rgi.game.getPlayer(sprite.getColorId()).color); } } } } /** * Zeichnet alle SkyEffects aller Sprites auf den Bildschirm, falls diese derzeit im sichtbaren Bereich liegen, * gemäß dem FOW gezeichnet werden sollen und sich nicht verstecken. * @param g */ private void renderSpriteSkyEffects(Graphics g) { for (int i = 0; i < allList.size(); i++) { Sprite sprite = allList.get(i); if (spriteInSight(sprite)) { //@TODO: FOW-Behandlung einbauen if (sprite.renderInNullFog()) { Position mainPos = sprite.getMainPositionForRenderOrigin(); sprite.renderSkyEffect(g, (mainPos.getX() - positionX) * FIELD_HALF_X, (int) ((mainPos.getY() - positionY) * FIELD_HALF_Y), positionX * FIELD_HALF_X, positionY * FIELD_HALF_Y, rgi.game.getPlayer(sprite.getColorId()).color); } } } } /** * Findet heraus, ob ein Sprite gerade im sichtbaren Bereich liegt. * Reine Scroll-Überprüfung, macht nichts mit FOW oder verstecken. * @param s * @return */ private boolean spriteInSight(Sprite s) { Position[] visPos = s.getVisisbilityPositions(); for (Position pos : visPos) { if (positionInSight(pos)) { // Wenn irgendwas sichtbar ist, dann true return true; } } // Kein einziges Feld im sichtbaren --> false return false; } /** * Findet heraus, ob eine Position (ein Feld) derzeit im sichtbaren Bereich liegt. * Reine Scroll-Überprüfung, macht nichts mit FOW. * @param s * @return */ private boolean positionInSight(Position s) { if (s.getX() >= positionX && s.getX() < positionX + viewX) { if (s.getY() >= positionY && s.getY() < positionY + viewY) { return true; } } return false; } /** * Zeichnet alle Health-Bars. * @param g2 */ /* private void renderHealthBars(Graphics g2) { for (int i = 0; i < buildingList.size(); i++) { Building b = buildingList.get(i); if (b.isSelected || (this.alwaysshowenergybars && b.wasSeen)) { this.renderHealth(b, g2, (b.position.getX() - positionX) * 20, (b.position.getY() - positionY) * 15); } } for (int i = 0; i < unitList.size(); i++) { Unit u = unitList.get(i); if (u.isSelected || (this.alwaysshowenergybars && u.alive)) { // Ist diese Einheit gerade sichtbar? (nur eigene oder sichtbare zeichnen) if (u.playerId == rgi.game.getOwnPlayer().playerId || rgi.game.shareSight(u, rgi.game.getOwnPlayer()) || fowmap[u.position.getX()][u.position.getY()] > 1) { Position tempP = null; if (u.isMoving()) { tempP = u.getMovingPosition(rgi, positionX, positionY); } else { tempP = new Position((u.position.getX() - positionX) * 20, (u.position.getY() - positionY) * 15); } renderHealth(u, g2, tempP.getX(), tempP.getY()); } } } } */ private void renderOverlays(Graphics g2) { // Zeichnet alle Overlays. for (int i = 0; i < overlays.size(); i++) { try { overlays.get(i).renderOverlay(g2, realPixX, realPixY); } catch (Exception ex) { ex.printStackTrace(); } } } /** * Zeichnet die Bewegungs und Angriffsziele aller Einheiten an, zum Debuggen * @param g2 */ private void renderUnitDest(Graphics g2) { // int mode = unitDestMode; // g2.setLineWidth(2); // for (int x = 0; x < unitList.size(); x++) { // Unit unit = unitList.get(x); // // Modus abfragen: // if (mode == 3 || (mode == 1 && unit.getPlayerId() == rgi.game.getOwnPlayer().getPlayerId()) || (mode == 2 && unit.getPlayerId() != rgi.game.getOwnPlayer().getPlayerId())) { // // Zuerst Bewegung // if (unit.movingtarget != null) { // // Markieren, ob Einheit flieht oder nicht // if (unit.getbehaviourC(4).active) { // // Angry, roter Punkt // g2.setColor(Color.red); // } else { // g2.setColor(Color.blue); // } // // Source (unit selber) // Position pos = unit.getMovingPosition(rgi, positionX, positionY); // int sx = pos.getX(); // int sy = pos.getY(); // g2.fillRect(sx, sy, 5, 5); // // Target (ziel) // // Diese 2. Abfrage ist sinnvoll und notwendig, weil getMovingPosition am Ende der Bewegung das movingtarget löscht // if (unit.movingtarget != null) { // int tx = (unit.movingtarget.getX() - positionX) * 20; // int ty = (unit.movingtarget.getY() - positionY) * 15; // // Zeichnen // g2.setColor(new Color(3, 100, 0)); // Dunkelgrün // g2.drawLine(sx + 19, sy + 25, tx + 19, ty + 25); // } // } // // Jetzt Angriff // if (unit.attacktarget != null) { // g2.setColor(Color.red); // // Source (unit selber) // int sx = (unit.position.getX() - positionX) * 20; // int sy = (unit.position.getY() - positionY) * 15; // if (unit.isMoving()) { // Position pos = unit.getMovingPosition(rgi, positionX, positionY); // sx = pos.getX(); // sy = pos.getY(); // } // // Target (ziel) // int tx = 0; // int ty = 0; // if (unit.attacktarget.getClass().equals(Unit.class)) { // Unit target = (Unit) unit.attacktarget; // if (target.isMoving()) { // Position pos = target.getMovingPosition(rgi, positionX, positionY); // tx = pos.getX(); // ty = pos.getY(); // } else { // tx = (target.position.getX() - positionX) * 20; // ty = (target.position.getY() - positionY) * 15; // } // } else if (unit.attacktarget.getClass().equals(Building.class)) { // Building target = (Building) unit.attacktarget; // //Gebäude-Mitte finden: // float bx = 0; // float by = 0; // //Z1 // //Einfach die Hälfte als Mitte nehmen // bx = target.position.getX() + ((target.getZ1() - 1) * 1.0f / 2); // by = target.position.getY() - ((target.getZ1() - 1) * 1.0f / 2); // //Z2 // // Einfach die Hälfte als Mitte nehmen // bx += ((target.getZ2() - 1) * 1.0f / 2); // by += ((target.getZ2() - 1) * 1.0f / 2); // // Gebäude-Mitte gefunden // tx = (int) ((bx - positionX) * 20) - 19; // ty = (int) ((by - positionY) * 15) - 25; // } // // Zeichnen // g2.drawLine(sx + 19, sy + 25, tx + 19, ty + 25); // } // } // } // g2.setLineWidth(1); } /** * Zeichnet NetIds von allen Einheiten / Gebäuden / Ressourcen * Zum Debugen. Funktioniert nur, wenn die Debug-Tools (cheats) aktiviert sind * @param g2 */ private void renderIds(Graphics g2) { // g2.setColor(Color.cyan); // g2.setFont(fonts[4]); // // Einheiten durchgehen // for (int i = 0; i < unitList.size(); i++) { // Unit unit = unitList.get(i); // if (unit.isMoving()) { // Position pos = unit.getMovingPosition(rgi, positionX, positionY); // g2.drawString(String.valueOf(unit.netID), pos.getX() + 10, pos.getY() + 16); // } else { // g2.drawString(String.valueOf(unit.netID), (unit.position.getX() - positionX) * 20 + 10, (unit.position.getY() - positionY) * 15 + 16); // } // } // // Gebäude // for (int i = 0; i < buildingList.size(); i++) { // Building building = buildingList.get(i); // g2.drawString(String.valueOf(building.netID), (building.position.getX() - positionX) * 20 + 10, (building.position.getY() - positionY) * 15 + 16); // } // // Ressourcen // for (int i = 0; i < resList.size(); i++) { // Ressource res = resList.get(i); // g2.drawString(String.valueOf(res.netID), (res.position.getX() - positionX) * 20 + 10, (res.position.getY() - positionY) * 15 + 16); // } } private void renderLoadScreen(Graphics g2) { // Löschen if (loadStatus < 10) { g2.setBackground(Color.white); g2.clear(); } //g2.clearRect(0, 0, realPixX, realPixY); if (launchError && !launchScreenGrayed) { parent.setTargetFrameRate(25); launchScreenGrayed = true; } // Ladebalken zeigen int lx = realPixX / 4; // Startposition des Balkens int ly = realPixY / 50; int dx = realPixX / 2; // Länge des Balkens int dy = realPixY / 32; g2.setColor(new Color(0, 0, 0, 0.8f)); // Rahmen ziehen g2.drawRect(lx - 2, ly - 2, dx + 3, dy + 3); // Balken zeichnen if (loadStatus != 4 || imgLoadTotal == 0) { g2.fillRect(lx, ly, dx * loadStatus / 10, dy); } else { int dxf = dx * loadStatus / 10 + (int) ((1.0 * this.imgLoadCount / imgLoadTotal) * dx / 10); g2.fillRect(lx, ly, dxf, dy); } // Status drunter anzeigen String status = "Status: "; if (!loadWait) { switch (loadStatus) { case 0: status = status + "waiting for server..."; break; case 1: status = status + "receiving gamesettings (phase 1 of 2)..."; break; case 2: status = status + "receiving gamesettings (phase 2 of 2)..."; break; case 3: status = status + "computing received gamesettings..."; break; case 4: status = status + "loading graphics (phase 1 of 2): importing images & textures"; break; case 5: status = status + "loading graphics (phase 2 of 2): importing animations"; break; case 6: status = status + "searching map..."; break; case 7: status = status + "downloading map..."; break; case 8: status = status + "loading map..."; break; case 9: status = status + "preparing start..."; break; case 10: status = status + "Centuries of Rage: Loading done! Have a lot of fun..."; break; } } else { switch (loadStatus) { case 5: status = status + "waiting for other players..."; break; case 8: status = status + "waiting for other players..."; break; case 9: status = status + "waiting for other players to finish preparations..."; break; } } g2.setFont(FontManager.getFont0()); g2.drawString(status, lx, (int) (ly + (dy * 1.5))); // Error - Status if (launchError) { // Allgemeinen Fehlerkasten zeichnen: int ex = realPixX / 5; // Startposition des Balkens int ey = realPixY / 10 * 2; int edx = realPixX / 5 * 3; // Länge des Balkens int edy = realPixY / 2; // Kasten zeichnen g2.setColor(Color.red); g2.fillRect(ex, ey, edx, edy); g2.setColor(Color.black); g2.drawRect(ex, ey, edx, edy); g2.drawRect(ex + 2, ey + 2, edx - 4, edy - 4); // Allgemeine Überschrift: g2.setFont(FontManager.getFont0()); g2.setAntiAlias(false); g2.drawString("ERROR! - SORRY!", ex + (edx / 2) - (FontManager.getFont0().getWidth("ERROR! - SORRY!") / 2), (float) (ey * 1.05)); g2.drawLine(ex + 2, (float) (ey + (edy * 0.9)), ex + edx - 2, (float) (ey + (edy * 0.9))); g2.drawString("Click here or press ENTER to quit", ex + (edx / 2) - (FontManager.getFont0().getWidth("Click here or press ENTER to quit") / 2), (float) (ey + (edy * 0.95) - 6)); } } private void renderBuildingWaypoint() { // // Gebäude-Sammelpunkt zeichnen // if (!rgi.rogGraphics.inputM.selected.isEmpty() && rgi.rogGraphics.inputM.selected.get(0).getClass().equals(Building.class)) { // Building b = (Building) rgi.rogGraphics.inputM.selected.get(0); // if (b.waypoint != null) { // // Dahin rendern // GraphicsImage image = coloredImgMap.get("img/game/building_defaulttarget.png" + b.getPlayerId()); // if (image != null) { // image.getImage().draw(((b.waypoint.getX() - positionX) * 20) - 40, ((b.waypoint.getY() - positionY) * 15) - 40); // } else { // System.out.println("ERROR: Textures missing (34124)"); // } // } // } } private void renderFogOfWar(Graphics g) { // // Rendert den Fog of War. Liest ihn dazu einfach aus der fowmap aus. // // Das Festlegen der fog-Map wird anderswo erledigt... // // Murks, aber die position müssen gerade sein... // if (positionX % 2 == 1) { // positionX--; // } // if (positionY % 2 == 1) { // positionY--; // } // for (int x = 0; x < (sizeX) && x < (viewX); x = x + 2) { // for (int y = 0; y < (sizeY) && y < (viewY + 2); y = y + 2) { // // Ist hier Schatten? // try { // byte fow = fowmap[x + positionX][y + positionY - 2]; // if (fow < 2) { // if (fow == 0) { // g.setColor(Color.black); // } else { // g.setColor(fowGray); // } // //g.fill(fowShape); // g.fillRect(x * 20, (y - 2) * 15 + 10, 40, 30); // } // } catch (ArrayIndexOutOfBoundsException ar) { // } catch (Exception ex) { // ex.printStackTrace(); // } // } // } // for (int x = 1; x < (sizeX) && x < (viewX + 4); x = x + 2) { // for (int y = 1; y < (sizeY) && y < (viewY + 2); y = y + 2) { // // Ist hier Schatten? // try { // byte fow = fowmap[x + positionX - 2][y + positionY - 2]; // if (fow < 2) { // if (fow == 0) { // g.setColor(Color.black); // } else { // g.setColor(fowGray); // } // g.fillRect((x - 2) * 20, (y - 2) * 15 + 10, 40, 30); // } // } catch (ArrayIndexOutOfBoundsException ar) { // } catch (Exception ex) { // ex.printStackTrace(); // } // } // } } private void renderPause(Graphics g2) { // PAUSE - Overlay rendern g2.setColor(Color.lightGray); g2.fillRect(realPixX / 3, realPixY / 3, realPixX / 3, realPixY / 5); g2.setColor(Color.black); g2.setFont(FontManager.getFont0()); g2.drawString("P A U S E", realPixX / 2 - 80, realPixY / 2 - 60); g2.drawRect(realPixX / 3, realPixY / 3, realPixX / 3, realPixY / 5); } private void renderSelBox(Graphics g2) { // // Rendert die SelektionBox // g2.setColor(Color.lightGray); // int dirX = mouseX - this.boxselectionstart.width; // int dirY = mouseY - this.boxselectionstart.height; // // Bpxen können nur von links oben nach rechts unten gezogen werden - eventuell Koordinaten tauschen // if (dirX < 0 && dirY > 0) { // // Nur x Tauschen // g2.drawRect(mouseX, this.boxselectionstart.height, this.boxselectionstart.width - mouseX, mouseY - this.boxselectionstart.height); // } else if (dirY < 0 && dirX > 0) { // // Nur Y tauschen // g2.drawRect(this.boxselectionstart.width, mouseY, mouseX - this.boxselectionstart.width, this.boxselectionstart.height - mouseY); // } else if (dirX < 0 && dirY < 0) { // // Beide tauschen // g2.drawRect(mouseX, mouseY, this.boxselectionstart.width - mouseX, this.boxselectionstart.height - mouseY); // } // // Nichts tauschen // g2.drawRect(this.boxselectionstart.width, this.boxselectionstart.height, dirX, dirY); } private void renderCursor() { if (renderPicCursor) { // Pic-Cursor // Einfach Bild an die gerasterte Cursorposition rendern. renderPic.getImage().draw(framePos.width * FIELD_HALF_X, (int) (framePos.height * FIELD_HALF_Y)); } } private void renderBackground() { /*if (modi != 3) { g2.drawImage(renderBackground, 0, 0); } else { if (g2 == null) { } g2.drawImage(renderBackground, 0, 0, realPixX, realPixY, positionX * 20, positionY * 15, (positionX * 20) + realPixX, (positionY * 15) + realPixY); } */ //System.out.println("This is runRenderRound, searching for <" + searchprop + "> mapsize(x,y) view [x,y]: (" + sizeX + "," + sizeY + ") [" + viewX + "," + viewY + "]"); // Alte Methode - Große Background-Bilder im Speicher verträgt nicht jedes System //runRenderRound("ground_tex", g2); //runRenderRound("fix_tex", g2); // Neu berechnen oder altes nehmen? if (rBvX == positionX && rBvY == positionY && renderBackground != null) { // Gleich altes nehmen renderBackground.draw(0, 0); } else { if (renderBackground == null) { System.out.println("ACHTUNG: RE-RENDERING BACKGROUND!!!!!"); } // Neu berechnen: try { if (renderBackground == null) { renderBackground = new Image(realPixX, realPixY); } Graphics g3 = renderBackground.getGraphics(); rBvX = positionX; rBvY = positionY; g3.setColor(Color.white); g3.fillRect(0, 0, renderBackground.getWidth(), renderBackground.getHeight()); for (int x = -2; x < sizeX && x < viewX; x += 1) { for (int y = -2; y < sizeY && y < viewY; y += 1) { if ((x + y) % 2 == 1) { continue; } // X und Y durchlaufen, wenn ein Bild da ist, dann einbauen // System.out.println("Searching for " + x + "," + y); String ground = null; try { ground = visMap[x + positionX][y + positionY].getGround_tex(); } catch (Exception ex) { // Kann beim Scrollein vorkommen - Einfach nichts zeichnen, denn da ist die Map zu Ende... } // Was da? if (ground != null) { Renderer.drawImage(ground, x * FIELD_HALF_X + OFFSET_1x1_X, (int) (y * FIELD_HALF_Y) + OFFSET_1x1_Y); } } } for (int x = -2; x < sizeX && x < (viewX + 1); x += 1) { for (int y = -2; y < sizeY && y < (viewY + 1); y += 1) { if ((x + y) % 2 == 1) { continue; } String fix = null; try { fix = visMap[x + positionX][y + positionY].getFix_tex(); } catch (Exception ex) { // Kann beim Scrollein vorkommen - Einfach nichts zeichnen, denn da ist die Map zu Ende... } if (fix != null) { Renderer.drawImage(fix, x * FIELD_HALF_X + OFFSET_1x1_X, (int) (y * FIELD_HALF_Y) + OFFSET_1x1_Y); } } } g3.flush(); renderBackground.draw(0, 0); } catch (org.newdawn.slick.SlickException ex) { } } } private void renderServerCol(Graphics g) { // Neues Bewegungssystem List<FreePolygon> polys = rgi.mapModule.moveMap.getPolysForDebug(); for (FreePolygon poly : polys) { g.setColor(poly.getColor()); Polygon gPoly = new Polygon(); List<Node> nodes = poly.getNodes(); for (Node node : nodes) { gPoly.addPoint((float) (node.getX() - positionX) * FIELD_HALF_X + BASIC_FIELD_OFFSET_X, (float) ((float) ((node.getY() - positionY) * FIELD_HALF_Y) + BASIC_FIELD_OFFSET_Y)); } g.fill(gPoly); } // // Murks, aber die position müssen gerade sein... // if (positionX % 2 == 1) { // positionX--; // } // if (positionY % 2 == 1) { // positionY--; // } // // Rendert die blaueb Kollisionsfarbe // for (int x = 0; x < sizeX && x < viewX; x++) { // for (int y = 0; y < sizeY && y < viewY; y++) { // if (x % 2 != y % 2) { // continue; // Nur echte Felder // } // // Hat dieses Feld Kollision? // try { // int val = rgi.mapModule.serverCollision[x + positionX][y + positionY]; // switch (val) { // case 1: // getImgMap().get("img/game/highlight_red.png").getImage().draw(x * FIELD_HALF_X, (int) (y * FIELD_HALF_Y)); // break; // case 2: // getImgMap().get("img/game/highlight_yellow_reddot.png").getImage().draw(x * FIELD_HALF_X, (int) (y * FIELD_HALF_Y)); // break; // case 3: // getImgMap().get("img/game/highlight_blue.png").getImage().draw(x * FIELD_HALF_X, (int) (y * FIELD_HALF_Y)); // break; // } // if (rgi.mapModule.serverRes[x + positionX][y + positionY] > System.currentTimeMillis()) { // imgMap.get("img/game/highlight_bluecross.png").getImage().draw(x * FIELD_HALF_X, (int) (y * FIELD_HALF_Y)); // } // } catch (Exception ex) { // } // } // } } private void renderCoords(Graphics g2) { // Gitter rendern g2.setColor(Color.black); g2.setLineWidth(1); for (int i = 0; i < viewX * 2; i += 2) { // Doppelt so lang, das Bildverhältniss ist ja in der Regel nicht quadratisch // Linie von der Oberen Kante nach rechts unten g2.drawLine(i * FIELD_HALF_X + 2, 0, viewX * FIELD_HALF_X + 20, (int) ((viewX - 1 - i) * FIELD_HALF_Y + 21)); // Linie von der Oberen Kante nach links unten g2.drawLine(i * FIELD_HALF_X + 28, 0, 0, (int) (i * FIELD_HALF_Y + 21)); } for (int i = 0; i < viewY; i += 2) { // Linie von der Linken Kante nach Rechts Unten g2.drawLine(0, (int) (i * FIELD_HALF_Y) - 1, (viewY - 1 - i) * FIELD_HALF_X + 42, (int) ((viewY * FIELD_HALF_Y) + 22.5)); } // Aktuelle Position suchen: Position mouse = translateCoordinatesToField(mouseX, mouseY); FloatingPointPosition precise = translateCoordinatesToFloatPos(mouseX, mouseY); // Position markieren: Renderer.drawImage("img/game/highlight_blue.png", (mouse.getX() - positionX) * FIELD_HALF_X, (int) ((mouse.getY() - positionY) * FIELD_HALF_Y)); // Position anzeigen g2.setColor(Color.white); Font font = rgi.chat.getFont(); String output = "Mouse: " + mouse.getX() + " " + mouse.getY(); String precout = "Mouse (precise): " + precise.getfX() + " " + precise.getfY(); g2.fillRect(5, 40, font.getWidth(output), font.getHeight(output)); g2.fillRect(5, 60, font.getWidth(precout), font.getHeight(precout)); g2.setFont(font); g2.setColor(Color.black); g2.drawString(output, 5, 40); g2.drawString(precout, 5, 60); // DEBUG - Begehbarkeit anzeigen: String walk = "free"; if (Server.getInnerServer().netmap.getMoveMap().isPositionWalkable(precise)) { walk = "blocked"; } g2.drawString(walk, 5, 80); } public void setFramePosition(Dimension td) { // Setzt die Position des Rahmens, inzwischen Editor&Game framePos = td; } public void setVisMap(AbstractMapElement[][] newVisMap, int X, int Y) { // Einfach einsetzen visMap = newVisMap; sizeX = X; sizeY = Y; fowmap = new byte[visMap.length][visMap[0].length]; // Durchlaufen, alles auf 0 (unerforscht) setzen for (int x = 0; x < fowmap.length; x++) { for (int y = 0; y < fowmap[0].length; y++) { fowmap[x][y] = 0; } } } public void setImageMap(HashMap<String, GraphicsImage> newMap) { // Die Bilder, die verfügbar sind imgMap = newMap; } public void setPosition(int posX, int posY) { // Setzt die aktuell sichtbare Position positionX = posX; positionY = posY; viewPosChanged(); } public void setVisibleArea(int vX, int vY) { //Setzt die Größe des sichtbaren Bereichs viewX = vX; viewY = vY; } public void setFogofwar(boolean rFow) { // Fog of War rendern renderFogOfWar = rFow; } public void setCursor(boolean rcursor) { renderCursor = rcursor; if (rcursor) { // Cursor unsichtbar machen parent.setMouseGrabbed(true); } else { parent.setMouseGrabbed(false); } } // Löscht die gesamte Fow-Map (überschreibt sie mit 0 (unerkundet)) // Bereits erkundete Bereiche bleiben erkundet private void clearFogOfWar() { for (int x = 0; x < fowmap.length; x++) { for (int y = 0; y < fowmap[0].length; y++) { if (fowmap[x][y] == 2) { fowmap[x][y] = 0; } } } } /** * Setzt alles auf Sichtbar. Kann nicht rückgängig gemacht werden. Ist cheaten */ public void freeFogOfWar() { for (int x = 0; x < fowmap.length; x++) { for (int y = 0; y < fowmap[0].length; y++) { fowmap[x][y] = 3; } } } /** * Startet das Rendern * @param rImg ein VolatileImage, im Savemode ein BufferedImage */ public void startRender() { // Echter Game-Rendering Mode // rImg ist Hintergrundbild modi = 3; initRun = new Date();// Das mach ich jetzt genau ein mal, das muss in den Gebäudebau-Handling-Code... // try {Thread.sleep(100000);} catch (Exception ex) {} } public void scrollUp() { // Ansicht ein Feld nach oben bewegen if (positionY > 1) { if (positionY == 1) { //positionY--; } else { positionY = positionY - 2; } } if (positionY % 2 == 1) { positionY++; } viewPosChanged(); } public void scrollRight() { if (viewX < sizeX) { // Ans sonsten ist eh alles drin if (positionX < (sizeX - viewX)) { positionX = positionX + 2; } } viewPosChanged(); } public void scrollLeft() { if (positionX >= 1) { if (positionX == 1) { //positionX--; } else { positionX = positionX - 2; } } if (positionX % 2 == 1) { positionX--; } viewPosChanged(); } public void scrollDown() { if (viewY < sizeY) { // Ansonsten ist eh alles drin, da brauch mer nicht scrollen... if (positionY < (sizeY - viewY)) { positionY = positionY + 2; } } viewPosChanged(); } /** * Informiert die Minimap darüber, dass sich die derzeitige AnzeigePosition geändert hat. */ private void viewPosChanged() { if (minimap != null) { // Falls aktiv minimap.viewChanged(positionX, positionY, viewX, viewY, sizeX, sizeY); } } public Dimension getSelectedField(int selX, int selY) { // Findet heraus, welches Feld geklickt wurde - Man muss die Felder mittig anklicken, sonst gehts nicht // Wir haben die X und Y Koordinate auf dem Display und wollen die X und Y Koordinate auf der Map bekommen // Versatz beachten selX = selX - 10; selY = selY - 15; // Grundposition bestimmen int coordX = selX / FIELD_HALF_X; int coordY = (int) (selY / FIELD_HALF_Y); // Scrollposition addieren coordX = coordX + positionX; coordY = coordY + positionY; boolean xg = (coordX % 2 == 0); boolean yg = (coordY % 2 == 0); if (xg != yg) { coordY--; } return new Dimension(coordX, coordY); } public Dimension getSpecialSelectedField(int selX, int selY) { // Position nicht hineinrechnen // Findet heraus, welches Feld geklickt wurde - Man muss die Felder mittig anklicken, sonst gehts nicht // Wir haben die X und Y Koordinate auf dem Display und wollen die X und Y Koordinate auf der Map bekommen // Versatz beachten selX = selX - OFFSET_PRECISE_X; selY = selY - OFFSET_PRECISE_Y; // Grundposition bestimmen int coordX = selX / FIELD_HALF_X; int coordY = (int) (selY / FIELD_HALF_Y); // Scrollposition addieren boolean xg = (coordX % 2 == 0); boolean yg = (coordY % 2 == 0); if (xg != yg) { coordY--; } return new Dimension(coordX, coordY); } public Position translateCoordinatesToField(int x, int y) { // Grundposition bestimmen // Versatz beachten x = x - OFFSET_PRECISE_X; y = y - OFFSET_PRECISE_Y; int coordX = x / FIELD_HALF_X; int coordY = (int) (y / FIELD_HALF_Y); // Scrollposition addieren coordX = coordX + positionX; coordY = coordY + positionY; // Keine ZwischenFelder boolean xg = (coordX % 2 == 0); boolean yg = (coordY % 2 == 0); if (xg != yg) { coordX++; } return new Position(coordX, coordY); } public FloatingPointPosition translateCoordinatesToFloatPos(int x, int y) { // Versatz beachten x = x - 10; y = y - 15; double coordX = (double) x / FIELD_HALF_X; double coordY = (double) y / FIELD_HALF_Y; // Scrollposition addieren coordX = coordX + positionX; coordY = coordY + positionY; return new FloatingPointPosition(coordX, coordY); } /* public void klickedOnMiniMap(final int button, final int x, final int y, final int clickCount) { // Koordinaten finden Dimension tempD = searchMiniMid(x, y); // Sicht auf Mitte davon setzen rgi.rogGraphics.jumpTo(tempD.width - (viewX / 2), tempD.height - (viewY / 2)); } public void klickedOnMiniMap(int x, int y) { // Koordinaten finden Dimension tempD = searchMiniMid(x, y); // Sicht auf Mitte davon setzen rgi.rogGraphics.jumpTo(tempD.width - (viewX / 2), tempD.height - (viewY / 2)); } */ public int getModi() { // liefert den aktuellen renderModus zurück return modi; } public void calcColoredMaps(Color[] colors) { // Berechnet die eingefärbten Texturen ArrayList<GraphicsImage> tList = new ArrayList<GraphicsImage>(); tList.addAll(coloredImgMap.values()); for (int i = 0; i < tList.size(); i++) { Image im = tList.get(i).getImage(); for (int playerId = 0; playerId < colors.length; playerId++) { ImageBuffer preImg = new ImageBuffer(im.getWidth(), im.getHeight()); for (int x = 0; x < im.getWidth(); x++) { for (int y = 0; y < im.getHeight(); y++) { // Das ganze Raster durchgehen und Farben ersetzen // Ersetzfarbe da? Color col = im.getColor(x, y); //int rgb = im.getRGB(x, y); //float[] col = Color.RGBtoHSB((rgb >> 16) & 0xff, (rgb >> 8) & 0xff, rgb & 0xff, null); float[] hsb = java.awt.Color.RGBtoHSB(col.getRed(), col.getGreen(), col.getBlue(), null); if (hsb[0] >= 0.8583333f && hsb[0] <= 0.8666666f) { // Ja, ersetzen Color tc = colors[playerId]; preImg.setRGBA(x, y, tc.getRed(), tc.getGreen(), tc.getBlue(), col.getAlpha()); } else { preImg.setRGBA(x, y, col.getRed(), col.getGreen(), col.getBlue(), col.getAlpha()); } } } // Bild berechnet, einfügen GraphicsImage newImg = new GraphicsImage(preImg.getImage()); newImg.setImageName(tList.get(i).getImageName()); imgMap.put(newImg.getImageName() + playerId, newImg); } } } public void setColModeImage(GraphicsImage img) { colModeImage = img; Image temp = img.getImage(); // BufferedImage tempNew = new BufferedImage(); } public void enableAntialising() { // Schaltet die Kantenglättung an useAntialising = true; } /** * Die Updates des FoW dürfen nicht während der Bildberechnung sein, sonst flackert es. */ private void updateBuildingFoW() { // clearFogOfWar(); // for (int i = 0; i < buildingList.size(); i++) { // Building b = buildingList.get(i); // // FoW berechnen // if (b.getPlayerId() == rgi.game.getOwnPlayer().playerId || rgi.game.shareSight(b, rgi.game.getOwnPlayer())) { // cutSight(b); // } // } } public void buildingsChanged() { // FoW updaten updateBuildingsFow = true; } private void cutSight(Building b) { // Mitte berechnen int x = (int) (b.getMainPosition().getX() + ((b.getZ1() + b.getZ2() - 2) * 1.0 / 2)); int y = b.getMainPosition().getY(); // Diese Position als Startfeld überhaupt zulässig? if ((x + y) % 2 == 1) { y++; } // Dieses Feld selber auch ausschneiden fowmap[x][y] = 2; cutCircleFast(b.getVisrange() + ((b.getZ1() + b.getZ2()) / 4), new Position(x, y), true); } /** * Setzt den Fow-Sichtlayer von sterbenden Einheitn auf Unit, damit die Gegend beim nächsten Update auf erkundet gesetzt werden kann. * @param b */ public void cutDieingBuildingSight(Building b) { // // Mitte berechnen // int x = (int) (b.getMainPosition().getX() + ((b.getZ1() + b.getZ2() - 2) * 1.0 / 2)); // int y = b.getMainPosition().getY(); // // Diese Position als Startfeld überhaupt zulässig? // if (((int) x + (int) y) % 2 == 1) { // y++; // } // // Dieses Feld selber auch ausschneiden // fowmap[x][y] = 3; // // Schablone holen // boolean[][] pattern = fowpatmgr.getPattern(b.getVisrange() + ((b.getZ1() + b.getZ2()) / 4)); // // Schablone anwenden // int sx = x - 40; // int sy = y - 40; // for (int x2 = 0; x2 < 80; x2++) { // for (int y2 = 0; y2 < 80; y2++) { // if (pattern[x2][y2]) { // try { // fowmap[sx + x2][sy + y2] = 3; // } catch (ArrayIndexOutOfBoundsException ex) { // // Nix tun, ein Kreis kann ja den Maprand schneiden, da gibts natürlich dann kein FoW-Raster... // } // } // } // } } private void cutSight(Unit unit) { // Mitte berechnen int x = unit.getMainPosition().getX(); int y = unit.getMainPosition().getY(); // Dieses Feld selber auch ausschneiden byte val = fowmap[x][y]; if (val == 0 || val == 1) { fowmap[x][y] = 3; } cutCircleFast(unit.getVisrange(), unit.getMainPosition(), false); } /** * Schneidet schnell Kreise in den FoW. * Funktioniert NUR mit Ranges von 1-20!!!, weil schablonenbasiert * @param range Sichtweite in ganzen Feldern (1-20) * @param origin Mitte * @param building Für Gebäude (true) oder Einheit (false) */ public void cutCircleFast(int range, Position origin, boolean building) { // // Schablone holen // boolean[][] pattern = fowpatmgr.getPattern(range); // // Schablone anwenden // int sx = origin.getX() - 40; // int sy = origin.getY() - 40; // for (int x = 0; x < 80; x++) { // for (int y = 0; y < 80; y++) { // if (pattern[x][y]) { // directCut(sx + x, sy + y, !building); // } // } // } } private void directCut(int X, int Y, boolean checkUp) { if (!checkUp) { try { fowmap[X][Y] = 2; } catch (ArrayIndexOutOfBoundsException ex) { } } else { try { byte val2 = fowmap[X][Y]; if (val2 == 0 || val2 == 1) { // Wenn unerforscht oder vergessen fowmap[X][Y] = 3; } } catch (ArrayIndexOutOfBoundsException ex) { } } } /** * Muss regelmäßig vom Grafikmodul aufgerufen werden (4 mal pro Sekunde oder so) * Aktualisiert die gesamte FoW-Map auf Einheiten-Sichtweiten */ public void calcFogOfWar() { // // Zuerst alles mal von Einheiten gesehene vergessen // for (int x = 0; x < fowmap.length; x++) { // for (int y = 0; y < fowmap[0].length; y++) { // byte v = fowmap[x][y]; // if (fowmap[x][y] == 3) { // fowmap[x][y] = 1; // } // // } // } // // Für alle Einheiten auf der Map // int ownPlayerId = rgi.game.getOwnPlayer().playerId; // for (int i = 0; i < unitList.size(); i++) { // Unit unit = unitList.get(i); // if (unit.getPlayerId() != ownPlayerId && !rgi.game.shareSight(unit, rgi.game.getOwnPlayer())) { // // Nur eigene Einheiten decken den Nebel des Krieges auf // continue; // } // cutSight(unit); // } } public void appendCoreInner(ClientCore.InnerClient inner) { rgi = inner; } public GraphicsContent() { super("Centuries of Rage HD (pre-Alpha)"); coloredImgMap = new HashMap<String, GraphicsImage>(); overlays = new ArrayList<Overlay>(); skyEffects = new ArrayList<SkyEffect>(); fowpatmgr = new GraphicsFogOfWarPattern(); allListLock = new ReentrantLock(); } public void repaint() { /* if (parent != null && parent.slickReady && initState == 0) { try { // this.render(parent, parent.getGraphics()); } catch (SlickException ex) { ex.printStackTrace(); } } */ } @Override public void init(GameContainer container) throws SlickException { parent = (CoreGraphics) container; parent.loadSplash(); parent.slickReady = true; parent.setAlwaysRender(true); parent.setVerbose(false); } @Override public void update(GameContainer container, int delta) throws SlickException { if (initRun != null) { // Update Input-System parent.inputM.updateIGEs(); } } @Override public void render(GameContainer container, Graphics g) throws SlickException { if (initState == -1) { System.out.println("Displaying Splash..."); this.paintComponent(g); return; } else if (initState == 12) { // Komponenten fürs Hauptmenu laden System.out.println("Preloading some components..."); parent.loadPreMain(); System.out.println("Initialising menu..."); parent.initMainMenu(); System.out.println("Initialising input..."); parent.initInput(); System.out.println("Initialisation done."); initState = 13; } else if (initState == 13) { // Hauptmenu parent.renderMainMenu(container, g); } else if (initState == 1) { setVisibleArea((realPixX / FIELD_HALF_X), (int) (realPixY / FIELD_HALF_Y)); modi = -1; // Logo setzen String[] ab = {"img/game/logo_128x128.png", "img/game/logo_32x32.png", "img/game/logo_16x16.png"}; try { parent.setIcons(ab); } catch (SlickException ex) { System.out.println("ERROR: Failed to load game Icons!"); rgi.logger("ERROR: Failed to load game Icons!"); } // Einmal vorrendern this.paintComponent(g); org.newdawn.slick.opengl.renderer.Renderer.get().flush(); Display.update(); parent.initModule(); rgi.chat.init((int) (0.5 * realPixX), (int) (0.3 * realPixY)); rgi.teamSel.setFont(rgi.chat.getFont()); overlays.add(rgi.teamSel); try { fireMan = new GraphicsFireManager(new Image("img/particles/simple.tga", true), rgi); } catch (Exception ex) { rgi.logger("Can't load particle img/particles/simple.tga"); } if ("true".equals(rgi.configs.get("graphicsDebug"))) { graphicsDebug = true; int framerate; try { framerate = Integer.parseInt((String) rgi.configs.get("framerate")); } catch (NumberFormatException ex) { // Nicht da, default von 35 nehmen framerate = 35; } analyser = new GraphicsTimeAnalyser(framerate); overlays.add(analyser); } initState = 0; // LOAD abgeschlossen, dem Server mitteilen rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 7, 0, 0, 0, 0)); } else if (initState == 3) { parent.startRendering(); initState = 0; } else if (initState == 4) { // FinalPrepare parent.finalPrepare(); minimap = Minimap.createMinimap(visMap, imgMap, realPixX, realPixY, rgi); minimap.setAllList(allList); //ingamemenu = new IngameMenu(realPixX, realPixY); resourcecounter = new ResourceCounter(); overlays.add(minimap); //overlays.add(ingamemenu); overlays.add(resourcecounter); // Fertig - dem Server schicken rgi.rogGraphics.triggerStatusWaiting(); rgi.netctrl.broadcastDATA(rgi.packetFactory((byte) 3, 0, 0, 0, 0)); initState = 0; } if (initRun != null) { parent.renderAndCalc(container, g); } else { this.paintComponent(g); } //this.paintComponent(g); if (buildingsChanged) { this.buildingsChanged(); buildingsChanged = false; } if (epocheChanged) { epocheChanged = false; } //parent.slickReady = true; } //@Override @Override public void mouseDragged(int arg0, int arg1, int arg2, int arg3) { } //@Override @Override public void inputStarted() { } }
tfg13/Centuries-of-Rage
src/de/_13ducks/cor/graphics/GraphicsContent.java
214,355
/** */ package de.urszeidler.eclipse.shr5; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.eclipse.emf.common.util.Enumerator; /** * <!-- begin-user-doc --> * A representation of the literals of the enumeration '<em><b>Zauber Dauer</b></em>', * and utility methods for working with them. * <!-- end-user-doc --> * @see de.urszeidler.eclipse.shr5.Shr5Package#getZauberDauer() * @model * @generated */ public enum ZauberDauer implements Enumerator { /** * The '<em><b>Sofort</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #SOFORT_VALUE * @generated * @ordered */ SOFORT(0, "Sofort", "Sofort"), /** * The '<em><b>Aufrechterhalten</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #AUFRECHTERHALTEN_VALUE * @generated * @ordered */ AUFRECHTERHALTEN(1, "Aufrechterhalten", "Aufrechterhalten"), /** * The '<em><b>Permanent</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #PERMANENT_VALUE * @generated * @ordered */ PERMANENT(2, "Permanent", "Permanent"); /** * The '<em><b>Sofort</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Sofort</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #SOFORT * @model name="Sofort" * @generated * @ordered */ public static final int SOFORT_VALUE = 0; /** * The '<em><b>Aufrechterhalten</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Aufrechterhalten</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #AUFRECHTERHALTEN * @model name="Aufrechterhalten" * @generated * @ordered */ public static final int AUFRECHTERHALTEN_VALUE = 1; /** * The '<em><b>Permanent</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Permanent</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #PERMANENT * @model name="Permanent" * @generated * @ordered */ public static final int PERMANENT_VALUE = 2; /** * An array of all the '<em><b>Zauber Dauer</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private static final ZauberDauer[] VALUES_ARRAY = new ZauberDauer[] { SOFORT, AUFRECHTERHALTEN, PERMANENT, }; /** * A public read-only list of all the '<em><b>Zauber Dauer</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static final List<ZauberDauer> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY)); /** * Returns the '<em><b>Zauber Dauer</b></em>' literal with the specified literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static ZauberDauer get(String literal) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { ZauberDauer result = VALUES_ARRAY[i]; if (result.toString().equals(literal)) { return result; } } return null; } /** * Returns the '<em><b>Zauber Dauer</b></em>' literal with the specified name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static ZauberDauer getByName(String name) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { ZauberDauer result = VALUES_ARRAY[i]; if (result.getName().equals(name)) { return result; } } return null; } /** * Returns the '<em><b>Zauber Dauer</b></em>' literal with the specified integer value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static ZauberDauer get(int value) { switch (value) { case SOFORT_VALUE: return SOFORT; case AUFRECHTERHALTEN_VALUE: return AUFRECHTERHALTEN; case PERMANENT_VALUE: return PERMANENT; } return null; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final int value; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final String name; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final String literal; /** * Only this class can construct instances. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private ZauberDauer(int value, String name, String literal) { this.value = value; this.name = name; this.literal = literal; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getValue() { return value; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getName() { return name; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getLiteral() { return literal; } /** * Returns the literal value of the enumerator, which is its string representation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { return literal; } } //ZauberDauer
UrsZeidler/shr5rcp
de.urszeidler.shr5.model/src/de/urszeidler/eclipse/shr5/ZauberDauer.java
214,356
/** */ package de.urszeidler.eclipse.shr5; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.eclipse.emf.common.util.Enumerator; /** * <!-- begin-user-doc --> * A representation of the literals of the enumeration '<em><b>Critter Dauer</b></em>', * and utility methods for working with them. * <!-- end-user-doc --> * @see de.urszeidler.eclipse.shr5.Shr5Package#getCritterDauer() * @model * @generated */ public enum CritterDauer implements Enumerator { /** * The '<em><b>Immer</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #IMMER_VALUE * @generated * @ordered */ IMMER(0, "immer", "immer"), /** * The '<em><b>Sofort</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #SOFORT_VALUE * @generated * @ordered */ SOFORT(1, "sofort", "sofort"), /** * The '<em><b>Aufrechterhalten</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #AUFRECHTERHALTEN_VALUE * @generated * @ordered */ AUFRECHTERHALTEN(2, "aufrechterhalten", "aufrechterhalten"), /** * The '<em><b>Permanent</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #PERMANENT_VALUE * @generated * @ordered */ PERMANENT(3, "permanent", "permanent"), /** * The '<em><b>Speziell</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #SPEZIELL_VALUE * @generated * @ordered */ SPEZIELL(4, "speziell", "speziell"); /** * The '<em><b>Immer</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Immer</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #IMMER * @model name="immer" * @generated * @ordered */ public static final int IMMER_VALUE = 0; /** * The '<em><b>Sofort</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Sofort</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #SOFORT * @model name="sofort" * @generated * @ordered */ public static final int SOFORT_VALUE = 1; /** * The '<em><b>Aufrechterhalten</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Aufrechterhalten</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #AUFRECHTERHALTEN * @model name="aufrechterhalten" * @generated * @ordered */ public static final int AUFRECHTERHALTEN_VALUE = 2; /** * The '<em><b>Permanent</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Permanent</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #PERMANENT * @model name="permanent" * @generated * @ordered */ public static final int PERMANENT_VALUE = 3; /** * The '<em><b>Speziell</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Speziell</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #SPEZIELL * @model name="speziell" * @generated * @ordered */ public static final int SPEZIELL_VALUE = 4; /** * An array of all the '<em><b>Critter Dauer</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private static final CritterDauer[] VALUES_ARRAY = new CritterDauer[] { IMMER, SOFORT, AUFRECHTERHALTEN, PERMANENT, SPEZIELL, }; /** * A public read-only list of all the '<em><b>Critter Dauer</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static final List<CritterDauer> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY)); /** * Returns the '<em><b>Critter Dauer</b></em>' literal with the specified literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static CritterDauer get(String literal) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { CritterDauer result = VALUES_ARRAY[i]; if (result.toString().equals(literal)) { return result; } } return null; } /** * Returns the '<em><b>Critter Dauer</b></em>' literal with the specified name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static CritterDauer getByName(String name) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { CritterDauer result = VALUES_ARRAY[i]; if (result.getName().equals(name)) { return result; } } return null; } /** * Returns the '<em><b>Critter Dauer</b></em>' literal with the specified integer value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static CritterDauer get(int value) { switch (value) { case IMMER_VALUE: return IMMER; case SOFORT_VALUE: return SOFORT; case AUFRECHTERHALTEN_VALUE: return AUFRECHTERHALTEN; case PERMANENT_VALUE: return PERMANENT; case SPEZIELL_VALUE: return SPEZIELL; } return null; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final int value; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final String name; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final String literal; /** * Only this class can construct instances. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private CritterDauer(int value, String name, String literal) { this.value = value; this.name = name; this.literal = literal; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public int getValue() { return value; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getName() { return name; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getLiteral() { return literal; } /** * Returns the literal value of the enumerator, which is its string representation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { return literal; } } //CritterDauer
UrsZeidler/shr5rcp
de.urszeidler.shr5.model/src/de/urszeidler/eclipse/shr5/CritterDauer.java
214,360
package com.voxeo.moho.media.dialect; import java.net.URI; import java.util.Map; import javax.media.mscontrol.MsControlException; import javax.media.mscontrol.Parameters; import javax.media.mscontrol.Qualifier; import javax.media.mscontrol.Value; import javax.media.mscontrol.mediagroup.RecorderEvent; import javax.media.mscontrol.mediagroup.signals.SignalDetectorEvent; import javax.media.mscontrol.networkconnection.NetworkConnection; import javax.media.mscontrol.resource.RTC; import javax.media.mscontrol.resource.ResourceEvent; import com.voxeo.moho.event.InputCompleteEvent.Cause; import com.voxeo.moho.media.BeepParameters; import com.voxeo.moho.media.EnergyParameters; import com.voxeo.moho.media.InputMode; import com.voxeo.moho.media.input.SignalGrammar.Signal; public class GenericDialect implements MediaDialect { @Override public void setBeepOnConferenceEnter(Parameters parameters, Boolean value) { } @Override public void setBeepOnConferenceExit(Parameters parameters, Boolean value) { } @Override public void setSpeechInputMode(Parameters parameters, InputMode value) { } @Override public void setSpeechLanguage(Parameters parameters, String value) { } @Override public void setSpeechTermChar(Parameters parameters, Character value) { } @Override public void setTextToSpeechVoice(Parameters parameters, String value) { } @Override public void setDtmfHotwordEnabled(Parameters parameters, Boolean value) { } @Override public void setDtmfTypeaheadEnabled(Parameters parameters, Boolean value) { } @Override public void setConfidence(Parameters parameters, float value) { } @Override public void setTextToSpeechLanguage(Parameters parameters, String value) { } @Override public void setSpeechIncompleteTimeout(Parameters parameters, long peechIncompleteTimeout) { } @Override public void setSpeechCompleteTimeout(Parameters parameters, long peechCompleteTimeout) { } @Override public void setMixerName(Parameters params, String name) { } @Override public void setCallRecordFileFormat(Parameters params, Value value) { } @Override public void setCallRecordAudioCodec(Parameters params, Value value) { } @Override public void startCallRecord(NetworkConnection nc, URI recordURI, RTC[] rtc, Parameters optargs, CallRecordListener listener) throws MsControlException { } @Override public void stopCallRecord(NetworkConnection nc) { } @Override public int getCallRecordDuration(ResourceEvent event) { // TODO Auto-generated method stub return 0; } @Override public void pauseCallRecord(NetworkConnection nc) { // TODO Auto-generated method stub } @Override public void resumeCallRecord(NetworkConnection nc) { // TODO Auto-generated method stub } @Override public boolean isPromptCompleteEvent(RecorderEvent event) { return false; } @Override public boolean isPromptCompleteEvent(SignalDetectorEvent event) { return false; } @Override public void enableRecorderPromptCompleteEvent(Parameters params, boolean enable) { } @Override public void enableDetectorPromptCompleteEvent(Parameters params, boolean enable) { } @Override public void setDtmfPassThrough(NetworkConnection nc, boolean passThrough) { } @Override public Map<String, String> getSISlots(SignalDetectorEvent event) { return null; } @Override public Value getSignalConstants(Signal signal) { return null; } @Override public void setAutoReset(Parameters params, boolean autoreset) { } @Override public void setEnergyParameters(Parameters params, EnergyParameters energy) { } @Override public void setBeepParameters(Parameters params, BeepParameters beep) { } @Override public Cause getInputCompleteEventCause(Qualifier qualifier) { return null; } @Override public void setIgnorePromptFailure(Parameters params, boolean ignore) { } }
voxeolabs/moho
moho-impl/src/main/java/com/voxeo/moho/media/dialect/GenericDialect.java
214,362
package alvinEditor; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.HashMap; import java.util.StringTokenizer; public class TechTermsHash { //public static void main(String[] args) throws FileNotFoundException { /*HashMap<String, String> hmap = buildHeap(); System.out.println(hmap.get("Touchpad".toLowerCase()));*/ //} /** * @return */ public static HashMap<String, String> buildHeap() { File file = new File("techData.txt"); HashMap<String, String> hmap = new HashMap<String, String>(); try (BufferedReader br = new BufferedReader(new FileReader(file))) { String line = ""; while ((line = br.readLine()) != null) { StringTokenizer st = new StringTokenizer(line, "@"); String key = st.nextToken(); // System.out.println(key); String value = st.nextToken().trim();// line.substring(key.length()+2);//substring(key.length()+2); //System.out.println(value); hmap.put(key, value); } } catch (IOException e) { System.out.println(e); } return hmap; } }
rohithvutnoor/EditNote
src/alvinEditor/TechTermsHash.java
214,364
package de.kekru.struktogrammeditor.struktogrammelemente; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.Rectangle; import java.util.ArrayList; import org.jdom.Element; import de.kekru.struktogrammeditor.other.JTextAreaEasy; public class StruktogrammElementListe extends ArrayList<StruktogrammElement> {//erbt von generischer ArrayList private static final long serialVersionUID = -122818269830027765L; private Rectangle bereich; private Graphics2D g; private String beschreibung = ""; //hier wird bei einer Fallauswahl und bei einer Verzweigung gespeichert, was über der jeweiligen Spalte stehen soll public StruktogrammElementListe(Graphics2D g){ super(); bereich = new Rectangle(); this.g = g; add(new LeerElement(g)); //Am Anfang kommt ein Leerelement in die Liste } public void setzeBeschreibung(String beschr){ beschreibung = beschr; } public String gibBeschreibung(){ return beschreibung; } public int gibAnzahlUnterelemente(){ return size(); } public void quellcodeAllerUnterelementeGenerieren(int typ, int anzahlEingerueckt, int anzahlEinzuruecken, boolean alsKommentar, JTextAreaEasy textarea){ for (int i=0; i < size(); i++){ get(i).quellcodeGenerieren(typ, anzahlEingerueckt, anzahlEinzuruecken, alsKommentar, textarea); } } public void schreibeXMLDatenAllerUnterElemente(Element parent){ //if (!(get(0) instanceof LeerElement)){//alle Struktogrammelemente, außer LeerElement, müssen XML-Daten schreiben for (int i=0; i < size(); i++){ get(i).schreibeXMLDaten(parent); } //} } private int gibTextbreite(String s){ return g != null ? (int) g.getFontMetrics().getStringBounds(s, g).getBounds().getWidth() : s.length() * 4;//http://www.tutorials.de/java/288641-textlaenge-pixel.html } public void alleZeichnen(){ for (int i=0; i < size(); i++){ get(i).zeichne(); } } public void graphicsAllerUnterlementeSetzen(Graphics2D g){ this.g = g; for (int i=0; i < size(); i++){ get(i).setzeGraphics(g); } } public boolean istUnterelement(StruktogrammElement eventuellesUnterelement){ for (int i=0; i < size(); i++){ if((get(i) == eventuellesUnterelement) || (get(i).istUnterelement(eventuellesUnterelement))){//wenn get(i) das Gesuchte ist, oder wenn get(i) das gesuchte Unterelement beinhaltet, wird true zurückgegeben return true; } } return false; } public void hinzufuegen(StruktogrammElement neues){//am Ende einfügen hinzufuegen(neues,null,true); } public void hinzufuegen(StruktogrammElement neues, StruktogrammElement naechstesOderVorheriges, boolean vorDemAltenEinfuegen){ ArrayList<StruktogrammElement> list = new ArrayList<StruktogrammElement>(); list.add(neues); hinzufuegen(list, naechstesOderVorheriges, vorDemAltenEinfuegen); } public void hinzufuegen(ArrayList<StruktogrammElement> neue, StruktogrammElement naechstesOderVorheriges, boolean vorDemAltenEinfuegen){ Object leeres = null; if (!isEmpty() && (get(0) instanceof LeerElement)){ leeres = get(0); //das LeerElement merken } if (naechstesOderVorheriges != null){ int position = indexOf(naechstesOderVorheriges); //Position des Elementes hinter oder vor dem das Neue eingefügt werden soll if (!vorDemAltenEinfuegen){//wenn nach dem alten Element eingefügt werden soll, wird die Position um 1 inkrementiert position++; } for(StruktogrammElement strElem : neue){ add(position, strElem);//Einfügen an der Stelle position; das Element, das vorher an dieser Position war, wird um eine Stelle weiter geschoben position++; } }else{ for(StruktogrammElement strElem : neue){ add(strElem); //Am Ende einfügen } } if (leeres != null){ remove(indexOf(leeres)); //das LeerElement entfernen } } public void entfernen(StruktogrammElement zuLoeschen){ remove(indexOf(zuLoeschen)); if (size() == 0){ add(new LeerElement(g)); //wenn die Liste jetzt leer ist, ein LeerElement einfügen } } public void alleEntfernen(){ clear(); add(new LeerElement(g)); } public Object gibElementAnPos(int x, int y, boolean nurListe){ if (bereich.contains(x,y)){ //Punkt ist innerhalb dieser Liste Object tmp; for (int i=0; i < size(); i++){ tmp = get(i).gibElementAnPos(x,y,nurListe); if (tmp != null){ return tmp; //das Listen-Element mit dem Index i beinhaltet den Punkt, dieses oder eines seiner Unterelemente wird zurückgegeben } } if (nurListe){ //es wurde noch kein Element zurückgegeben (auch keine weiter innere Liste), wenn also nach einer Liste gefragt ist... return this; //...wird diese zurückgeliefert } } return null; //Punkt ist nicht innerhalb dieser Liste } public StruktogrammElementListe gibListeDieDasElementHat(StruktogrammElement element){ StruktogrammElementListe tmp; for (int i=0; i < size(); i++){ if(get(i) == element){ return this; //ich habe das Element }else{ tmp = get(i).gibListeDieDasElementHat(element); if (tmp != null){ return tmp; //eine der Listen meiner Unterelemente hat das Element } } } return null; //ich und auch keine meiner Unterelemente hat das gesucht Element } //gibt die Breite des breitesten Unterelementes und die addierte Höhe aller Unterelemente an public Dimension gibDimensionDerUnterelemente(){ int breite = 0; int hoehe = 0; Rectangle rect; for (int i=0; i < size(); i++){ rect = get(i).gibRectangle(); if (rect.width > breite){ breite = rect.width; } hoehe += rect.height; } return new Dimension(breite, hoehe); } public void xPosAllerUnterelementeSetzen(int x){ for (int i=0; i < size(); i++){ get(i).setzeXPos(x); } bereich.x = x; } public void breiteDerUnterelementeSetzen(int neueBreite){ for (int i=0; i < size(); i++){ get(i).setzeBreite(neueBreite); } bereich.width = neueBreite; } public void gesamtHoeheSetzen(int neueHoehe){//Höhe des letzten Elementes wird verändert if(size() > 0){ int hoeheVorher = get(size() -1).gibHoehe(); //Höhe des letzten Elementes ermitteln get(size() -1).setzeHoehe(neueHoehe - (bereich.height - hoeheVorher)); //neue Höhe des letzten Elementes setzen } bereich.height = neueHoehe; } public Rectangle zeichenbereichAllerElementeAktualisieren(int x, int y){ int neueYPos = y; for (int i = 0; i < size(); i++){ neueYPos += get(i).zeichenbereichAktualisieren(x,neueYPos).getHeight();//Zeichenbereich von Element get(i) wird aktualisiert mit den Koordinaten x und neueYPos; neueYPos wird dabei für das nächste Element um die Höhe des aktuellen Elementes vergrößert } Dimension dim = gibDimensionDerUnterelemente();//größte Breite eines Unterlementes und Gesamthöhe aller Unterelemente if (dim.width < gibTextbreite(gibBeschreibung() +8)){//Beschreibung ist bei Verzweigung und Fallauswahl kein leerer String (wird gesetzt in setzeFaelle(...) durch den EingabeDialog) dim.width = gibTextbreite(gibBeschreibung()) +8; } breiteDerUnterelementeSetzen(dim.width);//alle Unterelemente auf die gleiche Breite bringen bereich.setSize(dim); bereich.setLocation(x,y); return bereich; } public int gibBreite(){ return bereich.width; } public int gibHoehe(){ return bereich.height; } public int gibRechterRand(){ return bereich.x + bereich.width; } public int gibX(){ return bereich.x; } public void zoomsAllerElementeZuruecksetzen(){ for(int i=0; i < size(); i++){ get(i).zoomsZuruecksetzen(); } } }
kekru/struktogrammeditor
src/main/java/de/kekru/struktogrammeditor/struktogrammelemente/StruktogrammElementListe.java
214,365
import javax.swing.*; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.lang.reflect.InvocationTargetException; import java.util.Collections; public class Controller implements MouseListener { private Game _game; private MainFrame _mainFrame; private boolean _isHumanPlayersTurn; public void initController(Game game, MainFrame mainFrame) { _game = game; _mainFrame = mainFrame; } /** * Event das die Ereignisse zum Karten legen und ziehen des menschlichen Spielers verarbeitet * @param mouseEvent */ @Override public void mouseClicked(MouseEvent mouseEvent) { System.out.println("Ist EDT?: " + SwingUtilities.isEventDispatchThread()); boolean repaint = false; // Unterscheiden ob Karte Ziehen oder Karte legen // Karte ziehen if (mouseEvent.getSource() instanceof DrawButton) { if (_isHumanPlayersTurn) { drawCard(_game.actualPlayer); _isHumanPlayersTurn = false; repaint = true; // spielt eine Runde mittels SwingWorker new PlayRoundWorker(this).execute(); } else { for (Player humanPlayer : _game.players) { if (humanPlayer instanceof RealPlayer) { drawCard(humanPlayer); _mainFrame.repaintPlayerCards(humanPlayer.cardsOnHand); _mainFrame.setVisible(true); repaint = false; } } } } // Karte legen else if (mouseEvent.getSource() instanceof PlayerCardButton) { PlayerCardButton playerCardButton = (PlayerCardButton) mouseEvent.getSource(); UnoCard unoCard = playerCardButton.get_unoCard(); // if (_game.actualPlayer instanceof RealPlayer) { if (realPlay(unoCard, (RealPlayer) _game.actualPlayer)) { _isHumanPlayersTurn = false; repaint = true; // Eine Runde mittels SwingWorker spielen new PlayRoundWorker(this).execute(); } // } // Zwischenwerfen einer Karte, wenn man nicht dran ist // else { // // for (Player humanPlayer : _game.players) { // // if (humanPlayer instanceof RealPlayer) { // // if (realPlay(unoCard, (RealPlayer) humanPlayer)) { // // _mainFrame.repaintPlayerCards(humanPlayer.cardsOnHand); // _mainFrame.setVisible(true); // repaint = false; // } // } // } // } } if (repaint) { _mainFrame.repaintPlayerCards(_game.actualPlayer.cardsOnHand); _mainFrame.setVisible(true); } } /** * Auspielen einer Karte durch einen realen Spieler * * @param cardToPlay Karte die ausgespielt werden soll * @param rPlayer Spieler Objekt des menschlichen Spielers * @return Gibt an ob der Zug gelunge ist. Also ob die Karte auf der Hand ist und auf die liegende passt */ private boolean realPlay(UnoCard cardToPlay, RealPlayer rPlayer) { // wird true, wenn die Karte passt boolean validPlay = false; System.out.println("Zu spielende Karte: " + cardToPlay.get_color() + ", " + cardToPlay.get_number()); boolean isOnHand = false; for (UnoCard c : rPlayer.cardsOnHand) { if (cardToPlay.equals(c)) { cardToPlay = c; isOnHand = true; } } if (isOnHand) { System.out.println("Auf Hand"); if (_game.actualCard.fits(cardToPlay)) { System.out.println("Karte passt"); _game.actualCard = cardToPlay; _mainFrame.refreshStack(_game.actualCard); _game.cardStack.add(_game.actualCard); rPlayer.cardsOnHand.remove(cardToPlay); System.out.println("Nach Kartenlegen: " + _game.actualPlayer.cardsOnHand.size() + " Karten"); for (UnoCard c : _game.actualPlayer.cardsOnHand) { System.out.println(c.get_color() + ", " + c.get_number()); } System.out.println("Noch " + _game.cardDeck.size() + " Karten auf Deck"); System.out.println("Bereits " + _game.cardStack.size() + " Karten auf Haufen"); System.out.println(); validPlay = true; } else { validPlay = false; System.out.println("Karte passt nicht. Bitte wählen Sie erneut oder Ziehen Sie eine Karte"); } } return validPlay; } /** * Auspielen einer Karte durch einen virtuellen Spieler * * @param vPlayer */ private void virtualPlay(final VirtualPlayer vPlayer) { boolean cardFits = false; for (final UnoCard c : vPlayer.cardsOnHand) { if (_game.actualCard.fits(c)) { _game.actualCard = c; final String protocol = vPlayer.get_name() + " spielt: " + c.get_color() + ", " + c.get_number(); Runnable runnable = new Runnable() { @Override public void run() { _mainFrame.refreshStack(_game.actualCard); _mainFrame.writeToProtocol(protocol); } }; SwingUtilities.invokeLater(runnable); _game.cardStack.add(_game.actualCard); vPlayer.cardsOnHand.remove(_game.actualCard); cardFits = true; System.out.println(vPlayer.get_name() + " spielt: " + c.get_color() + ", " + c.get_number()); break; } } if (cardFits == false) { drawCard(vPlayer); } } /** * Karte ziehen */ private void drawCard(Player drawingPlayer) { if (_game.cardDeck.size() < 1) { for (int i = 0; i < _game.cardStack.size(); i++) { _game.cardDeck.add(_game.cardStack.get(i)); } _game.cardStack.clear(); Collections.shuffle(_game.cardDeck); } final String protocol = drawingPlayer.get_name() + " hat gezogen"; // hier eine coole Syntax für das schreiben eines runnable, die intelliJ vorgeschlagen hat Runnable runnable = new Runnable() { @Override public void run() { _mainFrame.writeToProtocol(protocol); } }; SwingUtilities.invokeLater(runnable); UnoCard drawedCard = _game.cardDeck.get(0); drawingPlayer.cardsOnHand.add(drawedCard); _game.cardDeck.remove(drawedCard); } /** * Spielen einer Runde, wenn der menschliche Spieler dran ist wird aus der Methode gesprungen */ public void playRound() { // Spiele eine Runde for (int position = 0; position < _game.players.size(); position++) { _game.actualPlayer = _game.players.get(position); System.out.print("Liegende Karte: "); System.out.println(_game.actualCard.get_color() + ", " + _game.actualCard.get_number()); System.out.print("Spieler: "); System.out.println(_game.actualPlayer.get_name()); final String protocol; if(_game.actualPlayer instanceof VirtualPlayer){ protocol = _game.actualPlayer.get_name() + " ist am Zug.\n" + _game.actualPlayer.get_name() + " hat " + _game.actualPlayer.cardsOnHand.size() + " Karten."; } else{ protocol = "Du bist am Zug.\n"; } try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { _mainFrame.writeToProtocol(protocol); } }); } catch (InterruptedException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } // Pause, wenn bei den nicht-menschlichen Spielern if (_game.actualPlayer instanceof VirtualPlayer){ insertDelay(800); } if (_game.actualPlayer.cardsOnHand.size() < 2 && _game.actualPlayer.cardsOnHand.size() > 0) { try { SwingUtilities.invokeAndWait(new Runnable() { @Override public void run() { _mainFrame.writeToProtocol("UNO!!!"); } }); } catch (InterruptedException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } System.out.println("UNO!!!!"); } if (_game.actualPlayer.cardsOnHand.size() < 1) { System.out.println("GEWONNEN!!!!!!!!!"); String message = _game.actualPlayer.get_name(); message += " hat gewonnen!"; _mainFrame.Message(message); return; } System.out.println("Vor Kartenlegen: " + _game.actualPlayer.cardsOnHand.size() + " Karten"); for (UnoCard c : _game.actualPlayer.cardsOnHand) { System.out.println(c.get_color() + ", " + c.get_number()); } if (_game.actualPlayer instanceof VirtualPlayer) { virtualPlay((VirtualPlayer) _game.actualPlayer); } // bricht hier ab wenn es ein echter Spieler ist und wartet auf das Event else if (_game.actualPlayer instanceof RealPlayer) { _isHumanPlayersTurn = true; return; } System.out.println("Nach Kartenlegen: " + _game.actualPlayer.cardsOnHand.size() + " Karten"); for (UnoCard c : _game.actualPlayer.cardsOnHand) { System.out.println(c.get_color() + ", " + c.get_number()); } System.out.println("Noch " + _game.cardDeck.size() + " Karten auf Deck"); System.out.println("Bereits " + _game.cardStack.size() + " Karten auf Haufen"); System.out.println(); } } /** * Fügt eine Verzögerung in den Spielverlauf ein, die einen Zug eines virtuellen Spielers simuliert * * @param milliseconds Zeit in Millisekunden, die die Pause dauern soll */ private void insertDelay(long milliseconds) { try { Thread.sleep(milliseconds); } catch (InterruptedException e) { e.printStackTrace(); } } public void CreateCards() { // zwei Sätze Karten werden erstellt mit je 4 Farben und Zahlen 0 - 9 for (int h = 0; h < 2; h++) { for (int i = 1; i < 10; i++) { _game.cardDeck.add(new UnoCard(i, "blue")); } for (int i = 1; i < 10; i++) { _game.cardDeck.add(new UnoCard(i, "red")); } for (int i = 1; i < 10; i++) { _game.cardDeck.add(new UnoCard(i, "green")); } for (int i = 1; i < 10; i++) { _game.cardDeck.add(new UnoCard(i, "yellow")); } } _game.cardDeck.add(new UnoCard(0, "blue")); _game.cardDeck.add(new UnoCard(0, "red")); _game.cardDeck.add(new UnoCard(0, "green")); _game.cardDeck.add(new UnoCard(0, "yellow")); } public void uncoverFirstCard() { _game.actualCard = _game.cardDeck.get(0); _game.cardStack.add(_game.cardDeck.get(0)); _game.cardDeck.remove(0); _mainFrame.refreshStack(_game.actualCard); } public void DealCards() { for (Player p : _game.players) { for (int i = 0; i < 7; i++) { p.cardsOnHand.add(_game.cardDeck.get(0)); _game.cardDeck.remove(0); } } } @Override public void mousePressed(MouseEvent mouseEvent) { } @Override public void mouseReleased(MouseEvent mouseEvent) { } @Override public void mouseEntered(MouseEvent mouseEvent) { } @Override public void mouseExited(MouseEvent mouseEvent) { } }
EnJoIsKaTe/ProjectBA
Uno/src/Controller.java
214,369
/* * 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.graphics; import de._13ducks.cor.game.client.ClientCore; import java.util.ArrayList; import org.newdawn.slick.*; /** * Diese Klasse repräsentiert den Chat, mit dem Spieler chatten können, und mit dem Spielrelevante infos Angezeigt werden * * Die größe des Chatfensters wird einmalig beim Init übergeben. Der Chat passt dann seine Schriftgröße automatisch an * * @author tfg */ public class ClientChat implements Overlay { /** * Der normale, nicht aktivierte Modus. Nur die aktiven Nachrichten werden angezeigt. */ private static final int NORMAL_MODE = 1; /** * Der Eingabemodus. Das gesamte Chatfenster wird angezeigt, mit History. Derzeit gibt es keinen seperaten Team-Eingabemodus, da es noch keine Teams gibt */ private static final int ENTER_MODE = 2; /** * Konfigurations-Parameter * Gibt die maximale Anzahl dargestellter Zeilen an. (Für die History-Ansicht) * Bestimmt die Schriftgröße mit, sollte also nicht zu hoch eingstellt werden - dafür gibts ja die historyFunktion */ private final int LINES = 10; /** * Konfigurations-Parameter * Gibt an, wie lange eine Chatnachricht aktuell bleibt, bevor sie ausgeblendet wird * Gilt natürlich nicht für ENTER und HISTORY-Modes */ private final int UPTIME = 20000; /** * Konfig-Parameter. * Hintergrundfarbe des Chatfensters. */ private final Color COL_BACKGROUND = new org.newdawn.slick.Color(65, 65, 65, 160); /** * Konfig-Parameter. * Farbe der Grenzlinie des Chatfensters. */ private final Color COL_BACKGROUND2 = Color.black; /** * Konfig-Parameter. * Farbe des Hintergrunds des Content- und Eingabebereichs */ private final Color COL_CONTENT_AREA = new org.newdawn.slick.Color(50, 50, 50, 160); /** * Konfig-Parameter. * */ private final Color COL_TEXT = new org.newdawn.slick.Color(255, 255, 200); /** * Wie vieldes Fensters sind NICHT echter Inhalt. * Bedingt unter anderem die Rundung des Chatfensters, da diese den freien Bereich bedingt * Bezieht sich auf die Y-Größe */ private final float WINDOW_OVER_CONTENT = 0.05f; /** * Wieviel des Contents sind Trennbereicht zwischen Eingabe und History */ private final float GAP_OVER_CONTENT = 0.05f; /** * Bestimmt die Schriftgröße im Verhältniss zum vorhandenen Platz */ private final float FONTSIZE_OVER_LINESIZE = 0.8f; /** * Der Gesamte Inhalt des Chats. Wird eventuell irgendwann gekürzt (z.B. ab 1000 Zeilen), sollte aber schon ne Weile halten. */ private ArrayList<ChatLine> chatHistory; /** * Der aktuelle Modus. Es gibt: * 1 (ClientChat.NORMAL_MODE) - Nur aktuelle Nachrichten, kein Inhalt * 2 (ClientChat.ENTER_MODE) - Eingabemodus, mit History */ private int mode = ClientChat.NORMAL_MODE; /** * Die X-Größe des Chatfensters in Pixel */ private int pxlX; /** * Die Y-Größe des Chatfensters in Pixel */ private int pxlY; /** * Gesamter Content-Bereich */ private int intPxlX; /** * Gesamter Content-Bereich */ private int intPxlY; /** * History-Bereich */ private int hPxlY; /** * Enter-Bereich */ private int ePxlY; /** * Abstand vom Rahmen zum Content in Pixeln */ private int intgap; /** * Abstand von der Eingabe zur History in Pixeln */ private int intgapCH; /** * Abstand von der Schrift zu ihrem Feld. Die Schrift muss mittig sein. */ private int ilgap; /** * Die Scrollposition in der History-Ansicht */ private int scroll = 0; /** * Die Schrift des Chats. Die Größe wird selbstständig angepasst (beim init) */ private UnicodeFont font; /** * Was derzeit eingegeben wird */ private String enter = ""; /** * Bei langen Nachrichten verschiebt sich die Ansicht des Chats. * Hier wird gespeichert wie weit */ private int overSizeOffset; /** * Das Timing für den blinkenden Cursor */ private long cursorBlink = System.currentTimeMillis(); /** * Die Referenz auf alle Module. * Wird z.B. zum Abspielen von Sounds benötigt. */ ClientCore.InnerClient rgi; /** * Der normale Konstruktor. * Der Chat muss danach noch initialisiert (ClientChat.init()) werden, bevor er verwendet werden kann, dies geschieht normalerweise durch die Init-Routine des Game-Moduls. * @param rgi */ public ClientChat(ClientCore.InnerClient inner) { rgi = inner; } /** * Initialisiert den Chat. * Läd Schriften, braucht daher eventuell ein bisschen. * * Die hier übergebene Größe des Chats darf später nichtmehr geändert werden! * @param sizeX Die zukünftige Größe des Chats * @param sizeY Die zukünftige Größe des Chats */ public void init(int sizeX, int sizeY) { pxlX = sizeX; pxlY = sizeY; intgap = (int) (1.0 * pxlY * WINDOW_OVER_CONTENT); intPxlX = pxlX - (2 * intgap); intPxlY = pxlY - (2 * intgap); intgapCH = (int) (1.0 * pxlY * GAP_OVER_CONTENT); hPxlY = (int) (1.0 * (intPxlY - intgapCH) / LINES * (LINES - 1)); ePxlY = (int) (1.0 * (intPxlY - intgapCH) / LINES); // Die Schrift initialisieren // Ziel-Größe bestimmen int fontsize = (int) (1.0 * ePxlY * FONTSIZE_OVER_LINESIZE); font = new org.newdawn.slick.UnicodeFont(java.awt.Font.decode("Sans-" + fontsize)); font.addAsciiGlyphs(); font.getEffects().add(new org.newdawn.slick.font.effects.ShadowEffect(java.awt.Color.BLACK, 1, 1, 1.0f)); font.getEffects().add(new org.newdawn.slick.font.effects.ColorEffect(new java.awt.Color(255, 255, 200))); try { font.loadGlyphs(); } catch (SlickException ex) { } ilgap = (ePxlY - fontsize) / 2; chatHistory = new ArrayList<ChatLine>(); } /** * Liefert die Nachrichten, die derzeit angezeigt werden soll. * Regelt Timing für NORMAL_MODE automatisch * Berücksichtigt auch die eingestellte Zeilenzahl * @return */ private ChatLine[] getMessages() { ChatLine[] lines = new ChatLine[LINES - 1]; int aline = LINES - 2; for (int i = chatHistory.size() - 1 - scroll; i >= 0 && i > chatHistory.size() - LINES - scroll; i--) { // Müssen wir auf aktualität achten if (mode == ClientChat.NORMAL_MODE) { // Noch aktuell? ChatLine line = chatHistory.get(i); if (System.currentTimeMillis() - line.getMsgTime() < UPTIME) { // Ist noch aktuell, also verwenden lines[aline] = line; aline--; if (aline < 0) { // Zuteilung fertig return lines; } } else { // Nichtmehr aktuell, also abbrechen return lines; } } else { // Aktualität egal ChatLine line = chatHistory.get(i); lines[aline] = line; aline--; if (aline < 0) { // Zuteilung fertig return lines; } } } return lines; } /** * Zeichnet den Chat auf den Bildschirm/Buffer (wird auf g2 gezeichnet) * Der Chat entscheidet selbstständig, was gezeichnet wird (nur aktives (rahmenlos), hisory, eingabemaske etc.) * Der Chat belegt maximal den Platz von chatX bis chatSizeX und chatY bis chatSizeY, je nach Modus aber auch weniger. * * @param g2 * @param chatX X-Koordinate des Chatfensters (das nicht immer gezeinet wird) * @param chatY Y-Koordinate des Chatfensters (das nicht immer gezeinet wird) */ private void renderChat(Graphics g2, int chatX, int chatY) { // Der Chat zeigt immer die letzen paar Zeilen an, egal in welchem Modus. // Daher muss erst der eventuell vorhandene Hintergrund gezeichnet werden, und dann der Text if (mode == ClientChat.ENTER_MODE) { // Fenster g2.setColor(COL_BACKGROUND); g2.fillRoundRect(chatX, chatY, pxlX, pxlY, (int) (1.0 * pxlY * WINDOW_OVER_CONTENT)); // Rahmen g2.setColor(COL_BACKGROUND2); g2.drawRoundRect(chatX, chatY, pxlX, pxlY, (int) (1.0 * pxlY * WINDOW_OVER_CONTENT)); // InhaltsrahmenHistory (Inhalt und Linie) g2.setColor(COL_CONTENT_AREA); g2.fillRect(chatX + intgap, chatY + intgap, intPxlX, hPxlY); g2.setColor(COL_BACKGROUND2); g2.drawRect(chatX + intgap, chatY + intgap, intPxlX, hPxlY); // Inhaltsrahmen Enter (Inhalt und Linie) g2.setColor(COL_CONTENT_AREA); g2.fillRect(chatX + intgap, chatY + intgap + hPxlY + intgapCH, intPxlX, ePxlY); g2.setColor(COL_BACKGROUND2); g2.drawRect(chatX + intgap, chatY + intgap + hPxlY + intgapCH, intPxlX, ePxlY); } // Jetzt die vorhandenen Nachrichten anzeigen - aber die Menge kann unterschiedlich sein, je nach dem ob eingeblendet oder nicht. if (mode == ClientChat.ENTER_MODE) { // Das Enter-Feld g2.setFont(font); g2.setColor(COL_TEXT); if (enter != null) { if (overSizeOffset <= 0) { g2.drawString(enter, chatX + intgap + 3, chatY + intgap + hPxlY + intgapCH + ilgap); } else { // Zu lang, was weglassen g2.drawString(enter.substring(overSizeOffset), chatX + intgap + 1, chatY + intgap + hPxlY + intgapCH + ilgap); } } // Cursor int cpos = 2; if (enter != null) { if (font.getWidth(enter) < intPxlX) { cpos = font.getWidth(enter) + 2; } else { // Cursor ans Ende setzen cpos = intPxlX - 5; } } // Blinken des Cursors abhandeln if (System.currentTimeMillis() - cursorBlink <= 375) { g2.drawLine(chatX + intgap + cpos, chatY + intgap + hPxlY + intgapCH + ilgap + 1, chatX + intgap + cpos, chatY + intgap + hPxlY + intgapCH + ilgap + (int) (1.0 * ePxlY * FONTSIZE_OVER_LINESIZE)); } else if (System.currentTimeMillis() - cursorBlink > 750) { cursorBlink = System.currentTimeMillis(); } } // Nachrichten rendern g2.setFont(font); ChatLine[] content = getMessages(); for (int i = 0; i < content.length; i++) { ChatLine line = content[i]; if (line != null) { // Rendern // Pre if (line.renderPre()) { g2.setColor(line.getPremessageColor()); g2.drawString(line.getPremessage(), chatX + intgap + 3, chatY + intgap + (ePxlY * i) + ilgap); } // Content g2.setColor(line.getMessageColor()); g2.drawString(": " + line.getMessage(), chatX + intgap + 10 + font.getWidth(line.getPremessage()), chatY + intgap + (ePxlY * i) + ilgap); } } } /** * Aufrufen, um den Chat zu aktivieren/deaktivieren * Sollte aufgerufen werden, wenn der Chat-Button gedrückt wird * Der Chat schält selbstständig den Chat-Inputmode für das Inputmodul um. */ public void toggleChat() { if (mode == ClientChat.NORMAL_MODE) { // Modus umschalten mode = ClientChat.ENTER_MODE; rgi.rogGraphics.inputM.chatMode = true; } else { mode = ClientChat.NORMAL_MODE; rgi.rogGraphics.inputM.chatMode = false; } } /** * Hiermit lassen sich Inputsignale an das Modul weiterleiten * ENTER als Bestätigen/Abschicken wird automatisch gefangen, damit wird der Inputmode auch automatisch beendet. * PFEILTASTEN HOCH und RUNTER werden automatisch zum Scrollen verwendet. * Wenn andere Tasten wie z.B. ESCAPE als Abbruch-Taste verwendet werden sollen, muss das vorher abgefangen werden. * @param key * @param c */ public void input(int key, char c) { if (key == Input.KEY_ENTER || key == Input.KEY_NUMPADENTER) { // Nachricht abschicken rgi.netctrl.broadcastString(enter, (byte) 44); // Zurücksetzen enter = ""; overSizeOffset = 0; // Eingabemodus abschalten toggleChat(); } else if (key == Input.KEY_BACK) { // Letztes Löschen, falls da if (enter.length() > 1) { enter = enter.substring(0, enter.length() - 1); recalcOSO(false); } else { enter = ""; overSizeOffset = 0; } } else if (key == Input.KEY_UP) { // Hochscrollen, falls möglich int maxScroll = chatHistory.size() - LINES; if (maxScroll > scroll) { scroll++; } } else if (key == Input.KEY_DOWN) { // Runterscrollen, falls möglich if (scroll > 0) { scroll--; } } else { if (!Character.isISOControl(c)) { enter = enter + c; recalcOSO(true); } } } /** * Berechnet die Verschiebung der Chateingabe für lange Texte neu */ private void recalcOSO(boolean added) { if (font.getWidth(enter) > intPxlX) { if (added) { int i = overSizeOffset; while (font.getWidth(enter.substring(i++)) > intPxlX) {} overSizeOffset = i - 1; } else { int i = overSizeOffset; while (font.getWidth(enter.substring(i--)) < intPxlX) {} overSizeOffset = i + 2; } } } /** * Fügt eine Nachricht zum Chat hinzu. * Neu ankommende Nachrichten sollten hiermit zum Chat geadded werden * Bereits hier wird die Nachricht umgebrochen, sofern das erforderlich sein sollte * @param msg Die Nachricht selber * @param playerId Die PlayerId der Herkunft. < 0 ist der Server */ public void addMessage(String msg, int playerId) { ChatLine line = null; if (playerId > 0) { String playername = rgi.game.getPlayer(playerId).nickName; Color playerCol = rgi.game.getPlayer(playerId).color; line = new ChatLine(msg, playername, playerCol); } else if (playerId == -1) { line = new ChatLine(msg, "(Server)", this.COL_TEXT); } else if (playerId == -2) { line = new ChatLine(msg, "(Game)", this.COL_TEXT); } if (!needsNL(line)) { // Ist so ok chatHistory.add(line); // Aktuelle Scrollposition soll behalten werden, also um 1 erhöhen if (scroll > 0) { scroll++; } } else { // Muss umgebrochen werden - also mach mer das ChatLine[] splitted = splitLine(line); // Alle adden for (ChatLine lline : splitted) { chatHistory.add(lline); if (scroll > 0) { scroll++; } } } } /** * Untersucht, ob ein Umbrechen des Textes notwendig ist * @param line */ private boolean needsNL(ChatLine line) { return (font.getWidth("i " + line.getPremessage() + ": " + line.getMessage()) > intPxlX); } /** * Bricht den Text um. * Liefert die Nachricht als mehrere Umgebrochene Zeilen zurück * Versucht schön umzubrechen - also zwischen Wörtern - * Notfalls wird aber auch im Wort unterbrochen * * Bricht auch mehrfach um, sollte das möglich sein * @param line * @return */ private ChatLine[] splitLine(ChatLine line) { // Wir gehen Wort für Wort durch und schauen nach welchem wir die maximale Länge überschreiten. // Sollte es schon nach dem ersten Wort der Zeile sein, wird dieses halt zerschnitten String total = line.getMessage(); int max = intPxlX - 15 - font.getWidth("i " + line.getPremessage() + ": i"); // String in Wörter splitten ArrayList<String> words = new ArrayList<String>(); while (total.contains(" ")) { // Solange noch leerzeichen, also neue Wörter da sind String word = total.substring(0, total.indexOf(" ") + 1); words.add(word); total = total.substring(total.indexOf(" ") + 1); } // Den Rest auch adden words.add(total); // Wortliste fertig. Jetzt erste Zeile für Zeile zusammenbauen, bis das Maximum erreicht ist ArrayList<ChatLine> lines = new ArrayList<ChatLine>(); String wline = ""; String tryline = ""; while (!words.isEmpty()) { // Solange noch Wörter da sind tryline = tryline + words.get(0); if (font.getWidth(tryline) < max) { // Es war ok dieses Wort zu adden words.remove(0); wline = tryline; } else { // Zu lang if (wline.equals("")) { // Oje, nichtmal ein Wort hat reingepasst. Das Wort muss also gesplittet werden // Bis zu welchem Index würdes denn passen int i = 1; while (font.getWidth(words.get(0).substring(0, i++)) < max) { } i--; // Bis i passt es, das als gerade getestet Zeile einstellen und den rest vom Wort dalassen wline = words.get(0).substring(0, i) + "-"; String complete = words.remove(0); words.add(0, complete.substring(i, complete.length() - 1)); } // Zeile ist so fertig, also adden if (lines.isEmpty()) { // Die erste soll den Namen zeigen, die andern nichtmehr lines.add(new ChatLine(wline, line.getPremessage(), line.getPremessageColor())); } else { lines.add(new ChatLine(wline, line.getPremessage(), line.getPremessageColor(), true)); } // Zurück auf Anfang wline = ""; tryline = ""; } } // Fertig das was da ist noch als Zeile raushauen lines.add(new ChatLine(tryline, line.getPremessage(), line.getPremessageColor(), true)); // Fertig mit Splitten, Array zurückliefern return lines.toArray(new ChatLine[1]); } @Override public void renderOverlay(Graphics g, int fullResX, int fullResY) { renderChat(g, 10, (int) (0.65 * fullResY)); } public UnicodeFont getFont() { return font; } }
tfg13/Centuries-of-Rage
src/de/_13ducks/cor/graphics/ClientChat.java
214,376
package com.voxeo.moho.media.dialect; import javax.media.mscontrol.Parameters; import com.voxeo.moho.media.InputMode; public interface MediaDialect { void setSpeechLanguage(Parameters parameters, String value); void setSpeechTermChar(Parameters parameters, Character value); void setSpeechInputMode(Parameters parameters, InputMode value); void setTextToSpeechVoice(Parameters parameters, String value); void setBeepOnConferenceEnter(Parameters parameters, Boolean value); void setBeepOnConferenceExit(Parameters parameters, Boolean value); void setDtmfHotwordEnabled(Parameters parameters, Boolean value); void setDtmfTypeaheadEnabled(Parameters parameters, Boolean value); void setConfidence(Parameters parameters, float value); }
loopingrage/moho
moho-api/src/main/java/com/voxeo/moho/media/dialect/MediaDialect.java
214,377
package com.dsatab.data.enums; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public enum Position { Head_Up("Kopf Oben"), Head_Side("Kopf seitl."), Head_Face("Gesicht"), Neck("Hals"), LeftShoulder("Linke Schulter", "Schulter L"), LeftUpperArm("Linker Oberarm", "Oberarm L"), LeftLowerArm("Linker Unterarm", "Unterarm L"), RightShoulder( "Rechte Schulter", "Schulter R"), RightUpperArm("Rechter Oberarm", "Oberarm R"), RightLowerArm( "Rechter Unterarm", "Unterarm R"), Brust("Brust", 4), Bauch("Bauch", 4), Ruecken("Rücken", 4), Pelvis( "Becken"), UpperLeg("Oberschenkel"), LowerLeg("Unterschenkel"), Kopf("Kopf", 2), LinkeHand("Linke Hand", "Hand L"), RechteHand("Rechte Hand", "Hand R"), LinkesBein("Linkes Bein", "Bein L", 2), RechtesBein( "Rechtes Bein", "Bein R", 2), LinkerArm("Linker Arm", "Arm L", 1), RechterArm("Rechter Arm", "Arm R", 1); protected String name; protected String nameShort; protected int multiplier; Position(String name, String nameShort, int mul) { this.name = name; this.nameShort = nameShort; this.multiplier = mul; } Position(String name, int mul) { this(name, name, mul); } Position(String name, String nameShort) { this(name, nameShort, 0); } Position(String name) { this(name, name, 0); } public String getName() { return name; } public String getNameSort() { return nameShort; } public int getMultiplier() { return multiplier; } @Override public String toString() { return getName(); } public static List<Position> WOUND_POSITIONS = new ArrayList<Position>(Arrays.asList(Position.Kopf, Position.Bauch, Position.Brust, Position.LinkerArm, Position.RechterArm, Position.LinkesBein, Position.RechtesBein)); // DO NOT CHANGE ORDER has to be the same of csv import file!!! public static List<Position> ARMOR_POSITIONS = new ArrayList<Position>(Arrays.asList(Position.Kopf, Position.Brust, Position.Ruecken, Position.Bauch, Position.LinkerArm, Position.RechterArm, Position.LinkesBein, Position.RechtesBein)); public static final Position[] messer_dolch_stich = new Position[21]; static { messer_dolch_stich[1] = Position.UpperLeg; messer_dolch_stich[2] = Position.UpperLeg; messer_dolch_stich[3] = Position.RightShoulder; messer_dolch_stich[4] = Position.RightLowerArm; messer_dolch_stich[5] = Position.RightLowerArm; messer_dolch_stich[6] = Position.RechteHand; messer_dolch_stich[7] = Position.RechteHand; messer_dolch_stich[8] = Position.RightUpperArm; messer_dolch_stich[9] = Position.LeftLowerArm; messer_dolch_stich[10] = Position.LeftLowerArm; messer_dolch_stich[11] = Position.LinkeHand; messer_dolch_stich[12] = Position.Bauch; messer_dolch_stich[13] = Position.Bauch; messer_dolch_stich[14] = Position.Brust; messer_dolch_stich[15] = Position.Brust; messer_dolch_stich[16] = Position.Pelvis; messer_dolch_stich[17] = Position.LowerLeg; messer_dolch_stich[18] = Position.Head_Side; messer_dolch_stich[19] = Position.Head_Face; messer_dolch_stich[20] = Position.Head_Face; } public static final Position[] hieb_ketten = new Position[21]; static { hieb_ketten[1] = Position.Pelvis; hieb_ketten[2] = Position.UpperLeg; hieb_ketten[3] = Position.RechteHand; hieb_ketten[4] = Position.RightLowerArm; hieb_ketten[5] = Position.RightLowerArm; hieb_ketten[6] = Position.LeftLowerArm; hieb_ketten[7] = Position.LeftLowerArm; hieb_ketten[8] = Position.RightUpperArm; hieb_ketten[9] = Position.RightUpperArm; hieb_ketten[10] = Position.LeftUpperArm; hieb_ketten[11] = Position.LeftUpperArm; hieb_ketten[12] = Position.Brust; hieb_ketten[13] = Position.LeftShoulder; hieb_ketten[14] = Position.RightShoulder; hieb_ketten[15] = Position.RightShoulder; hieb_ketten[16] = Position.Bauch; hieb_ketten[17] = Position.Head_Up; hieb_ketten[18] = Position.Head_Up; hieb_ketten[19] = Position.LowerLeg; hieb_ketten[20] = Position.Head_Side; } public static final Position[] schwert_saebel = new Position[21]; static { schwert_saebel[1] = Position.RechteHand; schwert_saebel[2] = Position.RightUpperArm; schwert_saebel[3] = Position.RightLowerArm; schwert_saebel[4] = Position.RightLowerArm; schwert_saebel[5] = Position.UpperLeg; schwert_saebel[6] = Position.UpperLeg; schwert_saebel[7] = Position.Pelvis; schwert_saebel[8] = Position.Pelvis; schwert_saebel[9] = Position.Bauch; schwert_saebel[10] = Position.Bauch; schwert_saebel[11] = Position.LowerLeg; schwert_saebel[12] = Position.LeftShoulder; schwert_saebel[13] = Position.RightShoulder; schwert_saebel[14] = Position.LeftUpperArm; schwert_saebel[15] = Position.LeftLowerArm; schwert_saebel[16] = Position.Brust; schwert_saebel[17] = Position.Brust; schwert_saebel[18] = Position.Head_Face; schwert_saebel[19] = Position.Head_Up; schwert_saebel[20] = Position.Head_Side; } public static final Position[] stangen_zweih_stich = new Position[21]; static { stangen_zweih_stich[1] = Position.LeftLowerArm; stangen_zweih_stich[2] = Position.LeftUpperArm; stangen_zweih_stich[3] = Position.LeftUpperArm; stangen_zweih_stich[4] = Position.RightLowerArm; stangen_zweih_stich[5] = Position.RightUpperArm; stangen_zweih_stich[6] = Position.UpperLeg; stangen_zweih_stich[7] = Position.UpperLeg; stangen_zweih_stich[8] = Position.RightShoulder; stangen_zweih_stich[9] = Position.LowerLeg; stangen_zweih_stich[10] = Position.Bauch; stangen_zweih_stich[11] = Position.Bauch; stangen_zweih_stich[12] = Position.Bauch; stangen_zweih_stich[13] = Position.RechteHand; stangen_zweih_stich[14] = Position.Brust; stangen_zweih_stich[15] = Position.Brust; stangen_zweih_stich[16] = Position.Brust; stangen_zweih_stich[17] = Position.Neck; stangen_zweih_stich[18] = Position.Pelvis; stangen_zweih_stich[19] = Position.Head_Face; stangen_zweih_stich[20] = Position.Head_Face; } public static final Position[] stangen_zweih_hieb = new Position[21]; static { stangen_zweih_hieb[1] = Position.UpperLeg; stangen_zweih_hieb[2] = Position.UpperLeg; stangen_zweih_hieb[3] = Position.LowerLeg; stangen_zweih_hieb[4] = Position.Bauch; stangen_zweih_hieb[5] = Position.Pelvis; stangen_zweih_hieb[6] = Position.RightLowerArm; stangen_zweih_hieb[7] = Position.RightLowerArm; stangen_zweih_hieb[8] = Position.RightUpperArm; stangen_zweih_hieb[9] = Position.LeftLowerArm; stangen_zweih_hieb[10] = Position.RechteHand; stangen_zweih_hieb[11] = Position.LeftUpperArm; stangen_zweih_hieb[12] = Position.LeftShoulder; stangen_zweih_hieb[13] = Position.RightShoulder; stangen_zweih_hieb[14] = Position.RightShoulder; stangen_zweih_hieb[15] = Position.Brust; stangen_zweih_hieb[16] = Position.Brust; stangen_zweih_hieb[17] = Position.Head_Up; stangen_zweih_hieb[18] = Position.Head_Up; stangen_zweih_hieb[19] = Position.Head_Side; stangen_zweih_hieb[20] = Position.Head_Side; } public static final Position[] box_rauf_hruru = new Position[21]; static { box_rauf_hruru[1] = Position.Brust; box_rauf_hruru[2] = Position.Brust; box_rauf_hruru[3] = Position.LeftUpperArm; box_rauf_hruru[4] = Position.RightUpperArm; box_rauf_hruru[5] = Position.LeftLowerArm; box_rauf_hruru[6] = Position.LeftLowerArm; box_rauf_hruru[7] = Position.RightLowerArm; box_rauf_hruru[8] = Position.RightLowerArm; box_rauf_hruru[9] = Position.RechteHand; box_rauf_hruru[10] = Position.Head_Face; box_rauf_hruru[11] = Position.Head_Face; box_rauf_hruru[12] = Position.Head_Face; box_rauf_hruru[13] = Position.Bauch; box_rauf_hruru[14] = Position.Bauch; box_rauf_hruru[15] = Position.Pelvis; box_rauf_hruru[16] = Position.LeftShoulder; box_rauf_hruru[17] = Position.RightShoulder; box_rauf_hruru[18] = Position.Head_Side; box_rauf_hruru[19] = Position.Head_Side; box_rauf_hruru[20] = Position.Head_Side; } public static final Position[] fern_wurf = new Position[21]; static { fern_wurf[1] = Position.LeftShoulder; fern_wurf[2] = Position.RightShoulder; fern_wurf[3] = Position.Pelvis; fern_wurf[4] = Position.Pelvis; fern_wurf[5] = Position.LeftUpperArm; fern_wurf[6] = Position.RightUpperArm; fern_wurf[7] = Position.LeftLowerArm; fern_wurf[8] = Position.RightLowerArm; fern_wurf[9] = Position.Brust; fern_wurf[10] = Position.Brust; fern_wurf[11] = Position.Brust; fern_wurf[12] = Position.Neck; fern_wurf[13] = Position.Bauch; fern_wurf[14] = Position.Bauch; fern_wurf[15] = Position.RechteHand; fern_wurf[16] = Position.LowerLeg; fern_wurf[17] = Position.UpperLeg; fern_wurf[18] = Position.UpperLeg; fern_wurf[19] = Position.Kopf; fern_wurf[20] = Position.Kopf; } public static final Position[] official = new Position[21]; static { official[1] = Position.LinkesBein; official[2] = Position.RechtesBein; official[3] = Position.LinkesBein; official[4] = Position.RechtesBein; official[5] = Position.LinkesBein; official[6] = Position.RechtesBein; official[7] = Position.Bauch; official[8] = Position.Bauch; official[9] = Position.LinkeHand; official[10] = Position.RechteHand; official[11] = Position.LinkeHand; official[12] = Position.RechteHand; official[13] = Position.LinkeHand; official[14] = Position.RechteHand; official[15] = Position.Brust; official[16] = Position.Brust; official[17] = Position.Brust; official[18] = Position.Brust; official[19] = Position.Kopf; official[20] = Position.Kopf; } }
gandulf/DsaTab
DsaTab/src/main/java/com/dsatab/data/enums/Position.java
214,378
// Repräsentiert einen konstanten arithmetischen Summenausdruck // (Ausdruck in dem Zahlen durch Addition verknüpft werden). interface Expression extends Iterable { // Liefert den Wert des Ausdrucks. int eval(); // Liefert eine lesbare Darstellung des Ausdrucks ohne Klammern. String toString(); // Liefert einen neuen Ausdruck, in dem 'exp' als rechter Summand hinzugefügt wurde. Expression add(Expression exp); }
sueszli/ep2
2018/number, sum/solution/Expression.java
214,379
package org.drip.graph.astar; /* * -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /*! * Copyright (C) 2022 Lakshmi Krishnamurthy * Copyright (C) 2021 Lakshmi Krishnamurthy * Copyright (C) 2020 Lakshmi Krishnamurthy * * This file is part of DROP, an open-source library targeting analytics/risk, transaction cost analytics, * asset liability management analytics, capital, exposure, and margin analytics, valuation adjustment * analytics, and portfolio construction analytics within and across fixed income, credit, commodity, * equity, FX, and structured products. It also includes auxiliary libraries for algorithm support, * numerical analysis, numerical optimization, spline builder, model validation, statistical learning, * graph builder/navigator, and computational support. * * https://lakshmidrip.github.io/DROP/ * * DROP is composed of three modules: * * - DROP Product Core - https://lakshmidrip.github.io/DROP-Product-Core/ * - DROP Portfolio Core - https://lakshmidrip.github.io/DROP-Portfolio-Core/ * - DROP Computational Core - https://lakshmidrip.github.io/DROP-Computational-Core/ * * DROP Product Core implements libraries for the following: * - Fixed Income Analytics * - Loan Analytics * - Transaction Cost Analytics * * DROP Portfolio Core implements libraries for the following: * - Asset Allocation Analytics * - Asset Liability Management Analytics * - Capital Estimation Analytics * - Exposure Analytics * - Margin Analytics * - XVA Analytics * * DROP Computational Core implements libraries for the following: * - Algorithm Support * - Computation Support * - Function Analysis * - Graph Algorithm * - Model Validation * - Numerical Analysis * - Numerical Optimizer * - Spline Builder * - Statistical Learning * * Documentation for DROP is Spread Over: * * - Main => https://lakshmidrip.github.io/DROP/ * - Wiki => https://github.com/lakshmiDRIP/DROP/wiki * - GitHub => https://github.com/lakshmiDRIP/DROP * - Repo Layout Taxonomy => https://github.com/lakshmiDRIP/DROP/blob/master/Taxonomy.md * - Javadoc => https://lakshmidrip.github.io/DROP/Javadoc/index.html * - Technical Specifications => https://github.com/lakshmiDRIP/DROP/tree/master/Docs/Internal * - Release Versions => https://lakshmidrip.github.io/DROP/version.html * - Community Credits => https://lakshmidrip.github.io/DROP/credits.html * - Issues Catalog => https://github.com/lakshmiDRIP/DROP/issues * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. */ /** * <i>VertexFunction</i> exposes the Value at a Vertex. The References are: * * <br><br> * <ul> * <li> * Dechter, R., and J. Pearl (1985): Generalized Best-first Search Strategies and the Optimality of * A<sup>*</sup> <i>Journal of the ACM</i> <b>32 (3)</b> 505-536 * </li> * <li> * Hart, P. E., N. J. Nilsson, and B. Raphael (1968): A Formal Basis for the Heuristic Determination * of the Minimum Cost Paths <i>IEEE Transactions on Systems Sciences and Cybernetics</i> <b>4 * (2)</b> 100-107 * </li> * <li> * Kagan, E., and I. Ben-Gal (2014): A Group Testing Algorithm with Online Informational Learning * <i>IIE Transactions</i> <b>46 (2)</b> 164-184 * </li> * <li> * Russell, S. J. and P. Norvig (2018): <i>Artificial Intelligence: A Modern Approach 4<sup>th</sup> * Edition</i> <b>Pearson</b> * </li> * <li> * Wikipedia (2020): A<sup>*</sup> Search Algorithm * https://en.wikipedia.org/wiki/A*_search_algorithm * </li> * </ul> * * <br><br> * <ul> * <li><b>Module </b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/ComputationalCore.md">Computational Core Module</a></li> * <li><b>Library</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/GraphAlgorithmLibrary.md">Graph Algorithm Library</a></li> * <li><b>Project</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/graph/README.md">Graph Optimization and Tree Construction Algorithms</a></li> * <li><b>Package</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/graph/astar/README.md">A<sup>*</sup> Heuristic Shortest Path Family</a></li> * </ul> * <br><br> * * @author Lakshmi Krishnamurthy */ public interface VertexFunction { /** * Compute the Value at the Vertex * * @param vertex The Vertex * * @return The Value * * @throws java.lang.Exception Thrown if the Input are Invalid */ public abstract double evaluate ( final org.drip.graph.core.Vertex vertex) throws java.lang.Exception; }
lakshmiDRIP/DROP
src/main/java/org/drip/graph/astar/VertexFunction.java
214,380
package com.voxeo.moho.media.dialect; import javax.media.mscontrol.Parameters; import com.voxeo.moho.media.InputMode; public class GenericDialect implements MediaDialect { @Override public void setBeepOnConferenceEnter(Parameters parameters, Boolean value) {} @Override public void setBeepOnConferenceExit(Parameters parameters, Boolean value) {} @Override public void setSpeechInputMode(Parameters parameters, InputMode value) {} @Override public void setSpeechLanguage(Parameters parameters, String value) {} @Override public void setSpeechTermChar(Parameters parameters, Character value) {} @Override public void setTextToSpeechVoice(Parameters parameters, String value) {} @Override public void setDtmfHotwordEnabled(Parameters parameters, Boolean value) {} @Override public void setDtmfTypeaheadEnabled(Parameters parameters, Boolean value) {} @Override public void setConfidence(Parameters parameters, float value) {} }
loopingrage/moho
moho-impl/src/main/java/com/voxeo/moho/media/dialect/GenericDialect.java
214,383
/***************************** AVLBaum.java *********************************/ //import AlgoTools.IO; /** Ein AVLBaum ist ein SuchBaum, bei dem alle Knoten ausgeglichen * sind. Das heisst, die Hoehe aller Teilbaeume unterscheidet sich * maximal um eins. */ package db.avltree; public class AVLBaum extends SuchBaum { private int balance; // Balance public AVLBaum() { // erzeugt leeren AVLBaum balance = 0; } private static class Status { // Innere Klasse zur Uebergabe eines // Status in der Rekursion boolean unbal; // unbal ist true, wenn beim Einfue- // gen ein Sohn groesser geworden ist Status () { // Konstruktor der inneren Klasse unbal = false; // Element noch nicht eingefuegt => } // noch keine Unausgeglichenheit } public String toString() { // fuer Ausgabe: Inhalt(Balance) return inhalt + "(" + balance + ")"; } public boolean insert(Comparable x) throws Exception {// fuegt x in den AVLBaum ein: true, // wenn erfolgreich, sonst false. // Kapselt die Funktion insertAVL return insertAVL(x, new Status()); } private boolean insertAVL(Comparable x, Status s) throws Exception { // Tatsaechliche Methode zum // Einfuegen (rekursiv) boolean eingefuegt; if (empty()) { // Blatt: Hier kann eingefuegt werden inhalt = x; // Inhalt setzen links = new AVLBaum(); // Neuer leerer AVLBaum links rechts = new AVLBaum(); // Neuer leerer AVLBaum rechts s.unbal = true; // Dieser Teilbaum wurde groesser return true; // Einfuegen erfolgreich und } // dieser Teilbaum groesser else if (((Comparable) value()).compareTo(x) == 0) // Element schon im AVLBaum return false; else if (((Comparable) value()).compareTo(x) > 0) { // Element x ist kleiner => eingefuegt = ((AVLBaum) left()).insertAVL(x, s); // linker Teilbaum if (s.unbal) { // Linker Teilbaum wurde groesser switch (balance) { case 1: // Alte Unausgeglichenheit ausgegl. balance = 0; // => neue Balance = 0 s.unbal = false; // Unausgeglichenheit ausgeglichen return true; case 0: // Hier noch kein Rotieren noetig balance = -1; // Balance wird angeglichen return true; default: // Rotieren notwendig if (((AVLBaum) links).balance == -1) rotateLL(); else rotateLR(); s.unbal = false; // Unausgeglichenheit ausgeglichen return true; // => Rueckgabewert // angleichen } } } else { // Element ist groesser => eingefuegt = ((AVLBaum) right()).insertAVL(x, s);// rechter Teilbaum if (s.unbal) { // Rechter Teilbaum wurde groesser switch (balance) { case -1: // Alte Unausgeglichenheit ausgegl. balance = 0; // => neue Balance = 0 s.unbal = false; // Unausgeglichenheit ausgeglichen return true; case 0: // Hier noch kein Rotieren noetig balance = 1; // Balance wird angeglichen return true; default: // Rotieren notwendig if (((AVLBaum) rechts).balance == 1) rotateRR(); else rotateRL(); s.unbal = false; // Unausgeglichenheit ausgeglichen return true; // => Rueckgabewert // angleichen } } } return eingefuegt; // Keine Rotation => Ergebnis zurueck } public void rotateLL() { //IO.println("LL-Rotation im Teilbaum mit Wurzel "+ inhalt); AVLBaum a1 = (AVLBaum) links; // Merke linken AVLBaum a2 = (AVLBaum) rechts; // und rechten Teilbaum // Idee: Inhalt von a1 in die Wurzel links = a1.links; // Setze neuen linken Sohn rechts = a1; // Setze neuen rechten Sohn a1.links = a1.rechts; // Setze dessen linken a1.rechts = a2; // und rechten Sohn Object tmp = a1.inhalt; // Inhalt von rechts (==a1) a1.inhalt = inhalt; // wird mit Wurzel inhalt = tmp; // getauscht ((AVLBaum) rechts).balance = 0; // rechter Teilbaum balanciert balance = 0; // Wurzel balanciert } public void rotateLR() { //IO.println("LR-Rotation im Teilbaum mit Wurzel "+ inhalt); AVLBaum a1 = (AVLBaum) links; // Merke linken AVLBaum a2 = (AVLBaum) a1.rechts; // und dessen rechten Teilbaum // Idee: Inhalt von a2 in die Wurzel a1.rechts = a2.links; // Setze Soehne von a2 a2.links = a2.rechts; a2.rechts = rechts; rechts = a2; // a2 wird neuer rechter Sohn Object tmp = inhalt; // Inhalt von rechts (==a2) inhalt = rechts.inhalt; // wird mit Wurzel rechts.inhalt = tmp; // getauscht if (a2.balance == 1) // Neue Bal. fuer linken Sohn ((AVLBaum) links).balance = -1; else ((AVLBaum) links).balance = 0; if (a2.balance == -1) // Neue Bal. fuer rechten Sohn ((AVLBaum) rechts).balance = 1; else ((AVLBaum) rechts).balance = 0; balance = 0; // Wurzel balanciert } public void rotateRR() { //IO.println("RR-Rotation im Teilbaum mit Wurzel "+ inhalt); AVLBaum a1 = (AVLBaum) rechts; // Merke rechten AVLBaum a2 = (AVLBaum) links; // und linken Teilbaum // Idee: Inhalt von a1 in die Wurzel rechts = a1.rechts; // Setze neuen rechten Sohn links = a1; // Setze neuen linken Sohn a1.rechts = a1.links; // Setze dessen rechten a1.links = a2; // und linken Sohn Object tmp = a1.inhalt; // Inhalt von links (==a1) a1.inhalt = inhalt; // wird mit Wurzel inhalt = tmp; // getauscht ((AVLBaum) links).balance = 0; // linker Teilbaum balanciert balance = 0; // Wurzel balanciert } public void rotateRL() { //IO.println("RL-Rotation im Teilbaum mit Wurzel "+ inhalt); AVLBaum a1 = (AVLBaum) rechts; // Merke rechten Sohn AVLBaum a2 = (AVLBaum) a1.links; // und dessen linken Teilbaum // Idee: Inhalt von a2 in die Wurzel a1.links = a2.rechts; a2.rechts = a2.links; // Setze Soehne von a2 a2.links = links; links = a2; // a2 wird neuer linker Sohn Object tmp = inhalt; // Inhalt von links (==a2) inhalt = links.inhalt; // wird mit Wurzel links.inhalt = tmp; // getauscht if (a2.balance == -1) // Neue Bal. fuer rechten Sohn ((AVLBaum) rechts).balance = 1; else ((AVLBaum) rechts).balance = 0; if (a2.balance == 1) // Neue Bal. fuer linken Sohn ((AVLBaum) links).balance = -1; else ((AVLBaum) links).balance = 0; balance = 0; // Wurzel balanciert } @Override public boolean delete(Comparable x) throws Exception {// loescht x im AVLBaum: true, // wenn erfolgreich, sonst false. // Kapselt die Funktion deleteAVL return deleteAVL(x, new Status()); } private boolean deleteAVL(Comparable x, Status s) throws Exception { // Tatsaechliche Methode // zum Loeschen (rekursiv); true, wenn erfolgreich boolean geloescht; // true, wenn geloescht wurde if (empty()) { // Blatt: Element nicht gefunden return false; // => Einfuegen erfolglos } else if (((Comparable) value()).compareTo(x) < 0) { // Element x ist groesser => // Suche rechts weiter geloescht = ((AVLBaum) rechts).deleteAVL(x, s); if (s.unbal == true) balance2(s); // Gleiche ggf. aus return geloescht; } else if (((Comparable) value()).compareTo(x) > 0) { // Element x ist kleiner => // Suche links weiter geloescht = ((AVLBaum) links).deleteAVL(x, s); if (s.unbal == true) balance1(s); // Gleiche ggf. aus return geloescht; } else { // Element gefunden if (rechts.empty()) { // Kein rechter Sohn inhalt = links.inhalt; // ersetze Knoten durch linken Sohn links = links.links; // Kein linker Sohn mehr balance = 0; // Knoten ist Blatt s.unbal = true; // Hoehe hat sich geaendert } else if (links.empty()) { // Kein linker Sohn inhalt = rechts.inhalt; // ersetze Knoten durch rechten Sohn rechts = rechts.rechts; // Kein rechter Sohn mehr balance = 0; // Knoten ist Blatt s.unbal = true; // Hoehe hat sich geaendert } else { // Beide Soehne vorhanden inhalt = ((AVLBaum) links).del(s); // Rufe del() auf if (s.unbal) { // Gleiche Unbalance aus balance1(s); } } return true; // Loeschen erfolgreich } } private Object del(Status s) { // Sucht Ersatz fuer gel. Objekt Object ersatz; // Das Ersatz-Objekt if (!rechts.empty()) { // Suche groessten Sohn im Teilbaum ersatz = ((AVLBaum) rechts).del(s); if (s.unbal) // Gleicht ggf. Unbalance aus balance2(s); } else { // Tausche mit geloeschtem Knoten ersatz = inhalt; // Merke Ersatz und inhalt = links.inhalt; // ersetze Knoten durch linken Sohn. links = links.links; // Kein linker Sohn mehr balance = 0; // Knoten ist Blatt s.unbal = true; // Teilbaum wurde kuerzer } return ersatz; // Gib Ersatz-Objekt zurueck } private void balance1(Status s) { // Unbalance, weil linker Ast kuerzer switch (balance) { case -1: balance = 0; // Balance geaendert, nicht ausgegl. break; case 0: balance = 1; // Ausgeglichen s.unbal = false; break; default: // Ausgleichen (Rotation) notwendig int b = ((AVLBaum) rechts).balance; //Merke Balance des rechten Sohns if (b >= 0) { rotateRR(); if (b == 0) { // Gleiche neue Balancen an balance = -1; ((AVLBaum) links).balance = 1; s.unbal = false; } } else rotateRL(); break; } } private void balance2(Status s) { // Unbalance, weil recht. Ast kuerzer switch (balance) { case 1: balance = 0; // Balance geaendert, nicht ausgegl. break; case 0: balance = -1; // Ausgeglichen s.unbal = false; break; default: // Ausgleichen (Rotation) notwendig int b = ((AVLBaum) links).balance; // Merke Balance des linken Sohns if (b <= 0) { rotateLL(); if (b == 0) { // Gleiche neue Balancen an balance = 1; ((AVLBaum) rechts).balance = -1; s.unbal = false; } } else rotateLR(); break; } } }
sPyOpenSource/os
src/db/avltree/AVLBaum.java
214,384
package org.drip.graph.astar; /* * -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /*! * Copyright (C) 2022 Lakshmi Krishnamurthy * Copyright (C) 2021 Lakshmi Krishnamurthy * Copyright (C) 2020 Lakshmi Krishnamurthy * * This file is part of DROP, an open-source library targeting analytics/risk, transaction cost analytics, * asset liability management analytics, capital, exposure, and margin analytics, valuation adjustment * analytics, and portfolio construction analytics within and across fixed income, credit, commodity, * equity, FX, and structured products. It also includes auxiliary libraries for algorithm support, * numerical analysis, numerical optimization, spline builder, model validation, statistical learning, * graph builder/navigator, and computational support. * * https://lakshmidrip.github.io/DROP/ * * DROP is composed of three modules: * * - DROP Product Core - https://lakshmidrip.github.io/DROP-Product-Core/ * - DROP Portfolio Core - https://lakshmidrip.github.io/DROP-Portfolio-Core/ * - DROP Computational Core - https://lakshmidrip.github.io/DROP-Computational-Core/ * * DROP Product Core implements libraries for the following: * - Fixed Income Analytics * - Loan Analytics * - Transaction Cost Analytics * * DROP Portfolio Core implements libraries for the following: * - Asset Allocation Analytics * - Asset Liability Management Analytics * - Capital Estimation Analytics * - Exposure Analytics * - Margin Analytics * - XVA Analytics * * DROP Computational Core implements libraries for the following: * - Algorithm Support * - Computation Support * - Function Analysis * - Graph Algorithm * - Model Validation * - Numerical Analysis * - Numerical Optimizer * - Spline Builder * - Statistical Learning * * Documentation for DROP is Spread Over: * * - Main => https://lakshmidrip.github.io/DROP/ * - Wiki => https://github.com/lakshmiDRIP/DROP/wiki * - GitHub => https://github.com/lakshmiDRIP/DROP * - Repo Layout Taxonomy => https://github.com/lakshmiDRIP/DROP/blob/master/Taxonomy.md * - Javadoc => https://lakshmidrip.github.io/DROP/Javadoc/index.html * - Technical Specifications => https://github.com/lakshmiDRIP/DROP/tree/master/Docs/Internal * - Release Versions => https://lakshmidrip.github.io/DROP/version.html * - Community Credits => https://lakshmidrip.github.io/DROP/credits.html * - Issues Catalog => https://github.com/lakshmiDRIP/DROP/issues * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. */ /** * <i>VertexContext</i> holds the Current Vertex, its Parent, and the most recently expanded Vertexes for use * in the Alpha A<sup>*</sup> Heuristic Function. The References are: * * <br><br> * <ul> * <li> * Dechter, R., and J. Pearl (1985): Generalized Best-first Search Strategies and the Optimality of * A<sup>*</sup> <i>Journal of the ACM</i> <b>32 (3)</b> 505-536 * </li> * <li> * Hart, P. E., N. J. Nilsson, and B. Raphael (1968): A Formal Basis for the Heuristic Determination * of the Minimum Cost Paths <i>IEEE Transactions on Systems Sciences and Cybernetics</i> <b>4 * (2)</b> 100-107 * </li> * <li> * Kagan, E., and I. Ben-Gal (2014): A Group Testing Algorithm with Online Informational Learning * <i>IIE Transactions</i> <b>46 (2)</b> 164-184 * </li> * <li> * Russell, S. J. and P. Norvig (2018): <i>Artificial Intelligence: A Modern Approach 4<sup>th</sup> * Edition</i> <b>Pearson</b> * </li> * <li> * Wikipedia (2020): A<sup>*</sup> Search Algorithm * https://en.wikipedia.org/wiki/A*_search_algorithm * </li> * </ul> * * <br><br> * <ul> * <li><b>Module </b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/ComputationalCore.md">Computational Core Module</a></li> * <li><b>Library</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/GraphAlgorithmLibrary.md">Graph Algorithm Library</a></li> * <li><b>Project</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/graph/README.md">Graph Optimization and Tree Construction Algorithms</a></li> * <li><b>Package</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/graph/astar/README.md">A<sup>*</sup> Heuristic Shortest Path Family</a></li> * </ul> * <br><br> * * @author Lakshmi Krishnamurthy */ public class VertexContext { private org.drip.graph.core.Vertex _parent = null; private org.drip.graph.core.Vertex _current = null; private org.drip.graph.core.Vertex _mostRecentlyExpanded = null; /** * VertexContext Constructor * * @param current Current Vertex * @param parent Parent Vertex * @param mostRecentlyExpanded Most Recently Expanded Vertex * * @throws java.lang.Exception Thrown if the Inputs are Invalid */ public VertexContext ( final org.drip.graph.core.Vertex current, final org.drip.graph.core.Vertex parent, final org.drip.graph.core.Vertex mostRecentlyExpanded) throws java.lang.Exception { if (null == (_current = current) || null == (_mostRecentlyExpanded = mostRecentlyExpanded) ) { throw new java.lang.Exception ( "VertexContext Constructor => Invalid Inputs" ); } _parent = parent; } /** * Retrieve the Current Vertex * * @return The Current Vertex */ public org.drip.graph.core.Vertex current() { return _current; } /** * Retrieve the Parent Vertex * * @return The Parent Vertex */ public org.drip.graph.core.Vertex parent() { return _parent; } /** * Retrieve the Most Recently Expanded Vertex * * @return The Most Recently Expanded Vertex */ public org.drip.graph.core.Vertex mostRecentlyExpanded() { return _mostRecentlyExpanded; } }
lakshmiDRIP/DROP
src/main/java/org/drip/graph/astar/VertexContext.java
214,385
package org.drip.graph.astar; /* * -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /*! * Copyright (C) 2022 Lakshmi Krishnamurthy * Copyright (C) 2021 Lakshmi Krishnamurthy * Copyright (C) 2020 Lakshmi Krishnamurthy * * This file is part of DROP, an open-source library targeting analytics/risk, transaction cost analytics, * asset liability management analytics, capital, exposure, and margin analytics, valuation adjustment * analytics, and portfolio construction analytics within and across fixed income, credit, commodity, * equity, FX, and structured products. It also includes auxiliary libraries for algorithm support, * numerical analysis, numerical optimization, spline builder, model validation, statistical learning, * graph builder/navigator, and computational support. * * https://lakshmidrip.github.io/DROP/ * * DROP is composed of three modules: * * - DROP Product Core - https://lakshmidrip.github.io/DROP-Product-Core/ * - DROP Portfolio Core - https://lakshmidrip.github.io/DROP-Portfolio-Core/ * - DROP Computational Core - https://lakshmidrip.github.io/DROP-Computational-Core/ * * DROP Product Core implements libraries for the following: * - Fixed Income Analytics * - Loan Analytics * - Transaction Cost Analytics * * DROP Portfolio Core implements libraries for the following: * - Asset Allocation Analytics * - Asset Liability Management Analytics * - Capital Estimation Analytics * - Exposure Analytics * - Margin Analytics * - XVA Analytics * * DROP Computational Core implements libraries for the following: * - Algorithm Support * - Computation Support * - Function Analysis * - Graph Algorithm * - Model Validation * - Numerical Analysis * - Numerical Optimizer * - Spline Builder * - Statistical Learning * * Documentation for DROP is Spread Over: * * - Main => https://lakshmidrip.github.io/DROP/ * - Wiki => https://github.com/lakshmiDRIP/DROP/wiki * - GitHub => https://github.com/lakshmiDRIP/DROP * - Repo Layout Taxonomy => https://github.com/lakshmiDRIP/DROP/blob/master/Taxonomy.md * - Javadoc => https://lakshmidrip.github.io/DROP/Javadoc/index.html * - Technical Specifications => https://github.com/lakshmiDRIP/DROP/tree/master/Docs/Internal * - Release Versions => https://lakshmidrip.github.io/DROP/version.html * - Community Credits => https://lakshmidrip.github.io/DROP/credits.html * - Issues Catalog => https://github.com/lakshmiDRIP/DROP/issues * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. */ /** * <i>FHeuristic</i> implements the A<sup>*</sup> F-Heuristic Value at a Vertex. The References are: * * <br><br> * <ul> * <li> * Dechter, R., and J. Pearl (1985): Generalized Best-first Search Strategies and the Optimality of * A<sup>*</sup> <i>Journal of the ACM</i> <b>32 (3)</b> 505-536 * </li> * <li> * Hart, P. E., N. J. Nilsson, and B. Raphael (1968): A Formal Basis for the Heuristic Determination * of the Minimum Cost Paths <i>IEEE Transactions on Systems Sciences and Cybernetics</i> <b>4 * (2)</b> 100-107 * </li> * <li> * Kagan, E., and I. Ben-Gal (2014): A Group Testing Algorithm with Online Informational Learning * <i>IIE Transactions</i> <b>46 (2)</b> 164-184 * </li> * <li> * Russell, S. J. and P. Norvig (2018): <i>Artificial Intelligence: A Modern Approach 4<sup>th</sup> * Edition</i> <b>Pearson</b> * </li> * <li> * Wikipedia (2020): A<sup>*</sup> Search Algorithm * https://en.wikipedia.org/wiki/A*_search_algorithm * </li> * </ul> * * <br><br> * <ul> * <li><b>Module </b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/ComputationalCore.md">Computational Core Module</a></li> * <li><b>Library</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/GraphAlgorithmLibrary.md">Graph Algorithm Library</a></li> * <li><b>Project</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/graph/README.md">Graph Optimization and Tree Construction Algorithms</a></li> * <li><b>Package</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/graph/astar/README.md">A<sup>*</sup> Heuristic Shortest Path Family</a></li> * </ul> * <br><br> * * @author Lakshmi Krishnamurthy */ public class FHeuristic implements org.drip.graph.astar.VertexFunction { private org.drip.graph.astar.VertexFunction _gHeuristic = null; private org.drip.graph.astar.VertexFunction _hHeuristic = null; /** * FHeuristic Constructor * * @param gHeuristic The G Heuristic * @param hHeuristic The H Heuristic * * @throws java.lang.Exception Thrown if the Inputs are Invalid */ public FHeuristic ( final org.drip.graph.astar.VertexFunction gHeuristic, final org.drip.graph.astar.VertexFunction hHeuristic) throws java.lang.Exception { if (null == (_gHeuristic = gHeuristic) || null == (_hHeuristic = hHeuristic) ) { throw new java.lang.Exception ( "FHeuristic Constructor => Invalid Inputs" ); } } /** * Retrieve the G Heuristic * * @return The G Heuristic */ public org.drip.graph.astar.VertexFunction gHeuristic() { return _gHeuristic; } /** * Retrieve the H Heuristic * * @return The H Heuristic */ public org.drip.graph.astar.VertexFunction hHeuristic() { return _hHeuristic; } @Override public double evaluate ( final org.drip.graph.core.Vertex vertex) throws java.lang.Exception { return _gHeuristic.evaluate ( vertex ) + _hHeuristic.evaluate ( vertex ); } /** * Indicate if the Heuristic is Monotone * * @param graph The Graph * @param edge The Edge * * @return TRUE - The Heuristic is Monotone * * @throws java.lang.Exception Thrown if the Inputs are Invalid */ public boolean isMonotone ( final org.drip.graph.core.Network graph, final org.drip.graph.core.Edge edge) throws java.lang.Exception { if (null == graph || null == edge ) { throw new java.lang.Exception ( "FHeuristic::isMonotone => Invalid Inputs" ); } java.util.Map<java.lang.String, org.drip.graph.core.Vertex> vertexMap = graph.vertexMap(); return evaluate ( vertexMap.get ( edge.sourceVertexName() ) ) <= edge.weight() + evaluate ( vertexMap.get ( edge.destinationVertexName() ) ); } /** * Indicate if the Heuristic is Consistent * * @param graph The Graph * @param edge The Edge * * @return TRUE - The Heuristic is Consistent * * @throws java.lang.Exception Thrown if the Inputs are Invalid */ public boolean isConsistent ( final org.drip.graph.core.Network graph, final org.drip.graph.core.Edge edge) throws java.lang.Exception { return isMonotone ( graph, edge ); } /** * Compute the Reduced Weight of the Edge * * @param graph The Graph * @param edge The Edge * * @return The Reduced Weight of the Edge * * @throws java.lang.Exception Thrown if the Inputs are Invalid */ public double reducedWeight ( final org.drip.graph.core.Network graph, final org.drip.graph.core.Edge edge) throws java.lang.Exception { if (null == graph || null == edge ) { throw new java.lang.Exception ( "FHeuristic::reducedWeight => Invalid Inputs" ); } java.util.Map<java.lang.String, org.drip.graph.core.Vertex> vertexMap = graph.vertexMap(); return edge.weight() + evaluate ( vertexMap.get ( edge.destinationVertexName() ) ) - evaluate ( vertexMap.get ( edge.sourceVertexName() ) ); } }
lakshmiDRIP/DROP
src/main/java/org/drip/graph/astar/FHeuristic.java
214,386
/*************************************************************** /"A service by which a client may conduct asynchronous dialogues (message interchanges) with one or more other services. This service is useful when many collaborating services are required to satisfy a client request, and/or when significant delays are involved is satisfying the request. This service was defined under OWS 1.2 in support of SPS operations. WNS has broad applicability in many such multi-service applications. Copyright (C) 2007 by 52�North Initiative for Geospatial Open Source Software GmbH Author: Dennis Dahlmann, University of Muenster Contact: Andreas Wytzisk, 52�North Initiative for Geospatial Open Source Software GmbH, Martin-Luther-King-Weg 24, 48155 Muenster, Germany, [email protected] This program is free software; you can redistribute and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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 (see gnu-gpl v2.txt); if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA or visit the Free Software Foundation's web page, http://www.fsf.org. Created on: 2006-07-28 //Last changes on: 2007-03-15 //Last changes by: Dennis Dahlmann ***************************************************************/ package org.n52.wns.db; import org.n52.wns.WNSException; import org.x52North.wns.v2.WNSUserDocument; /** * @author Johannes Echterhoff * @version 2.0 * */ public interface UserDAO { /** * Returns the user document of the WNS. * * @return The user document of the WNS. * * @throws WNSException * If the user document could not be retrieved. */ WNSUserDocument getUserDocument() throws WNSException; /** * Persists the given user document. * * @param wnsud * The document to save. * * @throws WNSException * If the document could not be persisted. */ void storeWNSUserDocument(WNSUserDocument wnsud) throws WNSException; }
52North/WNS
src/main/java/org/n52/wns/db/UserDAO.java
214,387
/*************************************************************** /"A service by which a client may conduct asynchronous dialogues (message interchanges) with one or more other services. This service is useful when many collaborating services are required to satisfy a client request, and/or when significant delays are involved is satisfying the request. This service was defined under OWS 1.2 in support of SPS operations. WNS has broad applicability in many such multi-service applications. Copyright (C) 2007 by 52�North Initiative for Geospatial Open Source Software GmbH Author: Dennis Dahlmann, University of Muenster Contact: Andreas Wytzisk, 52�North Initiative for Geospatial Open Source Software GmbH, Martin-Luther-King-Weg 24, 48155 Muenster, Germany, [email protected] This program is free software; you can redistribute and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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 (see gnu-gpl v2.txt); if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA or visit the Free Software Foundation's web page, http://www.fsf.org. Created on: 2006-07-28 //Last changes on: 2007-03-15 //Last changes by: Dennis Dahlmann ***************************************************************/ package org.n52.wns.db; import org.n52.wns.WNSException; import org.x52North.wns.v2.WNSConfigDocument.WNSConfig.ServiceProperties.DataBaseProperties; /** * @author Johannes Echterhoff * @version 2.0 * */ public interface DAOFactory { /** * Returns a DAO for handling WNS users. * * @return A DAO for handling WNS users. */ public UserDAO getUserDAO() throws WNSException; public void configure(DataBaseProperties props); /** * * @return The DAO to handle messages */ public MessageDAO getMessageDAO() throws WNSException; }
52North/WNS
src/main/java/org/n52/wns/db/DAOFactory.java
214,388
package core.model.player; import core.constants.TrainingType; import core.constants.player.PlayerSpeciality; import core.constants.player.Speciality; import core.db.AbstractTable; import core.db.DBManager; import core.model.*; import core.model.match.MatchLineupTeam; import core.model.enums.MatchType; import core.model.match.Weather; import core.net.MyConnector; import core.net.OnlineWorker; import core.rating.RatingPredictionManager; import core.training.*; import core.util.*; import org.jetbrains.annotations.Nullable; import java.time.Duration; import java.util.*; import static java.lang.Integer.min; import static core.constants.player.PlayerSkill.*; public class Player extends AbstractTable.Storable { /** * Cache for player contribution (Hashtable<String, Float>) */ private static final Hashtable<String, Object> PlayerAbsoluteContributionCache = new Hashtable<>(); private static final Hashtable<String, Object> PlayerRelativeContributionCache = new Hashtable<>(); private byte idealPos = IMatchRoleID.UNKNOWN; private static final String BREAK = "[br]"; private static final String O_BRACKET = "["; private static final String C_BRACKET = "]"; private static final String EMPTY = ""; /** * Name */ private String m_sFirstName = ""; private String m_sNickName = ""; private String m_sLastName = ""; /** * Arrival in team */ private String m_arrivalDate; /** * Download date */ private HODateTime m_clhrfDate; /** * The player is no longer available in the current HRF */ private boolean m_bOld; /** * Wing skill */ private double m_dSubFluegelspiel; /** * Pass skill */ private double m_dSubPasspiel; /** * Playmaking skill */ private double m_dSubSpielaufbau; /** * Standards */ private double m_dSubStandards; /** * Goal */ private double m_dSubTorschuss; //Subskills private double m_dSubTorwart; /** * Verteidigung */ private double m_dSubVerteidigung; /** * Agressivität */ private int m_iAgressivitaet; /** * Alter */ private int m_iAlter; /** * Age Days */ private int m_iAgeDays; /** * Ansehen (ekel usw. ) */ private int m_iAnsehen = 1; /** * Bewertung */ private int m_iBewertung; /** * charakter ( ehrlich) */ private int m_iCharakter = 1; /** * Erfahrung */ private int m_iErfahrung = 1; /** * Fluegelspiel */ private int m_iFluegelspiel = 1; /** * Form */ private int m_iForm = 1; /** * Führungsqualität */ private int m_iFuehrung = 1; /** * Gehalt */ private int m_iGehalt = 1; /** * Gelbe Karten */ private int m_iCards; /** * Hattricks */ private int m_iHattrick; private int m_iGoalsCurrentTeam; /** * Home Grown */ private boolean m_bHomeGrown = false; /** * Kondition */ private int m_iKondition = 1; /** * Länderspiele */ private int m_iLaenderspiele; /** * Loyalty */ private int m_iLoyalty = 0; /** * Markwert */ private int m_iTSI; private String m_sNationality; /** * Aus welchem Land kommt der Player */ private int m_iNationalitaet = 49; /** * Passpiel */ private int m_iPasspiel = 1; /** * SpezialitätID */ private int iPlayerSpecialty; /** * Spielaufbau */ private int m_iSpielaufbau = 1; /** * SpielerID */ private int m_iSpielerID; /** * Standards */ private int m_iStandards = 1; /** * Tore Freundschaftspiel */ private int m_iToreFreund; /** * Tore Gesamt */ private int m_iToreGesamt; /** * Tore Liga */ private int m_iToreLiga; /** * Tore Pokalspiel */ private int m_iTorePokal; /** * Torschuss */ private int m_iTorschuss = 1; /** * Torwart */ private int m_iTorwart = 1; /** * Trainerfähigkeit */ private int m_iTrainer; /** * Trainertyp */ private TrainerType m_iTrainerTyp; /** * Transferlisted */ private int m_iTransferlisted; /** * shirt number (can be edited in hattrick) */ private int shirtNumber = -1; /** * player's category (can be edited in hattrick) */ private PlayerCategory playerCategory; /** * player statement (can be edited in hattrick) */ private String playerStatement; /** * Owner notes (can be edited in hattrick) */ private String ownerNotes; /** * Länderspiele */ private int m_iU20Laenderspiele; /** * Verletzt Wochen */ private int m_iInjuryWeeks = -1; /** * Verteidigung */ private int m_iVerteidigung = 1; /** * Training block */ private boolean m_bTrainingBlock = false; /** * Last match */ private String m_lastMatchDate; private Integer m_lastMatchId; private MatchType lastMatchType; private Integer lastMatchPosition; private Integer lastMatchMinutes; // Rating is number of half stars // real rating value is rating/2.0f private Integer m_lastMatchRating; private Integer lastMatchRatingEndOfGame; /** * specifying at what time –in minutes- that player entered the field * This parameter is only used by RatingPredictionManager to calculate the stamina effect * along the course of the game */ private int GameStartingTime = 0; private Integer nationalTeamId; private double subExperience; /** * future training priorities planed by the user */ private List<FuturePlayerTraining> futurePlayerTrainings; private Integer motherclubId; private String motherclubName; private Integer matchesCurrentTeam; private int hrf_id; private Integer htms = null; private Integer htms28 = null; public int getGameStartingTime() { return GameStartingTime; } public void setGameStartingTime(int gameStartingTime) { GameStartingTime = gameStartingTime; } //~ Constructors ------------------------------------------------------------------------------- /** * Creates a new instance of Player */ public Player() { } /** * Erstellt einen Player aus den Properties einer HRF Datei */ public Player(java.util.Properties properties, HODateTime hrfdate, int hrf_id) { // Separate first, nick and last names are available. Utilize them? this.hrf_id=hrf_id; m_iSpielerID = Integer.parseInt(properties.getProperty("id", "0")); m_sFirstName = properties.getProperty("firstname", ""); m_sNickName = properties.getProperty("nickname", ""); m_sLastName = properties.getProperty("lastname", ""); m_arrivalDate = properties.getProperty("arrivaldate"); m_iAlter = Integer.parseInt(properties.getProperty("ald", "0")); m_iAgeDays = Integer.parseInt(properties.getProperty("agedays", "0")); m_iKondition = Integer.parseInt(properties.getProperty("uth", "0")); m_iForm = Integer.parseInt(properties.getProperty("for", "0")); m_iTorwart = Integer.parseInt(properties.getProperty("mlv", "0")); m_iVerteidigung = Integer.parseInt(properties.getProperty("bac", "0")); m_iSpielaufbau = Integer.parseInt(properties.getProperty("spe", "0")); m_iPasspiel = Integer.parseInt(properties.getProperty("fra", "0")); m_iFluegelspiel = Integer.parseInt(properties.getProperty("ytt", "0")); m_iTorschuss = Integer.parseInt(properties.getProperty("mal", "0")); m_iStandards = Integer.parseInt(properties.getProperty("fas", "0")); iPlayerSpecialty = Integer.parseInt(properties.getProperty("speciality", "0")); m_iCharakter = Integer.parseInt(properties.getProperty("gentleness", "0")); m_iAnsehen = Integer.parseInt(properties.getProperty("honesty", "0")); m_iAgressivitaet = Integer.parseInt(properties.getProperty("aggressiveness", "0")); m_iErfahrung = Integer.parseInt(properties.getProperty("rut", "0")); m_bHomeGrown = Boolean.parseBoolean(properties.getProperty("homegr", "FALSE")); m_iLoyalty = Integer.parseInt(properties.getProperty("loy", "0")); m_iFuehrung = Integer.parseInt(properties.getProperty("led", "0")); m_iGehalt = Integer.parseInt(properties.getProperty("sal", "0")); m_iNationalitaet = Integer.parseInt(properties.getProperty("countryid", "0")); m_iTSI = Integer.parseInt(properties.getProperty("mkt", "0")); // also read subskills when importing hrf from hattrickportal.pro/ useful for U20/NT m_dSubFluegelspiel = Double.parseDouble(properties.getProperty("yttsub", "0")); m_dSubPasspiel = Double.parseDouble(properties.getProperty("frasub", "0")); m_dSubSpielaufbau = Double.parseDouble(properties.getProperty("spesub", "0")); m_dSubStandards = Double.parseDouble(properties.getProperty("fassub", "0")); m_dSubTorschuss = Double.parseDouble(properties.getProperty("malsub", "0")); m_dSubTorwart = Double.parseDouble(properties.getProperty("mlvsub", "0")); m_dSubVerteidigung = Double.parseDouble(properties.getProperty("bacsub", "0")); subExperience = Double.parseDouble(properties.getProperty("experiencesub", "0")); //TSI, alles vorher durch 1000 teilen m_clhrfDate = hrfdate; if (hrfdate.isBefore(HODateTime.fromDbTimestamp(DBManager.TSIDATE))) { m_iTSI /= 1000d; } m_iCards = Integer.parseInt(properties.getProperty("warnings", "0")); m_iInjuryWeeks = Integer.parseInt(properties.getProperty("ska", "0")); m_iToreFreund = Integer.parseInt(properties.getProperty("gtt", "0")); m_iToreLiga = Integer.parseInt(properties.getProperty("gtl", "0")); m_iTorePokal = Integer.parseInt(properties.getProperty("gtc", "0")); m_iToreGesamt = Integer.parseInt(properties.getProperty("gev", "0")); m_iHattrick = Integer.parseInt(properties.getProperty("hat", "0")); m_iGoalsCurrentTeam = Integer.parseInt(properties.getProperty("goalscurrentteam", "0")); matchesCurrentTeam = Integer.parseInt(properties.getProperty("matchescurrentteam", "0")); if (properties.get("rating") != null) { m_iBewertung = Integer.parseInt(properties.getProperty("rating", "0")); } String temp = properties.getProperty("trainertype", "-1"); if ((temp != null) && !temp.equals("")) { m_iTrainerTyp = TrainerType.fromInt(Integer.parseInt(temp)); } temp = properties.getProperty("trainerskill", "0"); if ((temp != null) && !temp.equals("")) { m_iTrainer = Integer.parseInt(temp); } temp = properties.getProperty("playernumber", ""); if ((temp != null) && !temp.equals("") && !temp.equals("null")) { shirtNumber = Integer.parseInt(temp); } m_iTransferlisted = Boolean.parseBoolean(properties.getProperty("transferlisted", "False")) ? 1 : 0; m_iLaenderspiele = Integer.parseInt(properties.getProperty("caps", "0")); m_iU20Laenderspiele = Integer.parseInt(properties.getProperty("capsU20", "0")); nationalTeamId = Integer.parseInt(properties.getProperty("nationalTeamID", "0")); // #461-lastmatch m_lastMatchDate = properties.getProperty("lastmatch_date"); if (m_lastMatchDate != null && !m_lastMatchDate.isEmpty()) { m_lastMatchId = Integer.parseInt(properties.getProperty("lastmatch_id", "0")); lastMatchPosition = Integer.parseInt(properties.getProperty("lastmatch_positioncode", "-1")); lastMatchMinutes = Integer.parseInt(properties.getProperty("lastmatch_playedminutes", "0")); // rating is stored as number of half stars m_lastMatchRating = (int) (2 * Double.parseDouble(properties.getProperty("lastmatch_rating", "0"))); lastMatchRatingEndOfGame = (int) (2 * Double.parseDouble(properties.getProperty("lastmatch_ratingendofgame", "0"))); } setLastMatchType(MatchType.getById( Integer.parseInt(properties.getProperty("lastmatch_type", "0")) )); playerCategory = PlayerCategory.valueOf(Integer.parseInt(properties.getProperty("playercategoryid", "0"))); playerStatement = properties.getProperty("statement", ""); ownerNotes = properties.getProperty("ownernotes", ""); //Subskills calculation //Called when saving the HRF because the necessary data is not available here final core.model.HOModel oldmodel = core.model.HOVerwaltung.instance().getModel(); final Player oldPlayer = oldmodel.getCurrentPlayer(m_iSpielerID); if (oldPlayer != null) { // Training blocked (could be done in the past) m_bTrainingBlock = oldPlayer.hasTrainingBlock(); motherclubId = oldPlayer.getMotherclubId(); motherclubName = oldPlayer.getMotherclubName(); } } public String getMotherclubName() { downloadMotherclubInfoIfMissing(); return this.motherclubName; } public Integer getMotherclubId() { downloadMotherclubInfoIfMissing(); return this.motherclubId; } private void downloadMotherclubInfoIfMissing() { if (motherclubId == null) { var connection = MyConnector.instance(); var isSilentDownload = connection.isSilentDownload(); try { connection.setSilentDownload(true); // try to download missing motherclub info var playerDetails = OnlineWorker.downloadPlayerDetails(this.getPlayerID()); if (playerDetails != null) { motherclubId = playerDetails.getMotherclubId(); motherclubName = playerDetails.getMotherclubName(); } } catch (Exception e){ HOLogger.instance().warning(getClass(), "mother club not available for player " + this.getFullName()); } finally { connection.setSilentDownload(isSilentDownload); // reset } } } //~ Methods ------------------------------------------------------------------------------------ /** * Setter for property m_iAgressivitaet. * * @param m_iAgressivitaet New value of property m_iAgressivitaet. */ public void setAgressivitaet(int m_iAgressivitaet) { this.m_iAgressivitaet = m_iAgressivitaet; } /** * Getter for property m_iAgressivitaet. * * @return Value of property m_iAgressivitaet. */ public int getAgressivitaet() { return m_iAgressivitaet; } /** * Setter for property m_iAlter. * * @param m_iAlter New value of property m_iAlter. */ public void setAge(int m_iAlter) { this.m_iAlter = m_iAlter; } /** * Getter for property m_iAlter. * * @return Value of property m_iAlter. */ public int getAlter() { return m_iAlter; } /** * Setter for property m_iAgeDays. * * @param m_iAgeDays New value of property m_iAgeDays. */ public void setAgeDays(int m_iAgeDays) { this.m_iAgeDays = m_iAgeDays; } /** * Getter for property m_iAgeDays. * * @return Value of property m_iAgeDays. */ public int getAgeDays() { return m_iAgeDays; } /** * Calculates full age with days and offset * * @return Double value of age & agedays & offset combined, * i.e. age + (agedays+offset)/112 */ public double getAlterWithAgeDays() { var now = HODateTime.now(); return getDoubleAgeFromDate(now); } /** * Calculates full age with days and offset for a given timestamp * used to sort columns * pay attention that it takes the hour and minute of the matchtime into account * if you only want the days between two days use method calendarDaysBetween(Calendar start, Calendar end) * * @return Double value of age & agedays & offset combined, * i.e. age + (agedays+offset)/112 */ public double getDoubleAgeFromDate(HODateTime t) { var hrfTime = HOVerwaltung.instance().getModel().getBasics().getDatum(); var diff = Duration.between(hrfTime.instant, t.instant); int years = getAlter(); int days = getAgeDays(); return years + (double) (days + diff.toDays()) / 112; } /** * Calculates String for full age and days correcting for the difference between (now and last HRF file) * * @return String of age & agedays format is "YY (DDD)" */ public String getAgeWithDaysAsString() { return getAgeWithDaysAsString(HODateTime.now()); } public String getAgeWithDaysAsString(HODateTime t){ return getAgeWithDaysAsString(this.getAlter(), this.getAgeDays(), t, this.m_clhrfDate); } /** * Calculates the player's age at date referencing the current hrf download * @param ageYears int player's age in years in current hrf download * @param ageDays int additional days * @param time HODateTime for which the player's age should be calculated * @return String */ public static String getAgeWithDaysAsString(int ageYears, int ageDays, HODateTime time) { return getAgeWithDaysAsString(ageYears, ageDays,time, HOVerwaltung.instance().getModel().getBasics().getDatum()); } /** * Calculates the player's age at date referencing the given hrf date * @param ageYears int player's age in years at reference time * @param ageDays int additional days * @param time HODateTime for which the player's age should be calculated * @param hrfTime HODateTime reference date, when player's age was given * @return String */ public static String getAgeWithDaysAsString(int ageYears, int ageDays, HODateTime time, HODateTime hrfTime) { var age = new HODateTime.HODuration(ageYears, ageDays).plus(HODateTime.HODuration.between(hrfTime, time)); return age.seasons + " (" + age.days + ")"; } /** * Get the full i18n'd string representing the player's age. Includes * the birthday indicator as well. * * @return the full i18n'd string representing the player's age */ public String getAgeStringFull() { var hrfTime = HOVerwaltung.instance().getModel().getBasics().getDatum(); var oldAge = new HODateTime.HODuration(this.getAlter(), this.getAgeDays()); var age = oldAge.plus(HODateTime.HODuration.between(hrfTime, HODateTime.now())); var birthday = oldAge.seasons != age.seasons; StringBuilder ret = new StringBuilder(); ret.append(age.seasons); ret.append(" "); ret.append(HOVerwaltung.instance().getLanguageString("ls.player.age.years")); ret.append(" "); ret.append(age.days); ret.append(" "); ret.append(HOVerwaltung.instance().getLanguageString("ls.player.age.days")); if (birthday) { ret.append(" ("); ret.append(HOVerwaltung.instance().getLanguageString("ls.player.age.birthday")); ret.append(")"); } return ret.toString(); } /** * Setter for property m_iAnsehen. * * @param m_iAnsehen New value of property m_iAnsehen. */ public void setAnsehen(int m_iAnsehen) { this.m_iAnsehen = m_iAnsehen; } /** * Getter for property m_iAnsehen. * * @return Value of property m_iAnsehen. */ public int getAnsehen() { return m_iAnsehen; } /** * Setter for property m_iBewertung. * * @param m_iBewertung New value of property m_iBewertung. */ public void setBewertung(int m_iBewertung) { this.m_iBewertung = m_iBewertung; } /** * Getter for property m_iBewertung. * * @return Value of property m_iBewertung. */ public int getRating() { return m_iBewertung; } /** * Getter for property m_iBonus. * * @return Value of property m_iBonus. */ public int getBonus() { int bonus = 0; if (m_iNationalitaet != HOVerwaltung.instance().getModel().getBasics().getLand()) { bonus = 20; } return bonus; } /** * Setter for property m_iCharakter. * * @param m_iCharakter New value of property m_iCharakter. */ public void setCharakter(int m_iCharakter) { this.m_iCharakter = m_iCharakter; } public String getArrivalDate() { return m_arrivalDate; } public void setArrivalDate(String m_arrivalDate) { this.m_arrivalDate = m_arrivalDate; } /** * Getter for property m_iCharackter. * * @return Value of property m_iCharackter. */ public int getCharakter() { return m_iCharakter; } /** * Setter for property m_iErfahrung. * * @param m_iErfahrung New value of property m_iErfahrung. */ public void setExperience(int m_iErfahrung) { this.m_iErfahrung = m_iErfahrung; } /** * Getter for property m_iErfahrung. * * @return Value of property m_iErfahrung. */ public int getExperience() { return m_iErfahrung; } /** * Setter for property m_iFluegelspiel. * * @param m_iFluegelspiel New value of property m_iFluegelspiel. */ public void setFluegelspiel(int m_iFluegelspiel) { this.m_iFluegelspiel = m_iFluegelspiel; } /** * Getter for property m_iFluegelspiel. * * @return Value of property m_iFluegelspiel. */ public int getWIskill() { return m_iFluegelspiel; } /** * Setter for property m_iForm. * * @param m_iForm New value of property m_iForm. */ public void setForm(int m_iForm) { this.m_iForm = m_iForm; } /** * Getter for property m_iForm. * * @return Value of property m_iForm. */ public int getForm() { return m_iForm; } /** * Setter for property m_iFuehrung. * * @param m_iFuehrung New value of property m_iFuehrung. */ public void setLeadership(int m_iFuehrung) { this.m_iFuehrung = m_iFuehrung; } /** * Getter for property m_iFuehrung. * * @return Value of property m_iFuehrung. */ public int getLeadership() { return m_iFuehrung; } /** * Setter for property m_iGehalt. * * @param m_iGehalt New value of property m_iGehalt. */ public void setGehalt(int m_iGehalt) { this.m_iGehalt = m_iGehalt; } /** * Getter for property m_iGehalt. * * @return Value of property m_iGehalt. */ public int getSalary() { return m_iGehalt; } /** * Setter for property m_iGelbeKarten. * * @param m_iGelbeKarten New value of property m_iGelbeKarten. */ public void setGelbeKarten(int m_iGelbeKarten) { this.m_iCards = m_iGelbeKarten; } /** * Getter for property m_iGelbeKarten. * * @return Value of property m_iGelbeKarten. */ public int getCards() { return m_iCards; } /** * gibt an ob der spieler gesperrt ist */ public boolean isRedCarded() { return (m_iCards > 2); } public void setHattrick(int m_iHattrick) { this.m_iHattrick = m_iHattrick; } public int getHattrick() { return m_iHattrick; } public int getGoalsCurrentTeam() { return m_iGoalsCurrentTeam; } public void setGoalsCurrentTeam(int m_iGoalsCurrentTeam) { this.m_iGoalsCurrentTeam = m_iGoalsCurrentTeam; } /** * Setter for m_bHomeGrown * */ public void setHomeGrown(boolean hg) { m_bHomeGrown = hg; } /** * Getter for m_bHomeGrown * * @return Value of property m_bHomeGrown */ public boolean isHomeGrown() { return m_bHomeGrown; } public HODateTime getHrfDate() { if ( m_clhrfDate == null){ m_clhrfDate = HOVerwaltung.instance().getModel().getBasics().getDatum(); } return m_clhrfDate; } public void setHrfDate(HODateTime timestamp) { m_clhrfDate = timestamp; } public void setHrfDate() { setHrfDate(HODateTime.now()); } /** * calculate the contribution for the ideal position */ public float getIdealPositionStrength(boolean mitForm, @Nullable Weather weather, boolean useWeatherImpact) { return getIdealPositionStrength(mitForm, false, weather, useWeatherImpact); } /** * calculate the contribution for the ideal position */ public float getIdealPositionStrength(boolean mitForm, boolean normalized, @Nullable Weather weather, boolean useWeatherImpact) { return getIdealPositionStrength(mitForm, normalized, 2, weather, useWeatherImpact); } /** * calculate the contribution for the ideal position */ public float getIdealPositionStrength(boolean mitForm, boolean normalized, int nb_decimal, @Nullable Weather weather, boolean useWeatherImpact) { return calcPosValue(getIdealPosition(), mitForm, normalized, nb_decimal, weather, useWeatherImpact); } /** * Calculate Player Ideal Position (weather impact not relevant here) */ public byte getIdealPosition() { //in case player best position is forced by user final int flag = getUserPosFlag(); if (flag == IMatchRoleID.UNKNOWN) { if (idealPos == IMatchRoleID.UNKNOWN) { final FactorObject[] allPos = FormulaFactors.instance().getAllObj(); float maxStk = -1.0f; byte currPosition; float contrib; for (int i = 0; (allPos != null) && (i < allPos.length); i++) { if (allPos[i].getPosition() == IMatchRoleID.FORWARD_DEF_TECH) continue; currPosition = allPos[i].getPosition(); contrib = calcPosValue(currPosition, true, true, null, false); if (contrib > maxStk) { maxStk = contrib; idealPos = currPosition; } } } return idealPos; } return (byte)flag; } /** * Calculate Player Alternative Best Positions (weather impact not relevant here) */ public byte[] getAlternativeBestPositions() { List<PositionContribute> positions = new ArrayList<>(); final FactorObject[] allPos = FormulaFactors.instance().getAllObj(); byte currPosition; PositionContribute currPositionContribute; for (int i = 0; (allPos != null) && (i < allPos.length); i++) { if (allPos[i].getPosition() == IMatchRoleID.FORWARD_DEF_TECH) continue; currPosition = allPos[i].getPosition(); currPositionContribute = new PositionContribute(calcPosValue(currPosition, true, true, null, false), currPosition); positions.add(currPositionContribute); } positions.sort((PositionContribute player1, PositionContribute player2) -> Float.compare(player2.getRating(), player1.getRating())); byte[] alternativePositions = new byte[positions.size()]; float tolerance = 1f - core.model.UserParameter.instance().alternativePositionsTolerance; int i; final float threshold = positions.get(0).getRating() * tolerance; for (i = 0; i < positions.size(); i++) { if (positions.get(i).getRating() >= threshold) { alternativePositions[i] = positions.get(i).getClPostionID(); } else { break; } } alternativePositions = Arrays.copyOf(alternativePositions, i); return alternativePositions; } /** * return whether or not the position is one of the best position for the player */ public boolean isAnAlternativeBestPosition(byte position){ return Arrays.asList(getAlternativeBestPositions()).contains(position); } /** * Setter for property m_iKondition. * * @param m_iKondition New value of property m_iKondition. */ public void setStamina(int m_iKondition) { this.m_iKondition = m_iKondition; } //////////////////////////////////////////////////////////////////////////////// //Accessor //////////////////////////////////////////////////////////////////////////////// /** * Getter for property m_iKondition. * * @return Value of property m_iKondition. */ public int getStamina() { return m_iKondition; } /** * Setter for property m_iLaenderspiele. * * @param m_iLaenderspiele New value of property m_iLaenderspiele. */ public void setLaenderspiele(int m_iLaenderspiele) { this.m_iLaenderspiele = m_iLaenderspiele; } /** * Getter for property m_iLaenderspiele. * * @return Value of property m_iLaenderspiele. */ public int getLaenderspiele() { return m_iLaenderspiele; } private final HashMap<Integer, Skillup> lastSkillups = new HashMap<>(); /** * liefert das Datum des letzen LevelAufstiegs für den angeforderten Skill [0] = Time der * Änderung [1] = Boolean: false=Keine Änderung gefunden */ public Skillup getLastLevelUp(int skill) { if ( lastSkillups.containsKey(skill)){ return lastSkillups.get(skill); } var ret = DBManager.instance().getLastLevelUp(skill, m_iSpielerID); lastSkillups.put(skill, ret); return ret; } private final HashMap<Integer, List<Skillup> > allSkillUps = new HashMap<>(); /** * gives information of skill ups */ public List<Skillup> getAllLevelUp(int skill) { if ( allSkillUps.containsKey(skill)) { return allSkillUps.get(skill); } var ret = DBManager.instance().getAllLevelUp(skill, m_iSpielerID); allSkillUps.put(skill, ret); return ret; } public void resetSkillUpInformation() { lastSkillups.clear(); allSkillUps.clear(); } /** * Returns the loyalty stat */ public int getLoyalty() { return m_iLoyalty; } /** * Sets the loyalty stat */ public void setLoyalty(int loy) { m_iLoyalty = loy; } /** * Setter for property m_sManuellerSmilie. * * @param manuellerSmilie New value of property m_sManuellerSmilie. */ public void setManuellerSmilie(java.lang.String manuellerSmilie) { getNotes().setManuelSmilie(manuellerSmilie); DBManager.instance().storePlayerNotes(notes); } /** * Getter for property m_sManuellerSmilie. * * @return Value of property m_sManuellerSmilie. */ public java.lang.String getInfoSmiley() { return getNotes().getManuelSmilie(); } /** * Sets the TSI * * @param m_iTSI New value of property m_iMarkwert. */ public void setTSI(int m_iTSI) { this.m_iTSI = m_iTSI; } /** * Returns the TSI * * @return Value of property m_iMarkwert. */ public int getTSI() { return m_iTSI; } public void setFirstName(java.lang.String m_sName) { if ( m_sName != null ) this.m_sFirstName = m_sName; else m_sFirstName = ""; } public java.lang.String getFirstName() { return m_sFirstName; } public void setNickName(java.lang.String m_sName) { if ( m_sName != null ) this.m_sNickName = m_sName; else m_sNickName = ""; } public java.lang.String getNickName() { return m_sNickName; } public void setLastName(java.lang.String m_sName) { if (m_sName != null ) this.m_sLastName = m_sName; else this.m_sLastName = ""; } public java.lang.String getLastName() { return m_sLastName; } /** * Getter for shortName * eg: James Bond = J. Bond * Nickname are ignored */ public String getShortName() { if (getFirstName().isEmpty()) { return getLastName(); } return getFirstName().charAt(0) + ". " + getLastName(); } public java.lang.String getFullName() { if (getNickName().isEmpty()) { return getFirstName() + " " +getLastName(); } return getFirstName() + " '" + getNickName() + "' " +getLastName(); } /** * Setter for property m_iNationalitaet. * * @param m_iNationalitaet New value of property m_iNationalitaet. */ public void setNationalityAsInt(int m_iNationalitaet) { this.m_iNationalitaet = m_iNationalitaet; } /** * Getter for property m_iNationalitaet. * * @return Value of property m_iNationalitaet. */ public int getNationalityAsInt() { return m_iNationalitaet; } public String getNationalityAsString() { if (m_sNationality != null){ return m_sNationality; } WorldDetailLeague leagueDetail = WorldDetailsManager.instance().getWorldDetailLeagueByCountryId(m_iNationalitaet); if ( leagueDetail != null ) { m_sNationality = leagueDetail.getCountryName(); } else{ m_sNationality = ""; } return m_sNationality; } /** * Setter for property m_bOld. * * @param m_bOld New value of property m_bOld. */ public void setOld(boolean m_bOld) { this.m_bOld = m_bOld; } /** * Getter for property m_bOld. * * @return Value of property m_bOld. */ public boolean isOld() { return m_bOld; } /** * Setter for property m_iPasspiel. * * @param m_iPasspiel New value of property m_iPasspiel. */ public void setPasspiel(int m_iPasspiel) { this.m_iPasspiel = m_iPasspiel; } /** * Getter for property m_iPasspiel. * * @return Value of property m_iPasspiel. */ public int getPSskill() { return m_iPasspiel; } /** * Zum speichern! Die Reduzierung des Marktwerts auf TSI wird rückgängig gemacht */ public int getMarktwert() { if (m_clhrfDate == null || m_clhrfDate.isBefore(HODateTime.fromDbTimestamp(DBManager.TSIDATE))) { //Echter Marktwert return m_iTSI * 1000; } //TSI return m_iTSI; } String latestTSIInjured; String latestTSINotInjured; public String getLatestTSINotInjured(){ if (latestTSINotInjured == null){ latestTSINotInjured = DBManager.instance().loadLatestTSINotInjured(m_iSpielerID); } return latestTSINotInjured; } public String getLatestTSIInjured(){ if (latestTSIInjured == null){ latestTSIInjured = DBManager.instance().loadLatestTSIInjured(m_iSpielerID); } return latestTSIInjured; } /** * Setter for property iPlayerSpecialty. * * @param iPlayerSpecialty New value of property iPlayerSpecialty. */ public void setPlayerSpecialty(int iPlayerSpecialty) { this.iPlayerSpecialty = iPlayerSpecialty; } /** * Getter for property iPlayerSpecialty. * * @return Value of property iPlayerSpecialty. */ public int getPlayerSpecialty() { return iPlayerSpecialty; } public boolean hasSpeciality(Speciality speciality) { Speciality s = Speciality.values()[iPlayerSpecialty]; return s.equals(speciality); } // returns the name of the speciality in the used language public String getSpecialityName() { Speciality s = Speciality.values()[iPlayerSpecialty]; if (s.equals(Speciality.NO_SPECIALITY)) { return EMPTY; } else { return HOVerwaltung.instance().getLanguageString("ls.player.speciality." + s.toString().toLowerCase(Locale.ROOT)); } } // return the name of the speciality with a break before and in brackets // e.g. [br][quick], used for HT-ML export public String getSpecialityExportName() { Speciality s = Speciality.values()[iPlayerSpecialty]; if (s.equals(Speciality.NO_SPECIALITY)) { return EMPTY; } else { return BREAK + O_BRACKET + getSpecialityName() + C_BRACKET; } } // no break so that the export looks better public String getSpecialityExportNameForKeeper() { Speciality s = Speciality.values()[iPlayerSpecialty]; if (s.equals(Speciality.NO_SPECIALITY)) { return EMPTY; } else { return O_BRACKET + getSpecialityName() + C_BRACKET; } } /** * Setter for property m_iSpielaufbau. * * @param m_iSpielaufbau New value of property m_iSpielaufbau. */ public void setSpielaufbau(int m_iSpielaufbau) { this.m_iSpielaufbau = m_iSpielaufbau; } /** * Getter for property m_iSpielaufbau. * * @return Value of property m_iSpielaufbau. */ public int getPMskill() { return m_iSpielaufbau; } /** * set whether or not that player can be selected by the assistant */ public void setCanBeSelectedByAssistant(boolean flag) { getNotes().setEligibleToPlay(flag); DBManager.instance().storePlayerNotes(notes); } /** * get whether or not that player can be selected by the assistant */ public boolean getCanBeSelectedByAssistant() { return getNotes().isEligibleToPlay(); } /** * Setter for property m_iSpielerID. * * @param m_iSpielerID New value of property m_iSpielerID. */ public void setPlayerID(int m_iSpielerID) { this.m_iSpielerID = m_iSpielerID; } /** * Getter for property m_iSpielerID. * * @return Value of property m_iSpielerID. */ public int getPlayerID() { return m_iSpielerID; } /** * Setter for property m_iStandards. * * @param m_iStandards New value of property m_iStandards. */ public void setStandards(int m_iStandards) { this.m_iStandards = m_iStandards; } /** * Getter for property m_iStandards. * * @return Value of property m_iStandards. */ public int getSPskill() { return m_iStandards; } /** * berechnet den Subskill pro position */ public float getSub4Skill(int skill) { return Math.min(0.99f, Helper.round(getSub4SkillAccurate(skill), 2)); } public float getSkill(int iSkill, boolean inclSubSkill) { if(inclSubSkill) { return getValue4Skill(iSkill) + getSub4Skill(iSkill); } else{ return getValue4Skill(iSkill); } } /** * Returns accurate subskill number. If you need subskill for UI * purpose it is better to use getSubskill4Pos() * * @param skill skill number * @return subskill between 0.0-0.999 */ public float getSub4SkillAccurate(int skill) { double value = switch (skill) { case KEEPER -> m_dSubTorwart; case PLAYMAKING -> m_dSubSpielaufbau; case DEFENDING -> m_dSubVerteidigung; case PASSING -> m_dSubPasspiel; case WINGER -> m_dSubFluegelspiel; case SCORING -> m_dSubTorschuss; case SET_PIECES -> m_dSubStandards; case EXPERIENCE -> subExperience; default -> 0; }; return (float) Math.min(0.999, value); } public void setSubskill4PlayerSkill(int skill, float value) { switch (skill) { case KEEPER -> m_dSubTorwart = value; case PLAYMAKING -> m_dSubSpielaufbau = value; case DEFENDING -> m_dSubVerteidigung = value; case PASSING -> m_dSubPasspiel = value; case WINGER -> m_dSubFluegelspiel = value; case SCORING -> m_dSubTorschuss = value; case SET_PIECES -> m_dSubStandards = value; case EXPERIENCE -> subExperience = value; } } /** * Setter for property m_sTeamInfoSmilie. * * @param teamInfoSmilie New value of property m_sTeamInfoSmilie. */ public void setTeamInfoSmilie(String teamInfoSmilie) { getNotes().setTeamInfoSmilie(teamInfoSmilie); DBManager.instance().storePlayerNotes(notes); } /** * Getter for property m_sTeamInfoSmilie. * * @return Value of property m_sTeamInfoSmilie. */ public String getTeamGroup() { var ret = getNotes().getTeamInfoSmilie(); return ret.replaceAll("\\.png$", ""); } /** * Setter for property m_iToreFreund. * * @param m_iToreFreund New value of property m_iToreFreund. */ public void setToreFreund(int m_iToreFreund) { this.m_iToreFreund = m_iToreFreund; } /** * Getter for property m_iToreFreund. * * @return Value of property m_iToreFreund. */ public int getToreFreund() { return m_iToreFreund; } /** * Setter for property m_iToreGesamt. * * @param m_iToreGesamt New value of property m_iToreGesamt. */ public void setAllOfficialGoals(int m_iToreGesamt) { this.m_iToreGesamt = m_iToreGesamt; } /** * Getter for property m_iToreGesamt. * * @return Value of property m_iToreGesamt. */ public int getAllOfficialGoals() { return m_iToreGesamt; } /** * Setter for property m_iToreLiga. * * @param m_iToreLiga New value of property m_iToreLiga. */ public void setToreLiga(int m_iToreLiga) { this.m_iToreLiga = m_iToreLiga; } /** * Getter for property m_iToreLiga. * * @return Value of property m_iToreLiga. */ public int getSeasonSeriesGoal() { return m_iToreLiga; } /** * Setter for property m_iTorePokal. * * @param m_iTorePokal New value of property m_iTorePokal. */ public void setTorePokal(int m_iTorePokal) { this.m_iTorePokal = m_iTorePokal; } /** * Getter for property m_iTorePokal. * * @return Value of property m_iTorePokal. */ public int getSeasonCupGoal() { return m_iTorePokal; } /** * Setter for property m_iTorschuss. * * @param m_iTorschuss New value of property m_iTorschuss. */ public void setTorschuss(int m_iTorschuss) { this.m_iTorschuss = m_iTorschuss; } /** * Getter for property m_iTorschuss. * * @return Value of property m_iTorschuss. */ public int getSCskill() { return m_iTorschuss; } /** * Setter for property m_iTorwart. * * @param m_iTorwart New value of property m_iTorwart. */ public void setTorwart(int m_iTorwart) { this.m_iTorwart = m_iTorwart; } /** * Getter for property m_iTorwart. * * @return Value of property m_iTorwart. */ public int getGKskill() { return m_iTorwart; } /** * Setter for property m_iTrainer. * * @param m_iTrainer New value of property m_iTrainer. */ public void setTrainerSkill(Integer m_iTrainer) { this.m_iTrainer = m_iTrainer; } /** * Getter for property m_iTrainer. * * @return Value of property m_iTrainer. */ public int getTrainerSkill() { return m_iTrainer; } /** * gibt an ob der Player Trainer ist */ public boolean isTrainer() { return m_iTrainer > 0 && m_iTrainerTyp != null; } /** * Setter for property m_iTrainerTyp. * * @param m_iTrainerTyp New value of property m_iTrainerTyp. */ public void setTrainerTyp(TrainerType m_iTrainerTyp) { this.m_iTrainerTyp = m_iTrainerTyp; } /** * Getter for property m_iTrainerTyp. * * @return Value of property m_iTrainerTyp. */ public TrainerType getTrainerTyp() { return m_iTrainerTyp; } /** * Last match * @return date */ public String getLastMatchDate(){ return m_lastMatchDate; } /** * Last match * @return rating */ public Integer getLastMatchRating(){ return m_lastMatchRating; } /** * Last match id * @return id */ public Integer getLastMatchId(){ return m_lastMatchId; } /** * Returns the {@link MatchType} of the last match. */ public MatchType getLastMatchType() { return lastMatchType; } /** * Sets the value of <code>lastMatchType</code> to <code>matchType</code>. */ public void setLastMatchType(MatchType matchType) { this.lastMatchType = matchType; } /** * Setter for property m_iTransferlisted. * * @param m_iTransferlisted New value of property m_iTransferlisted. */ public void setTransferlisted(int m_iTransferlisted) { this.m_iTransferlisted = m_iTransferlisted; } /** * Getter for property m_iTransferlisted. * * @return Value of property m_iTransferlisted. */ public int getTransferlisted() { return m_iTransferlisted; } /** * Setter for property m_iTrikotnummer. * * @param m_iTrikotnummer New value of property m_iTrikotnummer. */ public void setShirtNumber(int m_iTrikotnummer) { this.shirtNumber = m_iTrikotnummer; } /** * Getter for property m_iTrikotnummer. * * @return Value of property m_iTrikotnummer. */ public int getTrikotnummer() { return shirtNumber; } /** * Setter for property m_iU20Laenderspiele. * * @param m_iU20Laenderspiele New value of property m_iU20Laenderspiele. */ public void setU20Laenderspiele(int m_iU20Laenderspiele) { this.m_iU20Laenderspiele = m_iU20Laenderspiele; } /** * Getter for property m_iU20Laenderspiele. * * @return Value of property m_iU20Laenderspiele. */ public int getU20Laenderspiele() { return m_iU20Laenderspiele; } public void setHrfId(int hrf_id) { this.hrf_id=hrf_id; } public int getHrfId() { return this.hrf_id; } public void setLastMatchDate(String v) { this.m_lastMatchDate = v; } public void setLastMatchRating(Integer v) { this.m_lastMatchRating=v; } public void setLastMatchId(Integer v) { this.m_lastMatchId = v; } public Integer getHtms28() { if ( htms28 == null){ htms28 = Htms.htms28(getSkills(), this.m_iAlter, this.m_iAgeDays); } return htms28; } public Integer getHtms(){ if (htms == null){ htms= Htms.htms(getSkills()); } return htms; } private Map<Integer, Integer> getSkills() { var ret = new HashMap<Integer, Integer>(); ret.put(KEEPER, getGKskill()); ret.put(DEFENDING, getDEFskill()); ret.put(PLAYMAKING, getPMskill()); ret.put(WINGER, getWIskill()); ret.put(PASSING, getPSskill()); ret.put(SCORING, getSCskill()); ret.put(SET_PIECES, getSPskill()); return ret; } public static class Notes extends AbstractTable.Storable{ public Notes(){} private int playerId; public Notes(int playerId) { this.playerId = playerId; } public int getUserPos() { return userPos; } private int userPos = IMatchRoleID.UNKNOWN; public String getManuelSmilie() { return manuelSmilie; } public String getNote() { return note; } public boolean isEligibleToPlay() { return eligibleToPlay; } public String getTeamInfoSmilie() { return teamInfoSmilie; } public boolean isFired() { return isFired; } private String manuelSmilie=""; private String note=""; private boolean eligibleToPlay=true; private String teamInfoSmilie=""; private boolean isFired=false; public void setPlayerId(int playerId) { this.playerId=playerId; } public void setNote(String note) { this.note=note; } public void setEligibleToPlay(boolean spielberechtigt) { this.eligibleToPlay=spielberechtigt; } public void setTeamInfoSmilie(String teamInfoSmilie) { this.teamInfoSmilie=teamInfoSmilie; } public void setManuelSmilie(String manuellerSmilie) { this.manuelSmilie=manuellerSmilie; } public void setUserPos(int userPos) { this.userPos=userPos; } public void setIsFired(boolean isFired) { this.isFired=isFired; } public int getPlayerId() { return this.playerId; } } private Notes notes; private Notes getNotes(){ if ( notes==null){ notes = DBManager.instance().loadPlayerNotes(this.getPlayerID()); } return notes; } public void setUserPosFlag(byte flag) { getNotes().setUserPos(flag); DBManager.instance().storePlayerNotes(notes); this.setCanBeSelectedByAssistant(flag != IMatchRoleID.UNSELECTABLE); } public void setIsFired(boolean b) { getNotes().setIsFired(b); DBManager.instance().storePlayerNotes(notes); } public boolean isFired() { return getNotes().isFired(); } /** * liefert User Notiz zum Player */ public int getUserPosFlag() { return getNotes().getUserPos(); } public String getNote() {return getNotes().getNote();} public void setNote(String text) { getNotes().setNote(text); DBManager.instance().storePlayerNotes(notes); } /** * get Skillvalue 4 skill */ public int getValue4Skill(int skill) { return switch (skill) { case KEEPER -> m_iTorwart; case PLAYMAKING -> m_iSpielaufbau; case DEFENDING -> m_iVerteidigung; case PASSING -> m_iPasspiel; case WINGER -> m_iFluegelspiel; case SCORING -> m_iTorschuss; case SET_PIECES -> m_iStandards; case STAMINA -> m_iKondition; case EXPERIENCE -> m_iErfahrung; case FORM -> m_iForm; case LEADERSHIP -> m_iFuehrung; case LOYALTY -> m_iLoyalty; default -> 0; }; } public float getSkillValue(int skill){ return getSub4Skill(skill) + getValue4Skill(skill); } public void setSkillValue(int skill, float value){ int intVal = (int)value; setValue4Skill(skill, intVal); setSubskill4PlayerSkill(skill, value - intVal); } /** * set Skillvalue 4 skill * * @param skill the skill to change * @param value the new skill value */ public void setValue4Skill(int skill, int value) { switch (skill) { case KEEPER -> setTorwart(value); case PLAYMAKING -> setSpielaufbau(value); case PASSING -> setPasspiel(value); case WINGER -> setFluegelspiel(value); case DEFENDING -> setVerteidigung(value); case SCORING -> setTorschuss(value); case SET_PIECES -> setStandards(value); case STAMINA -> setStamina(value); case EXPERIENCE -> setExperience(value); case FORM -> setForm(value); case LEADERSHIP -> setLeadership(value); case LOYALTY -> setLoyalty(value); } } /** * Setter for property m_iVerletzt. * * @param m_iVerletzt New value of property m_iVerletzt. */ public void setInjuryWeeks(int m_iVerletzt) { this.m_iInjuryWeeks = m_iVerletzt; } /** * Getter for property m_iVerletzt. * * @return Value of property m_iVerletzt. */ public int getInjuryWeeks() { return m_iInjuryWeeks; } /** * Setter for property m_iVerteidigung. * * @param m_iVerteidigung New value of property m_iVerteidigung. */ public void setVerteidigung(int m_iVerteidigung) { this.m_iVerteidigung = m_iVerteidigung; } /** * Getter for property m_iVerteidigung. * * @return Value of property m_iVerteidigung. */ public int getDEFskill() { return m_iVerteidigung; } public float getImpactWeatherEffect(Weather weather) { return PlayerSpeciality.getImpactWeatherEffect(weather, iPlayerSpecialty); } /** * Calculates training effect for each skill * * @param train Trainingweek giving the matches that should be calculated * * @return TrainingPerPlayer */ public TrainingPerPlayer calculateWeeklyTraining(TrainingPerWeek train) { final int playerID = this.getPlayerID(); TrainingPerPlayer ret = new TrainingPerPlayer(this); ret.setTrainingWeek(train); if (train == null || train.getTrainingType() < 0) { return ret; } WeeklyTrainingType wt = WeeklyTrainingType.instance(train.getTrainingType()); if (wt != null) { try { var matches = train.getMatches(); int myID = HOVerwaltung.instance().getModel().getBasics().getTeamId(); TrainingWeekPlayer tp = new TrainingWeekPlayer(this); for (var match : matches) { var details = match.getMatchdetails(); if ( details != null ) { //Get the MatchLineup by id MatchLineupTeam mlt = details.getOwnTeamLineup(); if ( mlt != null) { MatchType type = mlt.getMatchType(); boolean walkoverWin = details.isWalkoverMatchWin(myID); if (type != MatchType.MASTERS) { // MASTERS counts only for experience tp.addFullTrainingMinutes(mlt.getTrainingMinutesPlayedInSectors(playerID, wt.getFullTrainingSectors(), walkoverWin)); tp.addBonusTrainingMinutes(mlt.getTrainingMinutesPlayedInSectors(playerID, wt.getBonusTrainingSectors(), walkoverWin)); tp.addPartlyTrainingMinutes(mlt.getTrainingMinutesPlayedInSectors(playerID, wt.getPartlyTrainingSectors(), walkoverWin)); tp.addOsmosisTrainingMinutes(mlt.getTrainingMinutesPlayedInSectors(playerID, wt.getOsmosisTrainingSectors(), walkoverWin)); } var minutes = mlt.getTrainingMinutesPlayedInSectors(playerID, null, walkoverWin); tp.addPlayedMinutes(minutes); ret.addExperience(match.getExperienceIncrease(min(90, minutes))); } else { HOLogger.instance().error(getClass(), "no lineup found in match " + match.getMatchSchedule().toLocaleDateTime() + " " + match.getHomeTeamName() + " - " + match.getGuestTeamName() ); } } } TrainingPoints trp = new TrainingPoints(wt, tp); // get experience increase of national team matches var id = this.getNationalTeamID(); if ( id != null && id != 0 && id != myID){ // TODO check if national matches are stored in database var nationalMatches = train.getNTmatches(); for (var match : nationalMatches){ MatchLineupTeam mlt = DBManager.instance().loadMatchLineupTeam(match.getMatchType().getId(), match.getMatchID(), this.getNationalTeamID()); var minutes = mlt.getTrainingMinutesPlayedInSectors(playerID, null, false); if ( minutes > 0 ) { ret.addExperience(match.getExperienceIncrease(min(90,minutes))); } } } ret.setTrainingPair(trp); } catch (Exception e) { HOLogger.instance().log(getClass(),e); } } return ret; } /** * Calculate the player strength on a specific lineup position * with or without form * * @param fo FactorObject with the skill weights for this position * @param useForm consider form? * @param normalized absolute or normalized contribution? * @return the player strength on this position */ float calcPosValue(FactorObject fo, boolean useForm, boolean normalized, @Nullable Weather weather, boolean useWeatherImpact) { if ((fo == null) || (fo.getSum() == 0.0f)) { return -1.0f; } // The stars formulas are changed by the user -> clear the cache if (!PlayerAbsoluteContributionCache.containsKey("lastChange") || ((Date) PlayerAbsoluteContributionCache.get("lastChange")).before(FormulaFactors.getLastChange())) { // System.out.println ("Clearing stars cache"); PlayerAbsoluteContributionCache.clear(); PlayerRelativeContributionCache.clear(); PlayerAbsoluteContributionCache.put("lastChange", new Date()); } /* * Create a key for the Hashtable cache * We cache every star rating to speed up calculation * (calling RPM.calcPlayerStrength() is quite expensive and this method is used very often) */ float loy = RatingPredictionManager.getLoyaltyHomegrownBonus(this); String key = fo.getPosition() + ":" + Helper.round(getGKskill() + getSub4Skill(KEEPER) + loy, 2) + "|" + Helper.round(getPMskill() + getSub4Skill(PLAYMAKING) + loy, 2) + "|" + Helper.round(getDEFskill() + getSub4Skill(DEFENDING) + loy, 2) + "|" + Helper.round(getWIskill() + getSub4Skill(WINGER) + loy, 2) + "|" + Helper.round(getPSskill() + getSub4Skill(PASSING) + loy, 2) + "|" + Helper.round(getSPskill() + getSub4Skill(SET_PIECES) + loy, 2) + "|" + Helper.round(getSCskill() + getSub4Skill(SCORING) + loy, 2) + "|" + getForm() + "|" + getStamina() + "|" + getExperience() + "|" + getPlayerSpecialty(); // used for Technical DefFW // Check if the key already exists in cache if (PlayerAbsoluteContributionCache.containsKey(key)) { // System.out.println ("Using star rating from cache, key="+key+", tablesize="+starRatingCache.size()); float rating = normalized ? (float) PlayerRelativeContributionCache.get(key) : (Float) PlayerAbsoluteContributionCache.get(key); if(useWeatherImpact){ rating *= getImpactWeatherEffect(weather); } return rating; } // Compute contribution float gkValue = fo.getGKfactor() * RatingPredictionManager.calcPlayerStrength(-2, this, KEEPER, useForm, false); float pmValue = fo.getPMfactor() * RatingPredictionManager.calcPlayerStrength(-2, this, PLAYMAKING, useForm, false); float deValue = fo.getDEfactor() * RatingPredictionManager.calcPlayerStrength(-2, this, DEFENDING, useForm, false); float wiValue = fo.getWIfactor() * RatingPredictionManager.calcPlayerStrength(-2, this, WINGER, useForm, false); float psValue = fo.getPSfactor() * RatingPredictionManager.calcPlayerStrength(-2, this, PASSING, useForm, false); float spValue = fo.getSPfactor() * RatingPredictionManager.calcPlayerStrength(-2, this, SET_PIECES, useForm, false); float scValue = fo.getSCfactor() * RatingPredictionManager.calcPlayerStrength(-2, this, SCORING, useForm, false); float val = gkValue + pmValue + deValue + wiValue + psValue + spValue + scValue; float absVal = val * 10; // multiplied by 10 for improved visibility float normVal = val / fo.getNormalizationFactor() * 100; // scaled between 0 and 100% // Put to cache PlayerAbsoluteContributionCache.put(key, absVal); PlayerRelativeContributionCache.put(key, normVal); // System.out.println ("Star rating put to cache, key="+key+", val="+val+", tablesize="+starRatingCache.size()); if (normalized) { return normVal; } else { return absVal; } } public float calcPosValue(byte pos, boolean useForm, boolean normalized, @Nullable Weather weather, boolean useWeatherImpact) { return calcPosValue(pos, useForm, normalized, core.model.UserParameter.instance().nbDecimals, weather, useWeatherImpact); } public float calcPosValue(byte pos, boolean useForm, @Nullable Weather weather, boolean useWeatherImpact) { return calcPosValue(pos, useForm, false, weather, useWeatherImpact); } /** * Calculate the player strength on a specific lineup position * with or without form * * @param pos position from IMatchRoleID (TORWART.. POS_ZUS_INNENV) * @param useForm consider form? * @return the player strength on this position */ public float calcPosValue(byte pos, boolean useForm, boolean normalized, int nb_decimals, @Nullable Weather weather, boolean useWeatherImpact) { float es; FactorObject factor = FormulaFactors.instance().getPositionFactor(pos); // Fix for TDF if (pos == IMatchRoleID.FORWARD_DEF && this.getPlayerSpecialty() == PlayerSpeciality.TECHNICAL) { factor = FormulaFactors.instance().getPositionFactor(IMatchRoleID.FORWARD_DEF_TECH); } if (factor != null) { es = calcPosValue(factor, useForm, normalized, weather, useWeatherImpact); } else { // For Coach or factor not found return 0 return 0.0f; } return core.util.Helper.round(es, nb_decimals); } /** * Copy the skills of old player. * Used by training * * @param old player to copy from */ public void copySkills(Player old) { for (int skillType = 0; skillType <= LOYALTY; skillType++) { setValue4Skill(skillType, old.getValue4Skill(skillType)); } } ////////////////////////////////////////////////////////////////////////////////// //equals ///////////////////////////////////////////////////////////////////////////////// @Override public boolean equals(Object obj) { boolean equals = false; if (obj instanceof Player) { equals = ((Player) obj).getPlayerID() == m_iSpielerID; } return equals; } /** * Does this player have a training block? * * @return training block */ public boolean hasTrainingBlock() { return m_bTrainingBlock; } /** * Set the training block of this player (true/false) * * @param isBlocked new value */ public void setTrainingBlock(boolean isBlocked) { this.m_bTrainingBlock = isBlocked; } public Integer getNationalTeamID() { return nationalTeamId; } public void setNationalTeamId( Integer id){ this.nationalTeamId=id; } public double getSubExperience() { return this.subExperience; } public void setSubExperience( Double experience){ if ( experience != null ) this.subExperience = experience; else this.subExperience=0; } public List<FuturePlayerTraining> getFuturePlayerTrainings(){ if ( futurePlayerTrainings == null){ futurePlayerTrainings = DBManager.instance().getFuturePlayerTrainings(this.getPlayerID()); if (futurePlayerTrainings.size()>0) { var start = HOVerwaltung.instance().getModel().getBasics().getHattrickWeek(); var remove = new ArrayList<FuturePlayerTraining>(); for (var t : futurePlayerTrainings) { if (t.endsBefore(start)){ remove.add(t); } } futurePlayerTrainings.removeAll(remove); } } return futurePlayerTrainings; } /** * Get the training priority of a hattrick week. If user training plan is given for the week this user selection is * returned. If no user plan is available, the training priority is determined by the player's best position. * * @param wt * used to get priority depending from the player's best position. * @param trainingDate * the training week * @return * the training priority */ public FuturePlayerTraining.Priority getTrainingPriority(WeeklyTrainingType wt, HODateTime trainingDate) { for ( var t : getFuturePlayerTrainings()) { if (t.contains(trainingDate)) { return t.getPriority(); } } // get Prio from best position int position = HelperWrapper.instance().getPosition(this.getIdealPosition()); for ( var p: wt.getTrainingSkillBonusPositions()){ if ( p == position) return FuturePlayerTraining.Priority.FULL_TRAINING; } for ( var p: wt.getTrainingSkillPositions()){ if ( p == position) { if ( wt.getTrainingType() == TrainingType.SET_PIECES) return FuturePlayerTraining.Priority.PARTIAL_TRAINING; return FuturePlayerTraining.Priority.FULL_TRAINING; } } for ( var p: wt.getTrainingSkillPartlyTrainingPositions()){ if ( p == position) return FuturePlayerTraining.Priority.PARTIAL_TRAINING; } for ( var p: wt.getTrainingSkillOsmosisTrainingPositions()){ if ( p == position) return FuturePlayerTraining.Priority.OSMOSIS_TRAINING; } return null; // No training } /** * Set training priority for a time interval. * Previously saved trainings of this interval are overwritten or deleted. * @param prio new training priority for the given time interval * @param from first week with new training priority * @param to last week with new training priority, null means open end */ public void setFutureTraining(FuturePlayerTraining.Priority prio, HODateTime from, HODateTime to) { var removeIntervals = new ArrayList<FuturePlayerTraining>(); for (var t : getFuturePlayerTrainings()) { if (t.cut(from, to) || t.cut(HODateTime.HT_START, HOVerwaltung.instance().getModel().getBasics().getHattrickWeek())) { removeIntervals.add(t); } } futurePlayerTrainings.removeAll(removeIntervals); if (prio != null) { futurePlayerTrainings.add(new FuturePlayerTraining(this.getPlayerID(), prio, from, to)); } DBManager.instance().storeFuturePlayerTrainings(futurePlayerTrainings); } public String getBestPositionInfo(@Nullable Weather weather, boolean useWeatherImpact) { return MatchRoleID.getNameForPosition(getIdealPosition()) + " (" + getIdealPositionStrength(true, true, 1, weather, useWeatherImpact) + "%)"; } /** * training priority information of the training panel * * @param nextWeek training priorities after this week will be considered * @return if there is one user selected priority, the name of the priority is returned * if there are more than one selected priorities, "individual priorities" is returned * if is no user selected priority, the best position information is returned */ public String getTrainingPriorityInformation(HODateTime nextWeek) { String ret=null; for ( var t : getFuturePlayerTrainings()) { // if ( !t.endsBefore(nextWeek)){ if ( ret != null ){ ret = HOVerwaltung.instance().getLanguageString("trainpre.individual.prios"); break; } ret = t.getPriority().toString(); } } if ( ret != null ) return ret; return getBestPositionInfo(null, false); } private static final int[] trainingSkills= { KEEPER, SET_PIECES, DEFENDING, SCORING, WINGER, PASSING, PLAYMAKING }; /** * Calculates skill status of the player * * @param previousID Id of the previous download. Previous player status is loaded by this id. * @param trainingWeeks List of training week information */ public void calcSubskills(int previousID, List<TrainingPerWeek> trainingWeeks) { var playerBefore = DBManager.instance().getSpieler(previousID).stream() .filter(i -> i.getPlayerID() == this.getPlayerID()).findFirst().orElse(null); if (playerBefore == null) { playerBefore = this.CloneWithoutSubskills(); } // since we don't want to work with temp player objects we calculate skill by skill // whereas experience is calculated within the first skill boolean experienceSubDone = this.getExperience() > playerBefore.getExperience(); // Do not calculate sub on experience skill up var experienceSub = experienceSubDone ? 0 : playerBefore.getSubExperience(); // set sub to 0 on skill up for (var skill : trainingSkills) { var sub = playerBefore.getSub4Skill(skill); var valueBeforeTraining = playerBefore.getValue4Skill(skill); var valueAfterTraining = this.getValue4Skill(skill); if (trainingWeeks.size() > 0) { for (var training : trainingWeeks) { var trainingPerPlayer = calculateWeeklyTraining(training); if (trainingPerPlayer != null) { if (!this.hasTrainingBlock()) {// player training is not blocked (blocking is no longer possible) sub += trainingPerPlayer.calcSubskillIncrement(skill, valueBeforeTraining + sub, training.getTrainingDate()); if (valueAfterTraining > valueBeforeTraining) { if (sub > 1) { sub -= 1.; } else { sub = 0.f; } } else if (valueAfterTraining < valueBeforeTraining) { if (sub < 0) { sub += 1.f; } else { sub = .99f; } } else { if (sub > 0.99f) { sub = 0.99f; } else if (sub < 0f) { sub = 0f; } } valueBeforeTraining = valueAfterTraining; } if (!experienceSubDone) { var inc = trainingPerPlayer.getExperienceSub(); experienceSub += inc; if (experienceSub > 0.99) experienceSub = 0.99; var minutes = 0; var tp =trainingPerPlayer.getTrainingPair(); if ( tp != null){ minutes = tp.getTrainingDuration().getPlayedMinutes(); } else { HOLogger.instance().warning(getClass(), "no training info found"); } HOLogger.instance().info(getClass(), "Training " + training.getTrainingDate().toLocaleDateTime() + "; Minutes= " + minutes + "; Experience increment of " + this.getFullName() + "; increment: " + inc + "; new sub value=" + experienceSub ); } } } experienceSubDone = true; } if (valueAfterTraining < valueBeforeTraining) { sub = .99f; } else if (valueAfterTraining > valueBeforeTraining) { sub = 0; HOLogger.instance().error(getClass(), "skill up without training"); // missing training in database } this.setSubskill4PlayerSkill(skill, sub); this.setSubExperience(experienceSub); } } private Player CloneWithoutSubskills() { var ret = new Player(); ret.setHrfId(this.hrf_id); ret.copySkills(this); ret.setPlayerID(getPlayerID()); ret.setAge(getAlter()); ret.setLastName(getLastName()); return ret; } public PlayerCategory getPlayerCategory() { return playerCategory; } public void setPlayerCategory(PlayerCategory playerCategory) { this.playerCategory = playerCategory; } public String getPlayerStatement() { return playerStatement; } public void setPlayerStatement(String playerStatement) { this.playerStatement = playerStatement; } public String getOwnerNotes() { return ownerNotes; } public void setOwnerNotes(String ownerNotes) { this.ownerNotes = ownerNotes; } public Integer getLastMatchPosition() { return lastMatchPosition; } public void setLastMatchPosition(Integer lastMatchPosition) { this.lastMatchPosition = lastMatchPosition; } public Integer getLastMatchMinutes() { return lastMatchMinutes; } public void setLastMatchMinutes(Integer lastMatchMinutes) { this.lastMatchMinutes = lastMatchMinutes; } /** * Rating at end of game * @return Integer number of half rating stars */ public Integer getLastMatchRatingEndOfGame() { return lastMatchRatingEndOfGame; } /** * Rating at end of game * @param lastMatchRatingEndOfGame number of half rating stars */ public void setLastMatchRatingEndOfGame(Integer lastMatchRatingEndOfGame) { this.lastMatchRatingEndOfGame = lastMatchRatingEndOfGame; } public void setMotherClubId(Integer teamID) { this.motherclubId = teamID; } public void setMotherClubName(String teamName) { this.motherclubName = teamName; } public void setMatchesCurrentTeam(Integer matchesCurrentTeam) { this.matchesCurrentTeam=matchesCurrentTeam; } public Integer getMatchesCurrentTeam() { return this.matchesCurrentTeam; } static class PositionContribute { private final float m_rating; private final byte clPositionID; public PositionContribute(float rating, byte clPostionID) { m_rating = rating; clPositionID = clPostionID; } public float getRating() { return m_rating; } public byte getClPostionID() { return clPositionID; } } /** * Create a clone of the player with modified skill values if man marking is switched on. * Values of Defending, Winger, Playmaking, Scoring and Passing are reduced depending of the distance * between man marker and opponent man marked player * * @param manMarkingPosition * null - no man marking changes * Opposite - reduce skills by 50% * NotOpposite - reduce skills by 65% * NotInLineup - reduce skills by 10% * @return * this player, if no man marking changes are selected * New modified player, if man marking changes are selected */ public Player createManMarker(ManMarkingPosition manMarkingPosition) { if ( manMarkingPosition == null) return this; var ret = new Player(); var skillFactor = (float)(1 - manMarkingPosition.value / 100.); ret.setPlayerSpecialty(this.getPlayerSpecialty()); ret.setAgeDays(this.getAgeDays()); ret.setAge(this.getAlter()); ret.setAgressivitaet(this.getAgressivitaet()); ret.setAnsehen(this.getAnsehen()); ret.setCharakter(this.getCharakter()); ret.setExperience(this.getExperience()); ret.setSubExperience(this.getSubExperience()); ret.setFirstName(this.getFirstName()); ret.setLastName(this.getLastName()); ret.setForm(this.getForm()); ret.setLeadership(this.getLeadership()); ret.setStamina(this.getStamina()); ret.setLoyalty(this.getLoyalty()); ret.setHomeGrown(this.isHomeGrown()); ret.setPlayerID(this.getPlayerID()); ret.setInjuryWeeks(this.getInjuryWeeks()); ret.setSkillValue(KEEPER, this.getSkillValue(KEEPER)); ret.setSkillValue(DEFENDING, skillFactor * this.getSkillValue(DEFENDING)); ret.setSkillValue(WINGER, skillFactor * this.getSkillValue(WINGER)); ret.setSkillValue(PLAYMAKING, skillFactor * this.getSkillValue(PLAYMAKING)); ret.setSkillValue(SCORING, skillFactor * this.getSkillValue(SCORING)); ret.setSkillValue(PASSING, skillFactor * this.getSkillValue(PASSING)); ret.setSkillValue(STAMINA, this.getSkillValue(STAMINA)); ret.setSkillValue(FORM, this.getSkillValue(FORM)); ret.setSkillValue(SET_PIECES, this.getSkillValue(SET_PIECES)); ret.setSkillValue(LEADERSHIP, this.getSkillValue(LEADERSHIP)); ret.setSkillValue(LOYALTY, this.getSkillValue(LOYALTY)); return ret; } public enum ManMarkingPosition { /** * central defender versus attack * wingback versus winger * central midfield versus central midfield */ Opposite(50), /** * central defender versus winger, central midfield * wingback versus attack, central midfield * central midfield versus central attack, winger */ NotOpposite(65), /** * opponent player is not in lineup or * any other combination */ NotInLineup(10); private final int value; ManMarkingPosition(int v){this.value=v;} public static ManMarkingPosition fromId(int id) { return switch (id) { case 50 -> Opposite; case 65 -> NotOpposite; case 10 -> NotInLineup; default -> null; }; } public int getValue() {return value;} } }
cmbarbu/HO
src/main/java/core/model/player/Player.java
214,389
package core.model.player; import core.constants.TrainingType; import core.constants.player.PlayerSpeciality; import core.constants.player.Speciality; import core.db.DBManager; import core.model.*; import core.model.match.MatchLineupTeam; import core.model.enums.MatchType; import core.model.match.Weather; import core.net.OnlineWorker; import core.rating.RatingPredictionManager; import core.training.*; import core.util.HODateTime; import core.util.HOLogger; import core.util.Helper; import core.util.HelperWrapper; import module.training.Skills; import org.jetbrains.annotations.Nullable; import java.time.Duration; import java.util.*; import static java.lang.Integer.min; import static core.constants.player.PlayerSkill.*; public class Player { /** * Cache for player contribution (Hashtable<String, Float>) */ private static Hashtable<String, Object> PlayerAbsoluteContributionCache = new Hashtable<>(); private static Hashtable<String, Object> PlayerRelativeContributionCache = new Hashtable<>(); private byte idealPos = IMatchRoleID.UNKNOWN; private static final String BREAK = "[br]"; private static final String O_BRACKET = "["; private static final String C_BRACKET = "]"; private static final String EMPTY = ""; /** * canPlay */ private Boolean m_bCanBeSelectedByAssistant; /** * Manual Smilie Filename */ private String m_sManuellerSmilie; /** * Name */ private String m_sFirstName = ""; private String m_sNickName = ""; private String m_sLastName = ""; /** * Arrival in team */ private String m_arrivalDate; /** * TeamInfo Smilie Filename */ private String m_sTeamInfoSmilie; /** * Download date */ private HODateTime m_clhrfDate; /** * The player is no longer available in the current HRF */ private boolean m_bOld; private byte m_bUserPosFlag = -2; /** * Wing skill */ private double m_dSubFluegelspiel; /** * Pass skill */ private double m_dSubPasspiel; /** * Playmaking skill */ private double m_dSubSpielaufbau; /** * Standards */ private double m_dSubStandards; /** * Goal */ private double m_dSubTorschuss; //Subskills private double m_dSubTorwart; /** * Verteidigung */ private double m_dSubVerteidigung; /** * Agressivität */ private int m_iAgressivitaet; /** * Alter */ private int m_iAlter; /** * Age Days */ private int m_iAgeDays; /** * Ansehen (ekel usw. ) */ private int m_iAnsehen = 1; /** * Bewertung */ private int m_iBewertung; /** * charakter ( ehrlich) */ private int m_iCharakter = 1; /** * Erfahrung */ private int m_iErfahrung = 1; /** * Fluegelspiel */ private int m_iFluegelspiel = 1; /** * Form */ private int m_iForm = 1; /** * Führungsqualität */ private int m_iFuehrung = 1; /** * Gehalt */ private int m_iGehalt = 1; /** * Gelbe Karten */ private int m_iCards; /** * Hattricks */ private int m_iHattrick; private int m_iGoalsCurrentTeam; /** * Home Grown */ private boolean m_bHomeGrown = false; /** * Kondition */ private int m_iKondition = 1; /** * Länderspiele */ private int m_iLaenderspiele; /** * Loyalty */ private int m_iLoyalty = 0; /** * Markwert */ private int m_iTSI; private String m_sNationality; /** * Aus welchem Land kommt der Player */ private int m_iNationalitaet = 49; /** * Passpiel */ private int m_iPasspiel = 1; /** * SpezialitätID */ private int iPlayerSpecialty; /** * Spielaufbau */ private int m_iSpielaufbau = 1; //////////////////////////////////////////////////////////////////////////////// //Member //////////////////////////////////////////////////////////////////////////////// /** * SpielerID */ private int m_iSpielerID; /** * Standards */ private int m_iStandards = 1; /** * Tore Freundschaftspiel */ private int m_iToreFreund; /** * Tore Gesamt */ private int m_iToreGesamt; /** * Tore Liga */ private int m_iToreLiga; /** * Tore Pokalspiel */ private int m_iTorePokal; /** * Torschuss */ private int m_iTorschuss = 1; /** * Torwart */ private int m_iTorwart = 1; /** * Trainerfähigkeit */ private int m_iTrainer; /** * Trainertyp */ private TrainerType m_iTrainerTyp; /** * Transferlisted */ private int m_iTransferlisted; /** * shirt number (can be edited in hattrick) */ private int shirtNumber = -1; /** * player's category (can be edited in hattrick) */ private PlayerCategory playerCategory; /** * player statement (can be edited in hattrick) */ private String playerStatement; /** * Owner notes (can be edited in hattrick) */ private String ownerNotes; /** * Länderspiele */ private int m_iU20Laenderspiele; /** * Verletzt Wochen */ private int m_iInjuryWeeks = -1; /** * Verteidigung */ private int m_iVerteidigung = 1; /** * Training block */ private boolean m_bTrainingBlock = false; /** * Last match */ private String m_lastMatchDate; private Integer m_lastMatchId; private MatchType lastMatchType; private Integer lastMatchPosition; private Integer lastMatchMinutes; // Rating is number of half stars // real rating value is rating/2.0f private Integer m_lastMatchRating; private Integer lastMatchRatingEndOfGame; /** * specifying at what time –in minutes- that player entered the field * This parameter is only used by RatingPredictionManager to calculate the stamina effect * along the course of the game */ private int GameStartingTime = 0; private Integer nationalTeamId; private double subExperience; /** * future training priorities planed by the user */ private List<FuturePlayerTraining> futurePlayerTrainings; private Integer motherclubId; private String motherclubName; private Integer matchesCurrentTeam; public int getGameStartingTime() { return GameStartingTime; } public void setGameStartingTime(int gameStartingTime) { GameStartingTime = gameStartingTime; } //~ Constructors ------------------------------------------------------------------------------- /** * Creates a new instance of Player */ public Player() { } /** * Erstellt einen Player aus den Properties einer HRF Datei */ public Player(java.util.Properties properties, HODateTime hrfdate) { // Separate first, nick and last names are available. Utilize them? m_iSpielerID = Integer.parseInt(properties.getProperty("id", "0")); m_sFirstName = properties.getProperty("firstname", ""); m_sNickName = properties.getProperty("nickname", ""); m_sLastName = properties.getProperty("lastname", ""); m_arrivalDate = properties.getProperty("arrivaldate"); m_iAlter = Integer.parseInt(properties.getProperty("ald", "0")); m_iAgeDays = Integer.parseInt(properties.getProperty("agedays", "0")); m_iKondition = Integer.parseInt(properties.getProperty("uth", "0")); m_iForm = Integer.parseInt(properties.getProperty("for", "0")); m_iTorwart = Integer.parseInt(properties.getProperty("mlv", "0")); m_iVerteidigung = Integer.parseInt(properties.getProperty("bac", "0")); m_iSpielaufbau = Integer.parseInt(properties.getProperty("spe", "0")); m_iPasspiel = Integer.parseInt(properties.getProperty("fra", "0")); m_iFluegelspiel = Integer.parseInt(properties.getProperty("ytt", "0")); m_iTorschuss = Integer.parseInt(properties.getProperty("mal", "0")); m_iStandards = Integer.parseInt(properties.getProperty("fas", "0")); iPlayerSpecialty = Integer.parseInt(properties.getProperty("speciality", "0")); m_iCharakter = Integer.parseInt(properties.getProperty("gentleness", "0")); m_iAnsehen = Integer.parseInt(properties.getProperty("honesty", "0")); m_iAgressivitaet = Integer.parseInt(properties.getProperty("aggressiveness", "0")); m_iErfahrung = Integer.parseInt(properties.getProperty("rut", "0")); m_bHomeGrown = Boolean.parseBoolean(properties.getProperty("homegr", "FALSE")); m_iLoyalty = Integer.parseInt(properties.getProperty("loy", "0")); m_iFuehrung = Integer.parseInt(properties.getProperty("led", "0")); m_iGehalt = Integer.parseInt(properties.getProperty("sal", "0")); m_iNationalitaet = Integer.parseInt(properties.getProperty("countryid", "0")); m_iTSI = Integer.parseInt(properties.getProperty("mkt", "0")); // also read subskills when importing hrf from hattrickportal.pro/ useful for U20/NT m_dSubFluegelspiel = Double.parseDouble(properties.getProperty("yttsub", "0")); m_dSubPasspiel = Double.parseDouble(properties.getProperty("frasub", "0")); m_dSubSpielaufbau = Double.parseDouble(properties.getProperty("spesub", "0")); m_dSubStandards = Double.parseDouble(properties.getProperty("fassub", "0")); m_dSubTorschuss = Double.parseDouble(properties.getProperty("malsub", "0")); m_dSubTorwart = Double.parseDouble(properties.getProperty("mlvsub", "0")); m_dSubVerteidigung = Double.parseDouble(properties.getProperty("bacsub", "0")); subExperience = Double.parseDouble(properties.getProperty("experiencesub", "0")); //TSI, alles vorher durch 1000 teilen m_clhrfDate = hrfdate; if (hrfdate.isBefore(HODateTime.fromDbTimestamp(DBManager.TSIDATE))) { m_iTSI /= 1000d; } m_iCards = Integer.parseInt(properties.getProperty("warnings", "0")); m_iInjuryWeeks = Integer.parseInt(properties.getProperty("ska", "0")); m_iToreFreund = Integer.parseInt(properties.getProperty("gtt", "0")); m_iToreLiga = Integer.parseInt(properties.getProperty("gtl", "0")); m_iTorePokal = Integer.parseInt(properties.getProperty("gtc", "0")); m_iToreGesamt = Integer.parseInt(properties.getProperty("gev", "0")); m_iHattrick = Integer.parseInt(properties.getProperty("hat", "0")); m_iGoalsCurrentTeam = Integer.parseInt(properties.getProperty("goalscurrentteam", "0")); matchesCurrentTeam = Integer.parseInt(properties.getProperty("matchescurrentteam", "0")); if (properties.get("rating") != null) { m_iBewertung = Integer.parseInt(properties.getProperty("rating", "0")); } String temp = properties.getProperty("trainertype", "-1"); if ((temp != null) && !temp.equals("")) { m_iTrainerTyp = TrainerType.fromInt(Integer.parseInt(temp)); } temp = properties.getProperty("trainerskill", "0"); if ((temp != null) && !temp.equals("")) { m_iTrainer = Integer.parseInt(temp); } temp = properties.getProperty("playernumber", ""); if ((temp != null) && !temp.equals("") && !temp.equals("null")) { shirtNumber = Integer.parseInt(temp); } m_iTransferlisted = Boolean.parseBoolean(properties.getProperty("transferlisted", "False")) ? 1 : 0; m_iLaenderspiele = Integer.parseInt(properties.getProperty("caps", "0")); m_iU20Laenderspiele = Integer.parseInt(properties.getProperty("capsU20", "0")); nationalTeamId = Integer.parseInt(properties.getProperty("nationalTeamID", "0")); // #461-lastmatch m_lastMatchDate = properties.getProperty("lastmatch_date"); if (m_lastMatchDate != null && !m_lastMatchDate.isEmpty()) { m_lastMatchId = Integer.parseInt(properties.getProperty("lastmatch_id", "0")); lastMatchPosition = Integer.parseInt(properties.getProperty("lastmatch_positioncode", "-1")); lastMatchMinutes = Integer.parseInt(properties.getProperty("lastmatch_playedminutes", "0")); // rating is stored as number of half stars m_lastMatchRating = (int) (2 * Double.parseDouble(properties.getProperty("lastmatch_rating", "0"))); lastMatchRatingEndOfGame = (int) (2 * Double.parseDouble(properties.getProperty("lastmatch_ratingendofgame", "0"))); } setLastMatchType(MatchType.getById( Integer.parseInt(properties.getProperty("lastmatch_type", "0")) )); playerCategory = PlayerCategory.valueOf(Integer.parseInt(properties.getProperty("playercategoryid", "0"))); playerStatement = properties.getProperty("statement", ""); ownerNotes = properties.getProperty("ownernotes", ""); //Subskills calculation //Called when saving the HRF because the necessary data is not available here final core.model.HOModel oldmodel = core.model.HOVerwaltung.instance().getModel(); final Player oldPlayer = oldmodel.getCurrentPlayer(m_iSpielerID); if (oldPlayer != null) { // Training blocked (could be done in the past) m_bTrainingBlock = oldPlayer.hasTrainingBlock(); motherclubId = oldPlayer.getMotherclubId(); motherclubName = oldPlayer.getMotherclubName(); if (motherclubId == null) { var playerDetails = OnlineWorker.downloadPlayerDetails(this.getPlayerID()); if (playerDetails != null) { motherclubId = playerDetails.getMotherclubId(); motherclubName = playerDetails.getMotherclubName(); } } } } public String getMotherclubName() { return this.motherclubName; } public Integer getMotherclubId() { return this.motherclubId; } //~ Methods ------------------------------------------------------------------------------------ /** * Setter for property m_iAgressivitaet. * * @param m_iAgressivitaet New value of property m_iAgressivitaet. */ public void setAgressivitaet(int m_iAgressivitaet) { this.m_iAgressivitaet = m_iAgressivitaet; } /** * Getter for property m_iAgressivitaet. * * @return Value of property m_iAgressivitaet. */ public int getAgressivitaet() { return m_iAgressivitaet; } /** * gives information of skill ups * returns vector of * object[] * [0] = date of skill up * [1] = Boolean: false=no skill up found * [2] = skill value */ public Vector<Object[]> getAllLevelUp(int skill) { return DBManager.instance().getAllLevelUp(skill, m_iSpielerID); } /** * Setter for property m_iAlter. * * @param m_iAlter New value of property m_iAlter. */ public void setAge(int m_iAlter) { this.m_iAlter = m_iAlter; } /** * Getter for property m_iAlter. * * @return Value of property m_iAlter. */ public int getAlter() { return m_iAlter; } /** * Setter for property m_iAgeDays. * * @param m_iAgeDays New value of property m_iAgeDays. */ public void setAgeDays(int m_iAgeDays) { this.m_iAgeDays = m_iAgeDays; } /** * Getter for property m_iAgeDays. * * @return Value of property m_iAgeDays. */ public int getAgeDays() { return m_iAgeDays; } /** * Calculates full age with days and offset * * @return Double value of age & agedays & offset combined, * i.e. age + (agedays+offset)/112 */ public double getAlterWithAgeDays() { var now = HODateTime.now(); return getDoubleAgeFromDate(now); } /** * Calculates full age with days and offset for a given timestamp * used to sort columns * pay attention that it takes the hour and minute of the matchtime into account * if you only want the days between two days use method calendarDaysBetween(Calendar start, Calendar end) * * @return Double value of age & agedays & offset combined, * i.e. age + (agedays+offset)/112 */ public double getDoubleAgeFromDate(HODateTime t) { var hrfTime = HOVerwaltung.instance().getModel().getBasics().getDatum(); var diff = Duration.between(hrfTime.instant, t.instant); int years = getAlter(); int days = getAgeDays(); return years + (double) (days + diff.toDays()) / 112; } /** * Calculates String for full age and days correcting for the difference between (now and last HRF file) * * @return String of age & agedays format is "YY (DDD)" */ public String getAgeWithDaysAsString() { return getAgeWithDaysAsString(HODateTime.now()); } public String getAgeWithDaysAsString(HODateTime t){ return getAgeWithDaysAsString(this.getAlter(), this.getAgeDays(), t); } public static String getAgeWithDaysAsString(int ageYears, int ageDays, HODateTime time) { var hrfTime = HOVerwaltung.instance().getModel().getBasics().getDatum(); var between = HODateTime.HODuration.between(hrfTime, time); if ( between.seasons>=0 && between.days >=0 ) { var age = new HODateTime.HODuration(ageYears, ageDays).plus(HODateTime.HODuration.between(hrfTime, time)); return age.seasons + " (" + age.days + ")"; } // Should not happen (computer might have wrong time settings) return ageYears + " (" + ageDays + ")"; } /** * Get the full i18n'd string representing the player's age. Includes * the birthday indicator as well. * * @return the full i18n'd string representing the player's age */ public String getAgeStringFull() { var hrfTime = HOVerwaltung.instance().getModel().getBasics().getDatum(); var oldAge = new HODateTime.HODuration(this.getAlter(), this.getAgeDays()); var age = oldAge.plus(HODateTime.HODuration.between(hrfTime, HODateTime.now())); var birthday = oldAge.seasons != age.seasons; StringBuilder ret = new StringBuilder(); ret.append(age.seasons); ret.append(" "); ret.append(HOVerwaltung.instance().getLanguageString("ls.player.age.years")); ret.append(" "); ret.append(age.days); ret.append(" "); ret.append(HOVerwaltung.instance().getLanguageString("ls.player.age.days")); if (birthday) { ret.append(" ("); ret.append(HOVerwaltung.instance().getLanguageString("ls.player.age.birthday")); ret.append(")"); } return ret.toString(); } /** * Setter for property m_iAnsehen. * * @param m_iAnsehen New value of property m_iAnsehen. */ public void setAnsehen(int m_iAnsehen) { this.m_iAnsehen = m_iAnsehen; } /** * Getter for property m_iAnsehen. * * @return Value of property m_iAnsehen. */ public int getAnsehen() { return m_iAnsehen; } /** * Setter for property m_iBewertung. * * @param m_iBewertung New value of property m_iBewertung. */ public void setBewertung(int m_iBewertung) { this.m_iBewertung = m_iBewertung; } /** * Getter for property m_iBewertung. * * @return Value of property m_iBewertung. */ public int getRating() { return m_iBewertung; } /** * Getter for property m_iBonus. * * @return Value of property m_iBonus. */ public int getBonus() { int bonus = 0; if (m_iNationalitaet != HOVerwaltung.instance().getModel().getBasics().getLand()) { bonus = 20; } return bonus; } /** * Setter for property m_iCharakter. * * @param m_iCharakter New value of property m_iCharakter. */ public void setCharakter(int m_iCharakter) { this.m_iCharakter = m_iCharakter; } public String getArrivalDate() { return m_arrivalDate; } public void setArrivalDate(String m_arrivalDate) { this.m_arrivalDate = m_arrivalDate; } /** * Getter for property m_iCharackter. * * @return Value of property m_iCharackter. */ public int getCharakter() { return m_iCharakter; } /** * Setter for property m_iErfahrung. * * @param m_iErfahrung New value of property m_iErfahrung. */ public void setExperience(int m_iErfahrung) { this.m_iErfahrung = m_iErfahrung; } /** * Getter for property m_iErfahrung. * * @return Value of property m_iErfahrung. */ public int getExperience() { return m_iErfahrung; } /** * Setter for property m_iFluegelspiel. * * @param m_iFluegelspiel New value of property m_iFluegelspiel. */ public void setFluegelspiel(int m_iFluegelspiel) { this.m_iFluegelspiel = m_iFluegelspiel; } /** * Getter for property m_iFluegelspiel. * * @return Value of property m_iFluegelspiel. */ public int getWIskill() { return m_iFluegelspiel; } /** * Setter for property m_iForm. * * @param m_iForm New value of property m_iForm. */ public void setForm(int m_iForm) { this.m_iForm = m_iForm; } /** * Getter for property m_iForm. * * @return Value of property m_iForm. */ public int getForm() { return m_iForm; } /** * Setter for property m_iFuehrung. * * @param m_iFuehrung New value of property m_iFuehrung. */ public void setLeadership(int m_iFuehrung) { this.m_iFuehrung = m_iFuehrung; } /** * Getter for property m_iFuehrung. * * @return Value of property m_iFuehrung. */ public int getLeadership() { return m_iFuehrung; } /** * Setter for property m_iGehalt. * * @param m_iGehalt New value of property m_iGehalt. */ public void setGehalt(int m_iGehalt) { this.m_iGehalt = m_iGehalt; } /** * Getter for property m_iGehalt. * * @return Value of property m_iGehalt. */ public int getSalary() { return m_iGehalt; } /** * Setter for property m_iGelbeKarten. * * @param m_iGelbeKarten New value of property m_iGelbeKarten. */ public void setGelbeKarten(int m_iGelbeKarten) { this.m_iCards = m_iGelbeKarten; } /** * Getter for property m_iGelbeKarten. * * @return Value of property m_iGelbeKarten. */ public int getCards() { return m_iCards; } /** * gibt an ob der spieler gesperrt ist */ public boolean isRedCarded() { return (m_iCards > 2); } public void setHattrick(int m_iHattrick) { this.m_iHattrick = m_iHattrick; } public int getHattrick() { return m_iHattrick; } public int getGoalsCurrentTeam() { return m_iGoalsCurrentTeam; } public void setGoalsCurrentTeam(int m_iGoalsCurrentTeam) { this.m_iGoalsCurrentTeam = m_iGoalsCurrentTeam; } /** * Setter for m_bHomeGrown * */ public void setHomeGrown(boolean hg) { m_bHomeGrown = hg; } /** * Getter for m_bHomeGrown * * @return Value of property m_bHomeGrown */ public boolean isHomeGrown() { return m_bHomeGrown; } public HODateTime getHrfDate() { if ( m_clhrfDate == null){ m_clhrfDate = HOVerwaltung.instance().getModel().getBasics().getDatum(); } return m_clhrfDate; } public void setHrfDate(HODateTime timestamp) { m_clhrfDate = timestamp; } public void setHrfDate() { setHrfDate(HODateTime.now()); } /** * calculate the contribution for the ideal position */ public float getIdealPositionStrength(boolean mitForm, @Nullable Weather weather, boolean useWeatherImpact) { return getIdealPositionStrength(mitForm, false, weather, useWeatherImpact); } /** * calculate the contribution for the ideal position */ public float getIdealPositionStrength(boolean mitForm, boolean normalized, @Nullable Weather weather, boolean useWeatherImpact) { return getIdealPositionStrength(mitForm, normalized, 2, weather, useWeatherImpact); } /** * calculate the contribution for the ideal position */ public float getIdealPositionStrength(boolean mitForm, boolean normalized, int nb_decimal, @Nullable Weather weather, boolean useWeatherImpact) { return calcPosValue(getIdealPosition(), mitForm, normalized, nb_decimal, weather, useWeatherImpact); } /** * Calculate Player Ideal Position (weather impact not relevant here) */ public byte getIdealPosition() { //in case player best position is forced by user final byte flag = getUserPosFlag(); if (flag == IMatchRoleID.UNKNOWN) { if (idealPos == IMatchRoleID.UNKNOWN) { final FactorObject[] allPos = FormulaFactors.instance().getAllObj(); float maxStk = -1.0f; byte currPosition; float contrib; for (int i = 0; (allPos != null) && (i < allPos.length); i++) { if (allPos[i].getPosition() == IMatchRoleID.FORWARD_DEF_TECH) continue; currPosition = allPos[i].getPosition(); contrib = calcPosValue(currPosition, true, true, null, false); if (contrib > maxStk) { maxStk = contrib; idealPos = currPosition; } } } return idealPos; } return flag; } /** * Calculate Player Alternative Best Positions (weather impact not relevant here) */ public byte[] getAlternativeBestPositions() { List<PositionContribute> positions = new ArrayList<>(); final FactorObject[] allPos = FormulaFactors.instance().getAllObj(); byte currPosition; PositionContribute currPositionContribute; for (int i = 0; (allPos != null) && (i < allPos.length); i++) { if (allPos[i].getPosition() == IMatchRoleID.FORWARD_DEF_TECH) continue; currPosition = allPos[i].getPosition(); currPositionContribute = new PositionContribute(calcPosValue(currPosition, true, true, null, false), currPosition); positions.add(currPositionContribute); } positions.sort((PositionContribute player1, PositionContribute player2) -> Float.compare(player2.getRating(), player1.getRating())); byte[] alternativePositions = new byte[positions.size()]; float tolerance = 1f - core.model.UserParameter.instance().alternativePositionsTolerance; int i; final float threshold = positions.get(0).getRating() * tolerance; for (i = 0; i < positions.size(); i++) { if (positions.get(i).getRating() >= threshold) { alternativePositions[i] = positions.get(i).getClPostionID(); } else { break; } } alternativePositions = Arrays.copyOf(alternativePositions, i); return alternativePositions; } /** * return whether or not the position is one of the best position for the player */ public boolean isAnAlternativeBestPosition(byte position){ return Arrays.asList(getAlternativeBestPositions()).contains(position); } /** * Setter for property m_iKondition. * * @param m_iKondition New value of property m_iKondition. */ public void setStamina(int m_iKondition) { this.m_iKondition = m_iKondition; } //////////////////////////////////////////////////////////////////////////////// //Accessor //////////////////////////////////////////////////////////////////////////////// /** * Getter for property m_iKondition. * * @return Value of property m_iKondition. */ public int getStamina() { return m_iKondition; } /** * Setter for property m_iLaenderspiele. * * @param m_iLaenderspiele New value of property m_iLaenderspiele. */ public void setLaenderspiele(int m_iLaenderspiele) { this.m_iLaenderspiele = m_iLaenderspiele; } /** * Getter for property m_iLaenderspiele. * * @return Value of property m_iLaenderspiele. */ public int getLaenderspiele() { return m_iLaenderspiele; } /** * liefert das Datum des letzen LevelAufstiegs für den angeforderten Skill [0] = Time der * Änderung [1] = Boolean: false=Keine Änderung gefunden */ public Object[] getLastLevelUp(int skill) { return DBManager.instance().getLastLevelUp(skill, m_iSpielerID); } /** * Returns the loyalty stat */ public int getLoyalty() { return m_iLoyalty; } /** * Sets the loyalty stat */ public void setLoyalty(int loy) { m_iLoyalty = loy; } /** * Setter for property m_sManuellerSmilie. * * @param manuellerSmilie New value of property m_sManuellerSmilie. */ public void setManuellerSmilie(java.lang.String manuellerSmilie) { if (manuellerSmilie == null) { manuellerSmilie = ""; } m_sManuellerSmilie = manuellerSmilie; DBManager.instance().saveManuellerSmilie(m_iSpielerID, manuellerSmilie); } /** * Getter for property m_sManuellerSmilie. * * @return Value of property m_sManuellerSmilie. */ public java.lang.String getInfoSmiley() { if (m_sManuellerSmilie == null) { m_sManuellerSmilie = DBManager.instance().getManuellerSmilie(m_iSpielerID); //Steht null in der DB? if (m_sManuellerSmilie == null) { m_sManuellerSmilie = ""; } } //database.DBZugriff.instance ().getManuellerSmilie( m_iSpielerID ); return m_sManuellerSmilie; } /** * Sets the TSI * * @param m_iTSI New value of property m_iMarkwert. */ public void setTSI(int m_iTSI) { this.m_iTSI = m_iTSI; } /** * Returns the TSI * * @return Value of property m_iMarkwert. */ public int getTSI() { return m_iTSI; } public void setFirstName(java.lang.String m_sName) { this.m_sFirstName = m_sName; } public java.lang.String getFirstName() { return DBManager.deleteEscapeSequences(m_sFirstName); } public void setNickName(java.lang.String m_sName) { this.m_sNickName = m_sName; } public java.lang.String getNickName() { return DBManager.deleteEscapeSequences(m_sNickName); } public void setLastName(java.lang.String m_sName) { this.m_sLastName = m_sName; } public java.lang.String getLastName() { return DBManager.deleteEscapeSequences(m_sLastName); } /** * Getter for shortName * eg: James Bond = J. Bond * Nickname are ignored */ public String getShortName() { if (getFirstName().isEmpty()) { return getLastName(); } return getFirstName().charAt(0) + ". " + getLastName(); } public java.lang.String getFullName() { if (getNickName().isEmpty()) { return getFirstName() + " " +getLastName(); } return getFirstName() + " '" + getNickName() + "' " +getLastName(); } /** * Setter for property m_iNationalitaet. * * @param m_iNationalitaet New value of property m_iNationalitaet. */ public void setNationalityAsInt(int m_iNationalitaet) { this.m_iNationalitaet = m_iNationalitaet; } /** * Getter for property m_iNationalitaet. * * @return Value of property m_iNationalitaet. */ public int getNationalityAsInt() { return m_iNationalitaet; } public String getNationalityAsString() { if (m_sNationality != null){ return m_sNationality; } WorldDetailLeague leagueDetail = WorldDetailsManager.instance().getWorldDetailLeagueByCountryId(m_iNationalitaet); if ( leagueDetail != null ) { m_sNationality = leagueDetail.getCountryName(); } else{ m_sNationality = ""; } return m_sNationality; } /** * Setter for property m_bOld. * * @param m_bOld New value of property m_bOld. */ public void setOld(boolean m_bOld) { this.m_bOld = m_bOld; } /** * Getter for property m_bOld. * * @return Value of property m_bOld. */ public boolean isOld() { return m_bOld; } /** * Setter for property m_iPasspiel. * * @param m_iPasspiel New value of property m_iPasspiel. */ public void setPasspiel(int m_iPasspiel) { this.m_iPasspiel = m_iPasspiel; } /** * Getter for property m_iPasspiel. * * @return Value of property m_iPasspiel. */ public int getPSskill() { return m_iPasspiel; } /** * Zum speichern! Die Reduzierung des Marktwerts auf TSI wird rückgängig gemacht */ public int getSaveMarktwert() { if (m_clhrfDate == null || m_clhrfDate.isBefore(HODateTime.fromDbTimestamp(DBManager.TSIDATE))) { //Echter Marktwert return m_iTSI * 1000; } //TSI return m_iTSI; } /** * Setter for property iPlayerSpecialty. * * @param iPlayerSpecialty New value of property iPlayerSpecialty. */ public void setPlayerSpecialty(int iPlayerSpecialty) { this.iPlayerSpecialty = iPlayerSpecialty; } /** * Getter for property iPlayerSpecialty. * * @return Value of property iPlayerSpecialty. */ public int getPlayerSpecialty() { return iPlayerSpecialty; } public boolean hasSpeciality(Speciality speciality) { Speciality s = Speciality.values()[iPlayerSpecialty]; return s.equals(speciality); } // returns the name of the speciality in the used language public String getSpecialityName() { Speciality s = Speciality.values()[iPlayerSpecialty]; if (s.equals(Speciality.NO_SPECIALITY)) { return EMPTY; } else { return HOVerwaltung.instance().getLanguageString("ls.player.speciality." + s.toString().toLowerCase(Locale.ROOT)); } } // return the name of the speciality with a break before and in brackets // e.g. [br][quick], used for HT-ML export public String getSpecialityExportName() { Speciality s = Speciality.values()[iPlayerSpecialty]; if (s.equals(Speciality.NO_SPECIALITY)) { return EMPTY; } else { return BREAK + O_BRACKET + getSpecialityName() + C_BRACKET; } } // no break so that the export looks better public String getSpecialityExportNameForKeeper() { Speciality s = Speciality.values()[iPlayerSpecialty]; if (s.equals(Speciality.NO_SPECIALITY)) { return EMPTY; } else { return O_BRACKET + getSpecialityName() + C_BRACKET; } } /** * Setter for property m_iSpielaufbau. * * @param m_iSpielaufbau New value of property m_iSpielaufbau. */ public void setSpielaufbau(int m_iSpielaufbau) { this.m_iSpielaufbau = m_iSpielaufbau; } /** * Getter for property m_iSpielaufbau. * * @return Value of property m_iSpielaufbau. */ public int getPMskill() { return m_iSpielaufbau; } /** * set whether or not that player can be selected by the assistant */ public void setCanBeSelectedByAssistant(boolean flag) { m_bCanBeSelectedByAssistant = flag; DBManager.instance().saveSpielerSpielberechtigt(m_iSpielerID, flag); } /** * get whether or not that player can be selected by the assistant */ public boolean getCanBeSelectedByAssistant() { //Only check if not authorized to play: Reduced access! if (m_bCanBeSelectedByAssistant == null) { m_bCanBeSelectedByAssistant = DBManager.instance().getSpielerSpielberechtigt(m_iSpielerID); } return m_bCanBeSelectedByAssistant; } /** * Setter for property m_iSpielerID. * * @param m_iSpielerID New value of property m_iSpielerID. */ public void setPlayerID(int m_iSpielerID) { this.m_iSpielerID = m_iSpielerID; } /** * Getter for property m_iSpielerID. * * @return Value of property m_iSpielerID. */ public int getPlayerID() { return m_iSpielerID; } /** * Setter for property m_iStandards. * * @param m_iStandards New value of property m_iStandards. */ public void setStandards(int m_iStandards) { this.m_iStandards = m_iStandards; } /** * Getter for property m_iStandards. * * @return Value of property m_iStandards. */ public int getSPskill() { return m_iStandards; } /** * berechnet den Subskill pro position */ public float getSub4Skill(int skill) { return Math.min(0.99f, Helper.round(getSub4SkillAccurate(skill), 2)); } public float getSkill(int iSkill, boolean inclSubSkill) { if(inclSubSkill) { return getValue4Skill(iSkill) + getSub4Skill(iSkill); } else{ return getValue4Skill(iSkill); } } /** * Returns accurate subskill number. If you need subskill for UI * purpose it is better to use getSubskill4Pos() * * @param skill skill number * @return subskill between 0.0-0.999 */ public float getSub4SkillAccurate(int skill) { double value = switch (skill) { case KEEPER -> m_dSubTorwart; case PLAYMAKING -> m_dSubSpielaufbau; case DEFENDING -> m_dSubVerteidigung; case PASSING -> m_dSubPasspiel; case WINGER -> m_dSubFluegelspiel; case SCORING -> m_dSubTorschuss; case SET_PIECES -> m_dSubStandards; case EXPERIENCE -> subExperience; default -> 0; }; return (float) Math.min(0.999, value); } public void setSubskill4PlayerSkill(int skill, float value) { switch (skill) { case KEEPER -> m_dSubTorwart = value; case PLAYMAKING -> m_dSubSpielaufbau = value; case DEFENDING -> m_dSubVerteidigung = value; case PASSING -> m_dSubPasspiel = value; case WINGER -> m_dSubFluegelspiel = value; case SCORING -> m_dSubTorschuss = value; case SET_PIECES -> m_dSubStandards = value; case EXPERIENCE -> subExperience = value; } } /** * Setter for property m_sTeamInfoSmilie. * * @param teamInfoSmilie New value of property m_sTeamInfoSmilie. */ public void setTeamInfoSmilie(String teamInfoSmilie) { if (teamInfoSmilie == null) { teamInfoSmilie = ""; } m_sTeamInfoSmilie = teamInfoSmilie; DBManager.instance().saveTeamInfoSmilie(m_iSpielerID, teamInfoSmilie); } /** * Getter for property m_sTeamInfoSmilie. * * @return Value of property m_sTeamInfoSmilie. */ public String getTeamGroup() { if (m_sTeamInfoSmilie == null) { m_sTeamInfoSmilie = DBManager.instance().getTeamInfoSmilie(m_iSpielerID); //Steht null in der DB? if (m_sTeamInfoSmilie == null) { m_sTeamInfoSmilie = ""; } } return m_sTeamInfoSmilie.replaceAll("\\.png$", ""); } /** * Setter for property m_iToreFreund. * * @param m_iToreFreund New value of property m_iToreFreund. */ public void setToreFreund(int m_iToreFreund) { this.m_iToreFreund = m_iToreFreund; } /** * Getter for property m_iToreFreund. * * @return Value of property m_iToreFreund. */ public int getToreFreund() { return m_iToreFreund; } /** * Setter for property m_iToreGesamt. * * @param m_iToreGesamt New value of property m_iToreGesamt. */ public void setAllOfficialGoals(int m_iToreGesamt) { this.m_iToreGesamt = m_iToreGesamt; } /** * Getter for property m_iToreGesamt. * * @return Value of property m_iToreGesamt. */ public int getAllOfficialGoals() { return m_iToreGesamt; } /** * Setter for property m_iToreLiga. * * @param m_iToreLiga New value of property m_iToreLiga. */ public void setToreLiga(int m_iToreLiga) { this.m_iToreLiga = m_iToreLiga; } /** * Getter for property m_iToreLiga. * * @return Value of property m_iToreLiga. */ public int getSeasonSeriesGoal() { return m_iToreLiga; } /** * Setter for property m_iTorePokal. * * @param m_iTorePokal New value of property m_iTorePokal. */ public void setTorePokal(int m_iTorePokal) { this.m_iTorePokal = m_iTorePokal; } /** * Getter for property m_iTorePokal. * * @return Value of property m_iTorePokal. */ public int getSeasonCupGoal() { return m_iTorePokal; } /** * Setter for property m_iTorschuss. * * @param m_iTorschuss New value of property m_iTorschuss. */ public void setTorschuss(int m_iTorschuss) { this.m_iTorschuss = m_iTorschuss; } /** * Getter for property m_iTorschuss. * * @return Value of property m_iTorschuss. */ public int getSCskill() { return m_iTorschuss; } /** * Setter for property m_iTorwart. * * @param m_iTorwart New value of property m_iTorwart. */ public void setTorwart(int m_iTorwart) { this.m_iTorwart = m_iTorwart; } /** * Getter for property m_iTorwart. * * @return Value of property m_iTorwart. */ public int getGKskill() { return m_iTorwart; } /** * Setter for property m_iTrainer. * * @param m_iTrainer New value of property m_iTrainer. */ public void setTrainerSkill(Integer m_iTrainer) { this.m_iTrainer = m_iTrainer; } /** * Getter for property m_iTrainer. * * @return Value of property m_iTrainer. */ public int getTrainerSkill() { return m_iTrainer; } /** * gibt an ob der Player Trainer ist */ public boolean isTrainer() { return m_iTrainer > 0 && m_iTrainerTyp != null; } /** * Setter for property m_iTrainerTyp. * * @param m_iTrainerTyp New value of property m_iTrainerTyp. */ public void setTrainerTyp(TrainerType m_iTrainerTyp) { this.m_iTrainerTyp = m_iTrainerTyp; } /** * Getter for property m_iTrainerTyp. * * @return Value of property m_iTrainerTyp. */ public TrainerType getTrainerTyp() { return m_iTrainerTyp; } /** * Last match * @return date */ public String getLastMatchDate(){ return m_lastMatchDate; } /** * Last match * @return rating */ public Integer getLastMatchRating(){ return m_lastMatchRating; } /** * Last match id * @return id */ public Integer getLastMatchId(){ return m_lastMatchId; } /** * Returns the {@link MatchType} of the last match. */ public MatchType getLastMatchType() { return lastMatchType; } /** * Sets the value of <code>lastMatchType</code> to <code>matchType</code>. */ public void setLastMatchType(MatchType matchType) { this.lastMatchType = matchType; } /** * Set last match £461 * @param date * @param rating * @param id */ public void setLastMatchDetails(String date, Integer rating, Integer id){ m_lastMatchDate = date; m_lastMatchRating = rating; m_lastMatchId = id; } /** * Setter for property m_iTransferlisted. * * @param m_iTransferlisted New value of property m_iTransferlisted. */ public void setTransferlisted(int m_iTransferlisted) { this.m_iTransferlisted = m_iTransferlisted; } /** * Getter for property m_iTransferlisted. * * @return Value of property m_iTransferlisted. */ public int getTransferlisted() { return m_iTransferlisted; } /** * Setter for property m_iTrikotnummer. * * @param m_iTrikotnummer New value of property m_iTrikotnummer. */ public void setShirtNumber(int m_iTrikotnummer) { this.shirtNumber = m_iTrikotnummer; } /** * Getter for property m_iTrikotnummer. * * @return Value of property m_iTrikotnummer. */ public int getTrikotnummer() { return shirtNumber; } /** * Setter for property m_iU20Laenderspiele. * * @param m_iU20Laenderspiele New value of property m_iU20Laenderspiele. */ public void setU20Laenderspiele(int m_iU20Laenderspiele) { this.m_iU20Laenderspiele = m_iU20Laenderspiele; } /** * Getter for property m_iU20Laenderspiele. * * @return Value of property m_iU20Laenderspiele. */ public int getU20Laenderspiele() { return m_iU20Laenderspiele; } public void setUserPosFlag(byte flag) { m_bUserPosFlag = flag; DBManager.instance().saveSpielerUserPosFlag(m_iSpielerID, m_bUserPosFlag); this.setCanBeSelectedByAssistant(flag != IMatchRoleID.UNSELECTABLE); } /** * liefert User Notiz zum Player */ public byte getUserPosFlag() { if (m_bUserPosFlag < MatchRoleID.UNKNOWN) { m_bUserPosFlag = DBManager.instance().getSpielerUserPosFlag(m_iSpielerID); } //database.DBZugriff.instance ().getSpielerNotiz ( m_iSpielerID ); return m_bUserPosFlag; } /** * get Skillvalue 4 skill */ public int getValue4Skill(int skill) { return switch (skill) { case KEEPER -> m_iTorwart; case PLAYMAKING -> m_iSpielaufbau; case DEFENDING -> m_iVerteidigung; case PASSING -> m_iPasspiel; case WINGER -> m_iFluegelspiel; case SCORING -> m_iTorschuss; case SET_PIECES -> m_iStandards; case STAMINA -> m_iKondition; case EXPERIENCE -> m_iErfahrung; case FORM -> m_iForm; case LEADERSHIP -> m_iFuehrung; case LOYALTY -> m_iLoyalty; default -> 0; }; } public float getSkillValue(int skill){ return getSub4Skill(skill) + getValue4Skill(skill); } public void setSkillValue(int skill, float value){ int intVal = (int)value; setValue4Skill(skill, intVal); setSubskill4PlayerSkill(skill, value - intVal); } /** * set Skillvalue 4 skill * * @param skill the skill to change * @param value the new skill value */ public void setValue4Skill(int skill, int value) { switch (skill) { case KEEPER -> setTorwart(value); case PLAYMAKING -> setSpielaufbau(value); case PASSING -> setPasspiel(value); case WINGER -> setFluegelspiel(value); case DEFENDING -> setVerteidigung(value); case SCORING -> setTorschuss(value); case SET_PIECES -> setStandards(value); case STAMINA -> setStamina(value); case EXPERIENCE -> setExperience(value); case FORM -> setForm(value); case LEADERSHIP -> setLeadership(value); case LOYALTY -> setLoyalty(value); } } /** * Setter for property m_iVerletzt. * * @param m_iVerletzt New value of property m_iVerletzt. */ public void setInjuryWeeks(int m_iVerletzt) { this.m_iInjuryWeeks = m_iVerletzt; } /** * Getter for property m_iVerletzt. * * @return Value of property m_iVerletzt. */ public int getInjuryWeeks() { return m_iInjuryWeeks; } /** * Setter for property m_iVerteidigung. * * @param m_iVerteidigung New value of property m_iVerteidigung. */ public void setVerteidigung(int m_iVerteidigung) { this.m_iVerteidigung = m_iVerteidigung; } /** * Getter for property m_iVerteidigung. * * @return Value of property m_iVerteidigung. */ public int getDEFskill() { return m_iVerteidigung; } public int getWeatherEffect(Weather weather) { return PlayerSpeciality.getWeatherEffect(weather, iPlayerSpecialty); } public float getImpactWeatherEffect(Weather weather) { return PlayerSpeciality.getImpactWeatherEffect(weather, iPlayerSpecialty); } /** * Calculates training effect for each skill * * @param train Trainingweek giving the matches that should be calculated * * @return TrainingPerPlayer */ public TrainingPerPlayer calculateWeeklyTraining(TrainingPerWeek train) { final int playerID = this.getPlayerID(); TrainingPerPlayer ret = new TrainingPerPlayer(this); ret.setTrainingWeek(train); if (train == null || train.getTrainingType() < 0) { return ret; } WeeklyTrainingType wt = WeeklyTrainingType.instance(train.getTrainingType()); if (wt != null) { try { var matches = train.getMatches(); int myID = HOVerwaltung.instance().getModel().getBasics().getTeamId(); TrainingWeekPlayer tp = new TrainingWeekPlayer(this); for (var match : matches) { var details = match.getMatchdetails(); if ( details != null ) { //Get the MatchLineup by id MatchLineupTeam mlt = details.getOwnTeamLineup(); if ( mlt != null) { MatchType type = mlt.getMatchType(); boolean walkoverWin = details.isWalkoverMatchWin(myID); if (type != MatchType.MASTERS) { // MASTERS counts only for experience tp.addFullTrainingMinutes(mlt.getTrainingMinutesPlayedInSectors(playerID, wt.getFullTrainingSectors(), walkoverWin)); tp.addBonusTrainingMinutes(mlt.getTrainingMinutesPlayedInSectors(playerID, wt.getBonusTrainingSectors(), walkoverWin)); tp.addPartlyTrainingMinutes(mlt.getTrainingMinutesPlayedInSectors(playerID, wt.getPartlyTrainingSectors(), walkoverWin)); tp.addOsmosisTrainingMinutes(mlt.getTrainingMinutesPlayedInSectors(playerID, wt.getOsmosisTrainingSectors(), walkoverWin)); } var minutes = mlt.getTrainingMinutesPlayedInSectors(playerID, null, walkoverWin); tp.addPlayedMinutes(minutes); ret.addExperience(match.getExperienceIncrease(min(90, minutes))); } else { HOLogger.instance().error(getClass(), "no lineup found in match details " + details.getMatchDate().toLocaleDateTime()); } } } TrainingPoints trp = new TrainingPoints(wt, tp); // get experience increase of national team matches var id = this.getNationalTeamID(); if ( id != null && id != 0 && id != myID){ // TODO check if national matches are stored in database var nationalMatches = train.getNTmatches(); for (var match : nationalMatches){ MatchLineupTeam mlt = DBManager.instance().loadMatchLineupTeam(match.getMatchType().getId(), match.getMatchID(), this.getNationalTeamID()); var minutes = mlt.getTrainingMinutesPlayedInSectors(playerID, null, false); if ( minutes > 0 ) { ret.addExperience(match.getExperienceIncrease(min(90,minutes))); } } } ret.setTrainingPair(trp); } catch (Exception e) { HOLogger.instance().log(getClass(),e); } } return ret; } /** * Performs skill drops on the player based on age and skills * * @param originalPlayer The player as he was before this week. Used to find a subskill to drop from. * @param weeks The number of weeks to drop in case of missing info. */ public void performSkilldrop(Player originalPlayer, int weeks) { if (originalPlayer == null) { return; } for (int skillType = 0; skillType < EXPERIENCE; skillType++) { if ((skillType == FORM) || (skillType == STAMINA)) { continue; } if (getValue4Skill(skillType) >= 1) { float drop = weeks * SkillDrops.instance().getSkillDrop(getValue4Skill(skillType), originalPlayer.getAlter(), skillType); // Only bother if there is drop, there is something to drop from, //and check that the player has not popped if ((drop > 0) && (originalPlayer.getSub4SkillAccurate(skillType) > 0) && (getValue4Skill(skillType) == originalPlayer.getValue4Skill(skillType))) { setSubskill4PlayerSkill(skillType, Math.max(0, getSub4SkillAccurate(skillType) - drop / 100)); } } } } /** * Calculate the player strength on a specific lineup position * with or without form * * @param fo FactorObject with the skill weights for this position * @param useForm consider form? * @param normalized absolute or normalized contribution? * @return the player strength on this position */ float calcPosValue(FactorObject fo, boolean useForm, boolean normalized, @Nullable Weather weather, boolean useWeatherImpact) { if ((fo == null) || (fo.getSum() == 0.0f)) { return -1.0f; } // The stars formulas are changed by the user -> clear the cache if (!PlayerAbsoluteContributionCache.containsKey("lastChange") || ((Date) PlayerAbsoluteContributionCache.get("lastChange")).before(FormulaFactors.getLastChange())) { // System.out.println ("Clearing stars cache"); PlayerAbsoluteContributionCache.clear(); PlayerRelativeContributionCache.clear(); PlayerAbsoluteContributionCache.put("lastChange", new Date()); } /* * Create a key for the Hashtable cache * We cache every star rating to speed up calculation * (calling RPM.calcPlayerStrength() is quite expensive and this method is used very often) */ float loy = RatingPredictionManager.getLoyaltyHomegrownBonus(this); String key = fo.getPosition() + ":" + Helper.round(getGKskill() + getSub4Skill(KEEPER) + loy, 2) + "|" + Helper.round(getPMskill() + getSub4Skill(PLAYMAKING) + loy, 2) + "|" + Helper.round(getDEFskill() + getSub4Skill(DEFENDING) + loy, 2) + "|" + Helper.round(getWIskill() + getSub4Skill(WINGER) + loy, 2) + "|" + Helper.round(getPSskill() + getSub4Skill(PASSING) + loy, 2) + "|" + Helper.round(getSPskill() + getSub4Skill(SET_PIECES) + loy, 2) + "|" + Helper.round(getSCskill() + getSub4Skill(SCORING) + loy, 2) + "|" + getForm() + "|" + getStamina() + "|" + getExperience() + "|" + getPlayerSpecialty(); // used for Technical DefFW // Check if the key already exists in cache if (PlayerAbsoluteContributionCache.containsKey(key)) { // System.out.println ("Using star rating from cache, key="+key+", tablesize="+starRatingCache.size()); float rating = normalized ? (float) PlayerRelativeContributionCache.get(key) : (Float) PlayerAbsoluteContributionCache.get(key); if(useWeatherImpact){ rating *= getImpactWeatherEffect(weather); } return rating; } // Compute contribution float gkValue = fo.getGKfactor() * RatingPredictionManager.calcPlayerStrength(-2, this, KEEPER, useForm, false); float pmValue = fo.getPMfactor() * RatingPredictionManager.calcPlayerStrength(-2, this, PLAYMAKING, useForm, false); float deValue = fo.getDEfactor() * RatingPredictionManager.calcPlayerStrength(-2, this, DEFENDING, useForm, false); float wiValue = fo.getWIfactor() * RatingPredictionManager.calcPlayerStrength(-2, this, WINGER, useForm, false); float psValue = fo.getPSfactor() * RatingPredictionManager.calcPlayerStrength(-2, this, PASSING, useForm, false); float spValue = fo.getSPfactor() * RatingPredictionManager.calcPlayerStrength(-2, this, SET_PIECES, useForm, false); float scValue = fo.getSCfactor() * RatingPredictionManager.calcPlayerStrength(-2, this, SCORING, useForm, false); float val = gkValue + pmValue + deValue + wiValue + psValue + spValue + scValue; float absVal = val * 10; // multiplied by 10 for improved visibility float normVal = val / fo.getNormalizationFactor() * 100; // scaled between 0 and 100% // Put to cache PlayerAbsoluteContributionCache.put(key, absVal); PlayerRelativeContributionCache.put(key, normVal); // System.out.println ("Star rating put to cache, key="+key+", val="+val+", tablesize="+starRatingCache.size()); if (normalized) { return normVal; } else { return absVal; } } public float calcPosValue(byte pos, boolean useForm, boolean normalized, @Nullable Weather weather, boolean useWeatherImpact) { return calcPosValue(pos, useForm, normalized, core.model.UserParameter.instance().nbDecimals, weather, useWeatherImpact); } public float calcPosValue(byte pos, boolean useForm, @Nullable Weather weather, boolean useWeatherImpact) { return calcPosValue(pos, useForm, false, weather, useWeatherImpact); } /** * Calculate the player strength on a specific lineup position * with or without form * * @param pos position from IMatchRoleID (TORWART.. POS_ZUS_INNENV) * @param useForm consider form? * @return the player strength on this position */ public float calcPosValue(byte pos, boolean useForm, boolean normalized, int nb_decimals, @Nullable Weather weather, boolean useWeatherImpact) { float es; FactorObject factor = FormulaFactors.instance().getPositionFactor(pos); // Fix for TDF if (pos == IMatchRoleID.FORWARD_DEF && this.getPlayerSpecialty() == PlayerSpeciality.TECHNICAL) { factor = FormulaFactors.instance().getPositionFactor(IMatchRoleID.FORWARD_DEF_TECH); } if (factor != null) { es = calcPosValue(factor, useForm, normalized, weather, useWeatherImpact); } else { // For Coach or factor not found return 0 return 0.0f; } return core.util.Helper.round(es, nb_decimals); } /** * Copy the skills of old player. * Used by training * * @param old player to copy from */ public void copySkills(Player old) { for (int skillType = 0; skillType <= LOYALTY; skillType++) { setValue4Skill(skillType, old.getValue4Skill(skillType)); } } /** * Performs the subskill reset needed at skill drop. * * @param skillType The ID of the skill to perform drop on. */ public void dropSubskills(int skillType) { if (getValue4Skill(skillType) > 0) { // non-existent has no subskill. setSubskill4PlayerSkill(skillType, 0.999f); } else { setSubskill4PlayerSkill(skillType, 0); } } ////////////////////////////////////////////////////////////////////////////////// //equals ///////////////////////////////////////////////////////////////////////////////// @Override public boolean equals(Object obj) { boolean equals = false; if (obj instanceof Player) { equals = ((Player) obj).getPlayerID() == m_iSpielerID; } return equals; } /** * prüft ob Skillup vorliegt */ protected boolean check4SkillUp(int skill, Player oldPlayer) { if ((oldPlayer != null) && (oldPlayer.getPlayerID() > 0)) return oldPlayer.getValue4Skill(skill) < getValue4Skill(skill); return false; } /** * Test for whether skilldown has occurred */ public boolean check4SkillDown(int skill, Player oldPlayer) { if (skill < EXPERIENCE) if ((oldPlayer != null) && (oldPlayer.getPlayerID() > 0)) return oldPlayer.getValue4Skill(skill) > getValue4Skill(skill); return false; } /** * Does this player have a training block? * * @return training block */ public boolean hasTrainingBlock() { return m_bTrainingBlock; } /** * Set the training block of this player (true/false) * * @param isBlocked new value */ public void setTrainingBlock(boolean isBlocked) { this.m_bTrainingBlock = isBlocked; } public Integer getNationalTeamID() { return nationalTeamId; } public void setNationalTeamId( Integer id){ this.nationalTeamId=id; } public double getSubExperience() { return this.subExperience; } public void setSubExperience( double experience){ this.subExperience = experience; } public List<FuturePlayerTraining> getFuturePlayerTrainings(){ if ( futurePlayerTrainings == null){ futurePlayerTrainings = DBManager.instance().getFuturePlayerTrainings(this.getPlayerID()); if (futurePlayerTrainings.size()>0) { var start = HOVerwaltung.instance().getModel().getBasics().getHattrickWeek(); var remove = new ArrayList<FuturePlayerTraining>(); for (var t : futurePlayerTrainings) { if (t.endsBefore(start)){ remove.add(t); } } futurePlayerTrainings.removeAll(remove); } } return futurePlayerTrainings; } /** * Get the training priority of a hattrick week. If user training plan is given for the week this user selection is * returned. If no user plan is available, the training priority is determined by the player's best position. * * @param wt * used to get priority depending from the player's best position. * @param trainingDate * the training week * @return * the training priority */ public FuturePlayerTraining.Priority getTrainingPriority(WeeklyTrainingType wt, HODateTime trainingDate) { for ( var t : getFuturePlayerTrainings()) { if (t.contains(trainingDate)) { return t.getPriority(); } } // get Prio from best position int position = HelperWrapper.instance().getPosition(this.getIdealPosition()); for ( var p: wt.getTrainingSkillBonusPositions()){ if ( p == position) return FuturePlayerTraining.Priority.FULL_TRAINING; } for ( var p: wt.getTrainingSkillPositions()){ if ( p == position) { if ( wt.getTrainingType() == TrainingType.SET_PIECES) return FuturePlayerTraining.Priority.PARTIAL_TRAINING; return FuturePlayerTraining.Priority.FULL_TRAINING; } } for ( var p: wt.getTrainingSkillPartlyTrainingPositions()){ if ( p == position) return FuturePlayerTraining.Priority.PARTIAL_TRAINING; } for ( var p: wt.getTrainingSkillOsmosisTrainingPositions()){ if ( p == position) return FuturePlayerTraining.Priority.OSMOSIS_TRAINING; } return null; // No training } /** * Set training priority for a time interval. * Previously saved trainings of this interval are overwritten or deleted. * @param prio new training priority for the given time interval * @param from first week with new training priority * @param to last week with new training priority, null means open end */ public void setFutureTraining(FuturePlayerTraining.Priority prio, HODateTime from, HODateTime to) { var removeIntervals = new ArrayList<FuturePlayerTraining>(); for (var t : getFuturePlayerTrainings()) { if (t.cut(from, to) || t.cut(HODateTime.htStart, HOVerwaltung.instance().getModel().getBasics().getHattrickWeek())) { removeIntervals.add(t); } } futurePlayerTrainings.removeAll(removeIntervals); if (prio != null) { futurePlayerTrainings.add(new FuturePlayerTraining(this.getPlayerID(), prio, from, to)); } DBManager.instance().storeFuturePlayerTrainings(this.getPlayerID(), futurePlayerTrainings); } public String getBestPositionInfo(@Nullable Weather weather, boolean useWeatherImpact) { return MatchRoleID.getNameForPosition(getIdealPosition()) + " (" + getIdealPositionStrength(true, true, 1, weather, useWeatherImpact) + "%)"; } /** * training priority information of the training panel * * @param nextWeek training priorities after this week will be considered * @return if there is one user selected priority, the name of the priority is returned * if there are more than one selected priorities, "individual priorities" is returned * if is no user selected priority, the best position information is returned */ public String getTrainingPriorityInformation(HODateTime nextWeek) { String ret=null; for ( var t : getFuturePlayerTrainings()) { // if ( !t.endsBefore(nextWeek)){ if ( ret != null ){ ret = HOVerwaltung.instance().getLanguageString("trainpre.individual.prios"); break; } ret = t.getPriority().toString(); } } if ( ret != null ) return ret; return getBestPositionInfo(null, false); } private static int[] trainingSkills= { KEEPER, SET_PIECES, DEFENDING, SCORING, WINGER, PASSING, PLAYMAKING }; /** * Calculates skill status of the player * * @param previousID Id of the previous download. Previous player status is loaded by this id. * @param trainingWeeks List of training week information */ public void calcSubskills(int previousID, List<TrainingPerWeek> trainingWeeks) { var playerBefore = DBManager.instance().getSpieler(previousID).stream() .filter(i -> i.getPlayerID() == this.getPlayerID()).findFirst().orElse(null); if (playerBefore == null) { playerBefore = this.CloneWithoutSubskills(); } // since we don't want to work with temp player objects we calculate skill by skill // whereas experience is calculated within the first skill boolean experienceSubDone = this.getExperience() > playerBefore.getExperience(); // Do not calculate sub on experience skill up var experienceSub = experienceSubDone ? 0 : playerBefore.getSubExperience(); // set sub to 0 on skill up for (var skill : trainingSkills) { var sub = playerBefore.getSub4Skill(skill); var valueBeforeTraining = playerBefore.getValue4Skill(skill); var valueAfterTraining = this.getValue4Skill(skill); if (trainingWeeks.size() > 0) { for (var training : trainingWeeks) { var trainingPerPlayer = calculateWeeklyTraining(training); if (trainingPerPlayer != null) { if (!this.hasTrainingBlock()) {// player training is not blocked (blocking is no longer possible) sub += trainingPerPlayer.calcSubskillIncrement(skill, valueBeforeTraining + sub); if (valueAfterTraining > valueBeforeTraining) { if (sub > 1) { sub -= 1.; } else { sub = 0.f; } } else if (valueAfterTraining < valueBeforeTraining) { if (sub < 0) { sub += 1.f; } else { sub = .99f; } } else { if (sub > 0.99f) { sub = 0.99f; } else if (sub < 0f) { sub = 0f; } } valueBeforeTraining = valueAfterTraining; } if (!experienceSubDone) { var inc = trainingPerPlayer.getExperienceSub(); experienceSub += inc; if (experienceSub > 0.99) experienceSub = 0.99; var minutes = 0; var tp =trainingPerPlayer.getTrainingPair(); if ( tp != null){ minutes = tp.getTrainingDuration().getPlayedMinutes(); } else { HOLogger.instance().warning(getClass(), "no training info found"); } HOLogger.instance().info(getClass(), "Training " + training.getTrainingDate().toLocaleDateTime() + "; Minutes= " + minutes + "; Experience increment of " + this.getFullName() + "; increment: " + inc + "; new sub value=" + experienceSub ); } } } experienceSubDone = true; } // Handle skill drops that happens the monday after training date var nextWeekTraining = TrainingManager.instance().getNextWeekTraining(); if (SkillDrops.instance().isActive() && nextWeekTraining != null && TrainingManager.instance().getNextWeekTraining().skillDropDayIsBetween(playerBefore.getHrfDate(), this.getHrfDate())) { // calc another skill down sub -= SkillDrops.instance().getSkillDrop(valueBeforeTraining, this.getAlter(), skill) / 100; if (sub < 0) { if (valueAfterTraining < valueBeforeTraining) { // OK sub += 1.; } else { // No skill down from Hattrick sub = 0; } } } else if (valueAfterTraining < valueBeforeTraining) { sub = .99f; } else if (valueAfterTraining > valueBeforeTraining) { sub = 0; HOLogger.instance().error(getClass(), "skill up without training"); // missing training in database } this.setSubskill4PlayerSkill(skill, sub); this.setSubExperience(experienceSub); } } private int getValue4Skill(Skills.HTSkillID skill) { return getValue4Skill(skill.convertToPlayerSkill()); } private double getSub4Skill(Skills.HTSkillID skill) { return getSub4Skill(skill.convertToPlayerSkill()); } private Player CloneWithoutSubskills() { var ret = new Player(); ret.copySkills(this); ret.setPlayerID(getPlayerID()); ret.setAge(getAlter()); ret.setLastName(getLastName()); return ret; } public PlayerCategory getPlayerCategory() { return playerCategory; } public void setPlayerCategory(PlayerCategory playerCategory) { this.playerCategory = playerCategory; } public String getPlayerStatement() { return playerStatement; } public void setPlayerStatement(String playerStatement) { this.playerStatement = playerStatement; } public String getOwnerNotes() { return ownerNotes; } public void setOwnerNotes(String ownerNotes) { this.ownerNotes = ownerNotes; } public Integer getLastMatchPosition() { return lastMatchPosition; } public void setLastMatchPosition(Integer lastMatchPosition) { this.lastMatchPosition = lastMatchPosition; } public Integer getLastMatchMinutes() { return lastMatchMinutes; } public void setLastMatchMinutes(Integer lastMatchMinutes) { this.lastMatchMinutes = lastMatchMinutes; } /** * Rating at end of game * @return Integer number of half rating stars */ public Integer getLastMatchRatingEndOfGame() { return lastMatchRatingEndOfGame; } /** * Rating at end of game * @param lastMatchRatingEndOfGame number of half rating stars */ public void setLastMatchRatingEndOfGame(Integer lastMatchRatingEndOfGame) { this.lastMatchRatingEndOfGame = lastMatchRatingEndOfGame; } public void setMotherClubId(Integer teamID) { this.motherclubId = teamID; } public void setMotherClubName(String teamName) { this.motherclubName = teamName; } public void setMatchesCurrentTeam(Integer matchesCurrentTeam) { this.matchesCurrentTeam=matchesCurrentTeam; } public Integer getMatchesCurrentTeam() { return this.matchesCurrentTeam; } static class PositionContribute { private final float m_rating; private final byte clPositionID; public PositionContribute(float rating, byte clPostionID) { m_rating = rating; clPositionID = clPostionID; } public float getRating() { return m_rating; } public byte getClPostionID() { return clPositionID; } } /** * Create a clone of the player with modified skill values if man marking is switched on. * Values of Defending, Winger, Playmaking, Scoring and Passing are reduced depending of the distance * between man marker and opponent man marked player * * @param manMarkingPosition * null - no man marking changes * Opposite - reduce skills by 50% * NotOpposite - reduce skills by 65% * NotInLineup - reduce skills by 10% * @return * this player, if no man marking changes are selected * New modified player, if man marking changes are selected */ public Player createManMarker(ManMarkingPosition manMarkingPosition) { if ( manMarkingPosition == null) return this; var ret = new Player(); var skillFactor = (float)(1 - manMarkingPosition.value / 100.); ret.setPlayerSpecialty(this.getPlayerSpecialty()); ret.setAgeDays(this.getAgeDays()); ret.setAge(this.getAlter()); ret.setAgressivitaet(this.getAgressivitaet()); ret.setAnsehen(this.getAnsehen()); ret.setCharakter(this.getCharakter()); ret.setExperience(this.getExperience()); ret.setSubExperience(this.getSubExperience()); ret.setFirstName(this.getFirstName()); ret.setLastName(this.getLastName()); ret.setForm(this.getForm()); ret.setLeadership(this.getLeadership()); ret.setStamina(this.getStamina()); ret.setLoyalty(this.getLoyalty()); ret.setHomeGrown(this.isHomeGrown()); ret.setPlayerID(this.getPlayerID()); ret.setInjuryWeeks(this.getInjuryWeeks()); ret.setSkillValue(KEEPER, this.getSkillValue(KEEPER)); ret.setSkillValue(DEFENDING, skillFactor * this.getSkillValue(DEFENDING)); ret.setSkillValue(WINGER, skillFactor * this.getSkillValue(WINGER)); ret.setSkillValue(PLAYMAKING, skillFactor * this.getSkillValue(PLAYMAKING)); ret.setSkillValue(SCORING, skillFactor * this.getSkillValue(SCORING)); ret.setSkillValue(PASSING, skillFactor * this.getSkillValue(PASSING)); ret.setSkillValue(STAMINA, this.getSkillValue(STAMINA)); ret.setSkillValue(FORM, this.getSkillValue(FORM)); ret.setSkillValue(SET_PIECES, this.getSkillValue(SET_PIECES)); ret.setSkillValue(LEADERSHIP, this.getSkillValue(LEADERSHIP)); ret.setSkillValue(LOYALTY, this.getSkillValue(LOYALTY)); return ret; } public enum ManMarkingPosition { /** * central defender versus attack * wingback versus winger * central midfield versus central midfield */ Opposite(50), /** * central defender versus winger, central midfield * wingback versus attack, central midfield * central midfield versus central attack, winger */ NotOpposite(65), /** * opponent player is not in lineup or * any other combination */ NotInLineup(10); private int value; ManMarkingPosition(int v){this.value=v;} public static ManMarkingPosition fromId(int id) { return switch (id) { case 50 -> Opposite; case 65 -> NotOpposite; case 10 -> NotInLineup; default -> null; }; } public int getValue() {return value;} } }
grojar/HO
src/main/java/core/model/player/Player.java
214,390
package core.model.player; import core.constants.TrainingType; import core.constants.player.PlayerSpeciality; import core.constants.player.Speciality; import core.db.AbstractTable; import core.db.DBManager; import core.model.*; import core.model.match.MatchLineupTeam; import core.model.enums.MatchType; import core.model.match.Weather; import core.net.MyConnector; import core.net.OnlineWorker; import core.rating.RatingPredictionManager; import core.training.*; import core.util.*; import org.apache.commons.lang3.math.NumberUtils; import org.jetbrains.annotations.Nullable; import java.time.Duration; import java.util.*; import static core.model.player.MatchRoleID.isFieldMatchRoleId; import static java.lang.Integer.min; import static core.constants.player.PlayerSkill.*; public class Player extends AbstractTable.Storable { /** * Cache for player contribution (Hashtable<String, Float>) */ private static final Hashtable<String, Object> PlayerAbsoluteContributionCache = new Hashtable<>(); private static final Hashtable<String, Object> PlayerRelativeContributionCache = new Hashtable<>(); private byte idealPos = IMatchRoleID.UNKNOWN; private static final String BREAK = "[br]"; private static final String O_BRACKET = "["; private static final String C_BRACKET = "]"; private static final String EMPTY = ""; /** * Name */ private String m_sFirstName = ""; private String m_sNickName = ""; private String m_sLastName = ""; /** * Arrival in team */ private String m_arrivalDate; /** * Download date */ private HODateTime m_clhrfDate; /** * The player is no longer available in the current HRF */ private boolean m_bOld; /** * Wing skill */ private double m_dSubFluegelspiel; /** * Pass skill */ private double m_dSubPasspiel; /** * Playmaking skill */ private double m_dSubSpielaufbau; /** * Standards */ private double m_dSubStandards; /** * Goal */ private double m_dSubTorschuss; //Subskills private double m_dSubTorwart; /** * Verteidigung */ private double m_dSubVerteidigung; /** * Agressivität */ private int m_iAgressivitaet; /** * Alter */ private int m_iAlter; /** * Age Days */ private int m_iAgeDays; /** * Ansehen (ekel usw. ) */ private int m_iAnsehen = 1; /** * Bewertung */ private int m_iBewertung; /** * charakter ( ehrlich) */ private int m_iCharakter = 1; /** * Erfahrung */ private int m_iErfahrung = 1; /** * Fluegelspiel */ private int m_iFluegelspiel = 1; /** * Form */ private int m_iForm = 1; /** * Führungsqualität */ private int m_iFuehrung = 1; /** * Gehalt */ private int m_iGehalt = 1; /** * Gelbe Karten */ private int m_iCards; /** * Hattricks */ private int m_iHattrick; private int m_iGoalsCurrentTeam; /** * Home Grown */ private boolean m_bHomeGrown = false; /** * Kondition */ private int m_iKondition = 1; /** * Länderspiele */ private int m_iLaenderspiele; /** * Loyalty */ private int m_iLoyalty = 0; /** * Markwert */ private int m_iTSI; private String m_sNationality; /** * Aus welchem Land kommt der Player */ private int m_iNationalitaet = 49; /** * Passpiel */ private int m_iPasspiel = 1; /** * SpezialitätID */ private int iPlayerSpecialty; /** * Spielaufbau */ private int m_iSpielaufbau = 1; /** * SpielerID */ private int m_iSpielerID; /** * Standards */ private int m_iStandards = 1; /** * Tore Freundschaftspiel */ private int m_iToreFreund; /** * Tore Gesamt */ private int m_iToreGesamt; /** * Tore Liga */ private int m_iToreLiga; /** * Tore Pokalspiel */ private int m_iTorePokal; /** * Torschuss */ private int m_iTorschuss = 1; /** * Torwart */ private int m_iTorwart = 1; /** * Trainerfähigkeit */ private int m_iTrainer; /** * Trainertyp */ private TrainerType m_iTrainerTyp; /** * Transferlisted */ private int m_iTransferlisted; /** * shirt number (can be edited in hattrick) */ private int shirtNumber = -1; /** * player's category (can be edited in hattrick) */ private PlayerCategory playerCategory; /** * player statement (can be edited in hattrick) */ private String playerStatement; /** * Owner notes (can be edited in hattrick) */ private String ownerNotes; /** * Länderspiele */ private int m_iU20Laenderspiele; /** * Verletzt Wochen */ private int m_iInjuryWeeks = -1; /** * Verteidigung */ private int m_iVerteidigung = 1; /** * Training block */ private boolean m_bTrainingBlock = false; /** * Last match */ private String m_lastMatchDate; private Integer m_lastMatchId; private MatchType lastMatchType; private Integer lastMatchPosition; private Integer lastMatchMinutes; // Rating is number of half stars // real rating value is rating/2.0f private Integer m_lastMatchRating; private Integer lastMatchRatingEndOfGame; /** * specifying at what time –in minutes- that player entered the field * This parameter is only used by RatingPredictionManager to calculate the stamina effect * along the course of the game */ private int GameStartingTime = 0; private Integer nationalTeamId; private double subExperience; /** * future training priorities planed by the user */ private List<FuturePlayerTraining> futurePlayerTrainings; private Integer motherclubId; private String motherclubName; private Integer matchesCurrentTeam; private int hrf_id; private Integer htms = null; private Integer htms28 = null; /** * Externally recruited coaches are no longer allowed to be part of the lineup */ private boolean lineupDisabled = false; public int getGameStartingTime() { return GameStartingTime; } public void setGameStartingTime(int gameStartingTime) { GameStartingTime = gameStartingTime; } //~ Constructors ------------------------------------------------------------------------------- /** * Creates a new instance of Player */ public Player() { } /** * Erstellt einen Player aus den Properties einer HRF Datei */ public Player(Properties properties, HODateTime hrfdate, int hrf_id) { // Separate first, nick and last names are available. Utilize them? this.hrf_id=hrf_id; m_iSpielerID = Integer.parseInt(properties.getProperty("id", "0")); m_sFirstName = properties.getProperty("firstname", ""); m_sNickName = properties.getProperty("nickname", ""); m_sLastName = properties.getProperty("lastname", ""); m_arrivalDate = properties.getProperty("arrivaldate"); m_iAlter = Integer.parseInt(properties.getProperty("ald", "0")); m_iAgeDays = Integer.parseInt(properties.getProperty("agedays", "0")); m_iKondition = Integer.parseInt(properties.getProperty("uth", "0")); m_iForm = Integer.parseInt(properties.getProperty("for", "0")); m_iTorwart = Integer.parseInt(properties.getProperty("mlv", "0")); m_iVerteidigung = Integer.parseInt(properties.getProperty("bac", "0")); m_iSpielaufbau = Integer.parseInt(properties.getProperty("spe", "0")); m_iPasspiel = Integer.parseInt(properties.getProperty("fra", "0")); m_iFluegelspiel = Integer.parseInt(properties.getProperty("ytt", "0")); m_iTorschuss = Integer.parseInt(properties.getProperty("mal", "0")); m_iStandards = Integer.parseInt(properties.getProperty("fas", "0")); iPlayerSpecialty = Integer.parseInt(properties.getProperty("speciality", "0")); m_iCharakter = Integer.parseInt(properties.getProperty("gentleness", "0")); m_iAnsehen = Integer.parseInt(properties.getProperty("honesty", "0")); m_iAgressivitaet = Integer.parseInt(properties.getProperty("aggressiveness", "0")); m_iErfahrung = Integer.parseInt(properties.getProperty("rut", "0")); m_bHomeGrown = Boolean.parseBoolean(properties.getProperty("homegr", "FALSE")); m_iLoyalty = Integer.parseInt(properties.getProperty("loy", "0")); m_iFuehrung = Integer.parseInt(properties.getProperty("led", "0")); m_iGehalt = Integer.parseInt(properties.getProperty("sal", "0")); m_iNationalitaet = Integer.parseInt(properties.getProperty("countryid", "0")); m_iTSI = Integer.parseInt(properties.getProperty("mkt", "0")); // also read subskills when importing hrf from hattrickportal.pro/ useful for U20/NT m_dSubFluegelspiel = Double.parseDouble(properties.getProperty("yttsub", "0")); m_dSubPasspiel = Double.parseDouble(properties.getProperty("frasub", "0")); m_dSubSpielaufbau = Double.parseDouble(properties.getProperty("spesub", "0")); m_dSubStandards = Double.parseDouble(properties.getProperty("fassub", "0")); m_dSubTorschuss = Double.parseDouble(properties.getProperty("malsub", "0")); m_dSubTorwart = Double.parseDouble(properties.getProperty("mlvsub", "0")); m_dSubVerteidigung = Double.parseDouble(properties.getProperty("bacsub", "0")); subExperience = Double.parseDouble(properties.getProperty("experiencesub", "0")); //TSI, alles vorher durch 1000 teilen m_clhrfDate = hrfdate; if (hrfdate.isBefore(HODateTime.fromDbTimestamp(DBManager.TSIDATE))) { m_iTSI /= 1000d; } m_iCards = Integer.parseInt(properties.getProperty("warnings", "0")); m_iInjuryWeeks = Integer.parseInt(properties.getProperty("ska", "0")); m_iToreFreund = Integer.parseInt(properties.getProperty("gtt", "0")); m_iToreLiga = Integer.parseInt(properties.getProperty("gtl", "0")); m_iTorePokal = Integer.parseInt(properties.getProperty("gtc", "0")); m_iToreGesamt = Integer.parseInt(properties.getProperty("gev", "0")); m_iHattrick = Integer.parseInt(properties.getProperty("hat", "0")); m_iGoalsCurrentTeam = Integer.parseInt(properties.getProperty("goalscurrentteam", "0")); matchesCurrentTeam = Integer.parseInt(properties.getProperty("matchescurrentteam", "0")); this.lineupDisabled = getBooleanIfNotNull(properties, "lineupdisabled"); this.m_iBewertung = getIntegerIfNotNull(properties, "rating", 0); this.m_iTrainerTyp = TrainerType.fromInt(getIntegerIfNotNull(properties, "trainertype", -1)); this.m_iTrainer = getIntegerIfNotNull(properties, "trainerskill", 0); var temp = properties.getProperty("playernumber", ""); if ((temp != null) && !temp.equals("") && !temp.equals("null")) { shirtNumber = Integer.parseInt(temp); } m_iTransferlisted = Boolean.parseBoolean(properties.getProperty("transferlisted", "False")) ? 1 : 0; m_iLaenderspiele = Integer.parseInt(properties.getProperty("caps", "0")); m_iU20Laenderspiele = Integer.parseInt(properties.getProperty("capsu20", "0")); this.nationalTeamId = getIntegerIfNotNull(properties, "nationalteamid", 0); // #461-lastmatch m_lastMatchDate = properties.getProperty("lastmatch_date"); if (m_lastMatchDate != null && !m_lastMatchDate.isEmpty()) { m_lastMatchId = Integer.parseInt(properties.getProperty("lastmatch_id", "0")); var pos = Integer.parseInt(properties.getProperty("lastmatch_positioncode", "-1")); if ( isFieldMatchRoleId(pos)) { lastMatchPosition = pos; } lastMatchMinutes = Integer.parseInt(properties.getProperty("lastmatch_playedminutes", "0")); // rating is stored as number of half stars m_lastMatchRating = (int) (2 * Double.parseDouble(properties.getProperty("lastmatch_rating", "0"))); lastMatchRatingEndOfGame = (int) (2 * Double.parseDouble(properties.getProperty("lastmatch_ratingendofgame", "0"))); } setLastMatchType(MatchType.getById( Integer.parseInt(properties.getProperty("lastmatch_type", "0")) )); playerCategory = PlayerCategory.valueOf(NumberUtils.toInt(properties.getProperty("playercategoryid"),0)); playerStatement = properties.getProperty("statement", ""); ownerNotes = properties.getProperty("ownernotes", ""); //Subskills calculation //Called when saving the HRF because the necessary data is not available here final HOModel oldmodel = HOVerwaltung.instance().getModel(); final Player oldPlayer = oldmodel.getCurrentPlayer(m_iSpielerID); if (oldPlayer != null) { // Training blocked (could be done in the past) m_bTrainingBlock = oldPlayer.hasTrainingBlock(); motherclubId = oldPlayer.getMotherclubId(); motherclubName = oldPlayer.getMotherclubName(); } } private int getIntegerIfNotNull(Properties properties, String key, int defaultValue) { var value = properties.getProperty(key); if ( value == null || value.isEmpty()){ return defaultValue; } return Integer.parseInt(value); } private boolean getBooleanIfNotNull(Properties properties, String key) { var value = properties.getProperty(key); if ( value == null || value.isEmpty()){ return false; } return Boolean.parseBoolean(value); } public String getMotherclubName() { downloadMotherclubInfoIfMissing(); return this.motherclubName; } public Integer getMotherclubId() { downloadMotherclubInfoIfMissing(); return this.motherclubId; } private void downloadMotherclubInfoIfMissing() { if (motherclubId == null) { var connection = MyConnector.instance(); var isSilentDownload = connection.isSilentDownload(); try { connection.setSilentDownload(true); // try to download missing mother club info var playerDetails = OnlineWorker.downloadPlayerDetails(String.valueOf(this.getPlayerID())); if (playerDetails != null) { motherclubId = playerDetails.getMotherclubId(); motherclubName = playerDetails.getMotherclubName(); } } catch (Exception e){ HOLogger.instance().warning(getClass(), "mother club not available for player " + this.getFullName()); } finally { connection.setSilentDownload(isSilentDownload); // reset } } } //~ Methods ------------------------------------------------------------------------------------ /** * Setter for property m_iAgressivitaet. * * @param m_iAgressivitaet New value of property m_iAgressivitaet. */ public void setAgressivitaet(int m_iAgressivitaet) { this.m_iAgressivitaet = m_iAgressivitaet; } /** * Getter for property m_iAgressivitaet. * * @return Value of property m_iAgressivitaet. */ public int getAgressivitaet() { return m_iAgressivitaet; } /** * Setter for property m_iAlter. * * @param m_iAlter New value of property m_iAlter. */ public void setAge(int m_iAlter) { this.m_iAlter = m_iAlter; } /** * Getter for property m_iAlter. * * @return Value of property m_iAlter. */ public int getAlter() { return m_iAlter; } /** * Setter for property m_iAgeDays. * * @param m_iAgeDays New value of property m_iAgeDays. */ public void setAgeDays(int m_iAgeDays) { this.m_iAgeDays = m_iAgeDays; } /** * Getter for property m_iAgeDays. * * @return Value of property m_iAgeDays. */ public int getAgeDays() { return m_iAgeDays; } /** * Calculates full age with days and offset * * @return Double value of age & agedays & offset combined, * i.e. age + (agedays+offset)/112 */ public double getAlterWithAgeDays() { var now = HODateTime.now(); return getDoubleAgeFromDate(now); } /** * Calculates full age with days and offset for a given timestamp * used to sort columns * pay attention that it takes the hour and minute of the matchtime into account * if you only want the days between two days use method calendarDaysBetween(Calendar start, Calendar end) * * @return Double value of age & agedays & offset combined, * i.e. age + (agedays+offset)/112 */ public double getDoubleAgeFromDate(HODateTime t) { var hrfTime = HOVerwaltung.instance().getModel().getBasics().getDatum(); var diff = Duration.between(hrfTime.instant, t.instant); int years = getAlter(); int days = getAgeDays(); return years + (double) (days + diff.toDays()) / 112; } /** * Calculates String for full age and days correcting for the difference between (now and last HRF file) * * @return String of age & agedays format is "YY (DDD)" */ public String getAgeWithDaysAsString() { return getAgeWithDaysAsString(HODateTime.now()); } public String getAgeWithDaysAsString(HODateTime t){ return getAgeWithDaysAsString(this.getAlter(), this.getAgeDays(), t, this.m_clhrfDate); } /** * Calculates the player's age at date referencing the current hrf download * @param ageYears int player's age in years in current hrf download * @param ageDays int additional days * @param time HODateTime for which the player's age should be calculated * @return String */ public static String getAgeWithDaysAsString(int ageYears, int ageDays, HODateTime time) { return getAgeWithDaysAsString(ageYears, ageDays,time, HOVerwaltung.instance().getModel().getBasics().getDatum()); } /** * Calculates the player's age at date referencing the given hrf date * @param ageYears int player's age in years at reference time * @param ageDays int additional days * @param time HODateTime for which the player's age should be calculated * @param hrfTime HODateTime reference date, when player's age was given * @return String */ public static String getAgeWithDaysAsString(int ageYears, int ageDays, HODateTime time, HODateTime hrfTime) { var age = new HODateTime.HODuration(ageYears, ageDays).plus(HODateTime.HODuration.between(hrfTime, time)); return age.seasons + " (" + age.days + ")"; } /** * Get the full i18n'd string representing the player's age. Includes * the birthday indicator as well. * * @return the full i18n'd string representing the player's age */ public String getAgeStringFull() { var hrfTime = HOVerwaltung.instance().getModel().getBasics().getDatum(); var oldAge = new HODateTime.HODuration(this.getAlter(), this.getAgeDays()); var age = oldAge.plus(HODateTime.HODuration.between(hrfTime, HODateTime.now())); var birthday = oldAge.seasons != age.seasons; StringBuilder ret = new StringBuilder(); ret.append(age.seasons); ret.append(" "); ret.append(HOVerwaltung.instance().getLanguageString("ls.player.age.years")); ret.append(" "); ret.append(age.days); ret.append(" "); ret.append(HOVerwaltung.instance().getLanguageString("ls.player.age.days")); if (birthday) { ret.append(" ("); ret.append(HOVerwaltung.instance().getLanguageString("ls.player.age.birthday")); ret.append(")"); } return ret.toString(); } /** * Setter for property m_iAnsehen. * * @param m_iAnsehen New value of property m_iAnsehen. */ public void setAnsehen(int m_iAnsehen) { this.m_iAnsehen = m_iAnsehen; } /** * Getter for property m_iAnsehen. * * @return Value of property m_iAnsehen. */ public int getAnsehen() { return m_iAnsehen; } /** * Setter for property m_iBewertung. * * @param m_iBewertung New value of property m_iBewertung. */ public void setBewertung(int m_iBewertung) { this.m_iBewertung = m_iBewertung; } /** * Getter for property m_iBewertung. * * @return Value of property m_iBewertung. */ public int getRating() { return m_iBewertung; } /** * Getter for property m_iBonus. * * @return Value of property m_iBonus. */ public int getBonus() { int bonus = 0; if (m_iNationalitaet != HOVerwaltung.instance().getModel().getBasics().getLand()) { bonus = 20; } return bonus; } /** * Setter for property m_iCharakter. * * @param m_iCharakter New value of property m_iCharakter. */ public void setCharakter(int m_iCharakter) { this.m_iCharakter = m_iCharakter; } public String getArrivalDate() { return m_arrivalDate; } public void setArrivalDate(String m_arrivalDate) { this.m_arrivalDate = m_arrivalDate; } /** * Getter for property m_iCharackter. * * @return Value of property m_iCharackter. */ public int getCharakter() { return m_iCharakter; } /** * Setter for property m_iErfahrung. * * @param m_iErfahrung New value of property m_iErfahrung. */ public void setExperience(int m_iErfahrung) { this.m_iErfahrung = m_iErfahrung; } /** * Getter for property m_iErfahrung. * * @return Value of property m_iErfahrung. */ public int getExperience() { return m_iErfahrung; } /** * Setter for property m_iFluegelspiel. * * @param m_iFluegelspiel New value of property m_iFluegelspiel. */ public void setFluegelspiel(int m_iFluegelspiel) { this.m_iFluegelspiel = m_iFluegelspiel; } /** * Getter for property m_iFluegelspiel. * * @return Value of property m_iFluegelspiel. */ public int getWIskill() { return m_iFluegelspiel; } /** * Setter for property m_iForm. * * @param m_iForm New value of property m_iForm. */ public void setForm(int m_iForm) { this.m_iForm = m_iForm; } /** * Getter for property m_iForm. * * @return Value of property m_iForm. */ public int getForm() { return m_iForm; } /** * Setter for property m_iFuehrung. * * @param m_iFuehrung New value of property m_iFuehrung. */ public void setLeadership(int m_iFuehrung) { this.m_iFuehrung = m_iFuehrung; } /** * Getter for property m_iFuehrung. * * @return Value of property m_iFuehrung. */ public int getLeadership() { return m_iFuehrung; } /** * Setter for property m_iGehalt. * * @param m_iGehalt New value of property m_iGehalt. */ public void setGehalt(int m_iGehalt) { this.m_iGehalt = m_iGehalt; } /** * Getter for property m_iGehalt. * * @return Value of property m_iGehalt. */ public int getSalary() { return m_iGehalt; } /** * Setter for property m_iGelbeKarten. * * @param m_iGelbeKarten New value of property m_iGelbeKarten. */ public void setGelbeKarten(int m_iGelbeKarten) { this.m_iCards = m_iGelbeKarten; } /** * Getter for property m_iGelbeKarten. * * @return Value of property m_iGelbeKarten. */ public int getCards() { return m_iCards; } /** * gibt an ob der spieler gesperrt ist */ public boolean isRedCarded() { return (m_iCards > 2); } public void setHattrick(int m_iHattrick) { this.m_iHattrick = m_iHattrick; } public int getHattrick() { return m_iHattrick; } public int getGoalsCurrentTeam() { return m_iGoalsCurrentTeam; } public void setGoalsCurrentTeam(int m_iGoalsCurrentTeam) { this.m_iGoalsCurrentTeam = m_iGoalsCurrentTeam; } /** * Setter for m_bHomeGrown * */ public void setHomeGrown(boolean hg) { m_bHomeGrown = hg; } /** * Getter for m_bHomeGrown * * @return Value of property m_bHomeGrown */ public boolean isHomeGrown() { return m_bHomeGrown; } public HODateTime getHrfDate() { if ( m_clhrfDate == null){ m_clhrfDate = HOVerwaltung.instance().getModel().getBasics().getDatum(); } return m_clhrfDate; } public void setHrfDate(HODateTime timestamp) { m_clhrfDate = timestamp; } public void setHrfDate() { setHrfDate(HODateTime.now()); } /** * calculate the contribution for the ideal position */ public float getIdealPositionStrength(boolean mitForm, @Nullable Weather weather, boolean useWeatherImpact) { return getIdealPositionStrength(mitForm, false, weather, useWeatherImpact); } /** * calculate the contribution for the ideal position */ public float getIdealPositionStrength(boolean mitForm, boolean normalized, @Nullable Weather weather, boolean useWeatherImpact) { return getIdealPositionStrength(mitForm, normalized, 2, weather, useWeatherImpact); } /** * calculate the contribution for the ideal position */ public float getIdealPositionStrength(boolean mitForm, boolean normalized, int nb_decimal, @Nullable Weather weather, boolean useWeatherImpact) { return calcPosValue(getIdealPosition(), mitForm, normalized, nb_decimal, weather, useWeatherImpact); } /** * Calculate Player Ideal Position (weather impact not relevant here) */ public byte calculateIdealPosition(){ final FactorObject[] allPos = FormulaFactors.instance().getAllObj(); float maxStk = -1.0f; byte currPosition; float contrib; for (int i = 0; (allPos != null) && (i < allPos.length); i++) { if (allPos[i].getPosition() == IMatchRoleID.FORWARD_DEF_TECH) continue; currPosition = allPos[i].getPosition(); contrib = calcPosValue(currPosition, true, true, null, false); if (contrib > maxStk) { maxStk = contrib; idealPos = currPosition; } } return idealPos ; } public byte getIdealPosition() { //in case player best position is forced by user final int flag = getUserPosFlag(); if (flag == IMatchRoleID.UNKNOWN) { if (idealPos == IMatchRoleID.UNKNOWN) { idealPos = calculateIdealPosition(); } return idealPos; } return (byte)flag; } /** * Calculate Player Alternative Best Positions (weather impact not relevant here) */ public byte[] getAlternativeBestPositions() { List<PositionContribute> positions = new ArrayList<>(); final FactorObject[] allPos = FormulaFactors.instance().getAllObj(); byte currPosition; PositionContribute currPositionContribute; for (int i = 0; (allPos != null) && (i < allPos.length); i++) { if (allPos[i].getPosition() == IMatchRoleID.FORWARD_DEF_TECH) continue; currPosition = allPos[i].getPosition(); currPositionContribute = new PositionContribute(calcPosValue(currPosition, true, true, null, false), currPosition); positions.add(currPositionContribute); } positions.sort((PositionContribute player1, PositionContribute player2) -> Float.compare(player2.getRating(), player1.getRating())); byte[] alternativePositions = new byte[positions.size()]; float tolerance = 1f - UserParameter.instance().alternativePositionsTolerance; int i; final float threshold = positions.get(0).getRating() * tolerance; for (i = 0; i < positions.size(); i++) { if (positions.get(i).getRating() >= threshold) { alternativePositions[i] = positions.get(i).getClPostionID(); } else { break; } } alternativePositions = Arrays.copyOf(alternativePositions, i); return alternativePositions; } /** * return whether or not the position is one of the best position for the player */ public boolean isAnAlternativeBestPosition(byte position){ return Arrays.asList(getAlternativeBestPositions()).contains(position); } /** * Setter for property m_iKondition. * * @param m_iKondition New value of property m_iKondition. */ public void setStamina(int m_iKondition) { this.m_iKondition = m_iKondition; } //////////////////////////////////////////////////////////////////////////////// //Accessor //////////////////////////////////////////////////////////////////////////////// /** * Getter for property m_iKondition. * * @return Value of property m_iKondition. */ public int getStamina() { return m_iKondition; } /** * Setter for property m_iLaenderspiele. * * @param m_iLaenderspiele New value of property m_iLaenderspiele. */ public void setLaenderspiele(int m_iLaenderspiele) { this.m_iLaenderspiele = m_iLaenderspiele; } /** * Getter for property m_iLaenderspiele. * * @return Value of property m_iLaenderspiele. */ public int getLaenderspiele() { return m_iLaenderspiele; } private final HashMap<Integer, Skillup> lastSkillups = new HashMap<>(); /** * liefert das Datum des letzen LevelAufstiegs für den angeforderten Skill [0] = Time der * Änderung [1] = Boolean: false=Keine Änderung gefunden */ public Skillup getLastLevelUp(int skill) { if ( lastSkillups.containsKey(skill)){ return lastSkillups.get(skill); } var ret = DBManager.instance().getLastLevelUp(skill, m_iSpielerID); lastSkillups.put(skill, ret); return ret; } private final HashMap<Integer, List<Skillup> > allSkillUps = new HashMap<>(); /** * gives information of skill ups */ public List<Skillup> getAllLevelUp(int skill) { if ( allSkillUps.containsKey(skill)) { return allSkillUps.get(skill); } var ret = DBManager.instance().getAllLevelUp(skill, m_iSpielerID); allSkillUps.put(skill, ret); return ret; } public void resetSkillUpInformation() { lastSkillups.clear(); allSkillUps.clear(); } /** * Returns the loyalty stat */ public int getLoyalty() { return m_iLoyalty; } /** * Sets the loyalty stat */ public void setLoyalty(int loy) { m_iLoyalty = loy; } /** * Setter for property m_sManuellerSmilie. * * @param manuellerSmilie New value of property m_sManuellerSmilie. */ public void setManuellerSmilie(String manuellerSmilie) { getNotes().setManuelSmilie(manuellerSmilie); DBManager.instance().storePlayerNotes(notes); } /** * Getter for property m_sManuellerSmilie. * * @return Value of property m_sManuellerSmilie. */ public String getInfoSmiley() { return getNotes().getManuelSmilie(); } /** * Sets the TSI * * @param m_iTSI New value of property m_iMarkwert. */ public void setTSI(int m_iTSI) { this.m_iTSI = m_iTSI; } /** * Returns the TSI * * @return Value of property m_iMarkwert. */ public int getTSI() { return m_iTSI; } public void setFirstName(String m_sName) { if ( m_sName != null ) this.m_sFirstName = m_sName; else m_sFirstName = ""; } public String getFirstName() { return m_sFirstName; } public void setNickName(String m_sName) { if ( m_sName != null ) this.m_sNickName = m_sName; else m_sNickName = ""; } public String getNickName() { return m_sNickName; } public void setLastName(String m_sName) { if (m_sName != null ) this.m_sLastName = m_sName; else this.m_sLastName = ""; } public String getLastName() { return m_sLastName; } /** * Getter for shortName * eg: James Bond = J. Bond * Nickname are ignored */ public String getShortName() { if (getFirstName().isEmpty()) { return getLastName(); } return getFirstName().charAt(0) + ". " + getLastName(); } public String getFullName() { if (getNickName().isEmpty()) { return getFirstName() + " " +getLastName(); } return getFirstName() + " '" + getNickName() + "' " +getLastName(); } /** * Setter for property m_iNationalitaet. * * @param m_iNationalitaet New value of property m_iNationalitaet. */ public void setNationalityAsInt(int m_iNationalitaet) { this.m_iNationalitaet = m_iNationalitaet; } /** * Getter for property m_iNationalitaet. * * @return Value of property m_iNationalitaet. */ public int getNationalityAsInt() { return m_iNationalitaet; } public String getNationalityAsString() { if (m_sNationality != null){ return m_sNationality; } WorldDetailLeague leagueDetail = WorldDetailsManager.instance().getWorldDetailLeagueByCountryId(m_iNationalitaet); if ( leagueDetail != null ) { m_sNationality = leagueDetail.getCountryName(); } else{ m_sNationality = ""; } return m_sNationality; } /** * Setter for property m_bOld. * * @param m_bOld New value of property m_bOld. */ public void setOld(boolean m_bOld) { this.m_bOld = m_bOld; } /** * Getter for property m_bOld. * * @return Value of property m_bOld. */ public boolean isOld() { return m_bOld; } /** * Setter for property m_iPasspiel. * * @param m_iPasspiel New value of property m_iPasspiel. */ public void setPasspiel(int m_iPasspiel) { this.m_iPasspiel = m_iPasspiel; } /** * Getter for property m_iPasspiel. * * @return Value of property m_iPasspiel. */ public int getPSskill() { return m_iPasspiel; } /** * Zum speichern! Die Reduzierung des Marktwerts auf TSI wird rückgängig gemacht */ public int getMarktwert() { if (m_clhrfDate == null || m_clhrfDate.isBefore(HODateTime.fromDbTimestamp(DBManager.TSIDATE))) { //Echter Marktwert return m_iTSI * 1000; } //TSI return m_iTSI; } String latestTSIInjured; String latestTSINotInjured; public String getLatestTSINotInjured(){ if (latestTSINotInjured == null){ latestTSINotInjured = DBManager.instance().loadLatestTSINotInjured(m_iSpielerID); } return latestTSINotInjured; } public String getLatestTSIInjured(){ if (latestTSIInjured == null){ latestTSIInjured = DBManager.instance().loadLatestTSIInjured(m_iSpielerID); } return latestTSIInjured; } /** * Setter for property iPlayerSpecialty. * * @param iPlayerSpecialty New value of property iPlayerSpecialty. */ public void setPlayerSpecialty(int iPlayerSpecialty) { this.iPlayerSpecialty = iPlayerSpecialty; } /** * Getter for property iPlayerSpecialty. * * @return Value of property iPlayerSpecialty. */ public int getPlayerSpecialty() { return iPlayerSpecialty; } public boolean hasSpeciality(Speciality speciality) { Speciality s = Speciality.values()[iPlayerSpecialty]; return s.equals(speciality); } // returns the name of the speciality in the used language public String getSpecialityName() { Speciality s = Speciality.values()[iPlayerSpecialty]; if (s.equals(Speciality.NO_SPECIALITY)) { return EMPTY; } else { return HOVerwaltung.instance().getLanguageString("ls.player.speciality." + s.toString().toLowerCase(Locale.ROOT)); } } // return the name of the speciality with a break before and in brackets // e.g. [br][quick], used for HT-ML export public String getSpecialityExportName() { Speciality s = Speciality.values()[iPlayerSpecialty]; if (s.equals(Speciality.NO_SPECIALITY)) { return EMPTY; } else { return BREAK + O_BRACKET + getSpecialityName() + C_BRACKET; } } // no break so that the export looks better public String getSpecialityExportNameForKeeper() { Speciality s = Speciality.values()[iPlayerSpecialty]; if (s.equals(Speciality.NO_SPECIALITY)) { return EMPTY; } else { return O_BRACKET + getSpecialityName() + C_BRACKET; } } /** * Setter for property m_iSpielaufbau. * * @param m_iSpielaufbau New value of property m_iSpielaufbau. */ public void setSpielaufbau(int m_iSpielaufbau) { this.m_iSpielaufbau = m_iSpielaufbau; } /** * Getter for property m_iSpielaufbau. * * @return Value of property m_iSpielaufbau. */ public int getPMskill() { return m_iSpielaufbau; } /** * set whether that player can be selected by the assistant */ public void setCanBeSelectedByAssistant(boolean flag) { if (this.isLineupDisabled()) flag = false; getNotes().setEligibleToPlay(flag); DBManager.instance().storePlayerNotes(notes); } /** * get whether that player can be selected by the assistant */ public boolean getCanBeSelectedByAssistant() { return !this.isLineupDisabled() && getNotes().isEligibleToPlay(); } /** * Setter for property m_iSpielerID. * * @param m_iSpielerID New value of property m_iSpielerID. */ public void setPlayerID(int m_iSpielerID) { this.m_iSpielerID = m_iSpielerID; } /** * Getter for property m_iSpielerID. * * @return Value of property m_iSpielerID. */ public int getPlayerID() { return m_iSpielerID; } /** * Setter for property m_iStandards. * * @param m_iStandards New value of property m_iStandards. */ public void setStandards(int m_iStandards) { this.m_iStandards = m_iStandards; } /** * Getter for property m_iStandards. * * @return Value of property m_iStandards. */ public int getSPskill() { return m_iStandards; } /** * berechnet den Subskill pro position */ public float getSub4Skill(int skill) { return Math.min(0.99f, Helper.round(getSub4SkillAccurate(skill), 2)); } public float getSkill(int iSkill, boolean inclSubSkill) { if(inclSubSkill) { return getValue4Skill(iSkill) + getSub4Skill(iSkill); } else{ return getValue4Skill(iSkill); } } /** * Returns accurate subskill number. If you need subskill for UI * purpose it is better to use getSubskill4Pos() * * @param skill skill number * @return subskill between 0.0-0.999 */ public float getSub4SkillAccurate(int skill) { double value = switch (skill) { case KEEPER -> m_dSubTorwart; case PLAYMAKING -> m_dSubSpielaufbau; case DEFENDING -> m_dSubVerteidigung; case PASSING -> m_dSubPasspiel; case WINGER -> m_dSubFluegelspiel; case SCORING -> m_dSubTorschuss; case SET_PIECES -> m_dSubStandards; case EXPERIENCE -> subExperience; default -> 0; }; return (float) Math.min(0.999, value); } public void setSubskill4PlayerSkill(int skill, float value) { switch (skill) { case KEEPER -> m_dSubTorwart = value; case PLAYMAKING -> m_dSubSpielaufbau = value; case DEFENDING -> m_dSubVerteidigung = value; case PASSING -> m_dSubPasspiel = value; case WINGER -> m_dSubFluegelspiel = value; case SCORING -> m_dSubTorschuss = value; case SET_PIECES -> m_dSubStandards = value; case EXPERIENCE -> subExperience = value; } } /** * Setter for property m_sTeamInfoSmilie. * * @param teamInfoSmilie New value of property m_sTeamInfoSmilie. */ public void setTeamInfoSmilie(String teamInfoSmilie) { getNotes().setTeamInfoSmilie(teamInfoSmilie); DBManager.instance().storePlayerNotes(notes); } /** * Getter for property m_sTeamInfoSmilie. * * @return Value of property m_sTeamInfoSmilie. */ public String getTeamGroup() { var ret = getNotes().getTeamInfoSmilie(); return ret.replaceAll("\\.png$", ""); } /** * Setter for property m_iToreFreund. * * @param m_iToreFreund New value of property m_iToreFreund. */ public void setToreFreund(int m_iToreFreund) { this.m_iToreFreund = m_iToreFreund; } /** * Getter for property m_iToreFreund. * * @return Value of property m_iToreFreund. */ public int getToreFreund() { return m_iToreFreund; } /** * Setter for property m_iToreGesamt. * * @param m_iToreGesamt New value of property m_iToreGesamt. */ public void setAllOfficialGoals(int m_iToreGesamt) { this.m_iToreGesamt = m_iToreGesamt; } /** * Getter for property m_iToreGesamt. * * @return Value of property m_iToreGesamt. */ public int getAllOfficialGoals() { return m_iToreGesamt; } /** * Setter for property m_iToreLiga. * * @param m_iToreLiga New value of property m_iToreLiga. */ public void setToreLiga(int m_iToreLiga) { this.m_iToreLiga = m_iToreLiga; } /** * Getter for property m_iToreLiga. * * @return Value of property m_iToreLiga. */ public int getSeasonSeriesGoal() { return m_iToreLiga; } /** * Setter for property m_iTorePokal. * * @param m_iTorePokal New value of property m_iTorePokal. */ public void setTorePokal(int m_iTorePokal) { this.m_iTorePokal = m_iTorePokal; } /** * Getter for property m_iTorePokal. * * @return Value of property m_iTorePokal. */ public int getSeasonCupGoal() { return m_iTorePokal; } /** * Setter for property m_iTorschuss. * * @param m_iTorschuss New value of property m_iTorschuss. */ public void setTorschuss(int m_iTorschuss) { this.m_iTorschuss = m_iTorschuss; } /** * Getter for property m_iTorschuss. * * @return Value of property m_iTorschuss. */ public int getSCskill() { return m_iTorschuss; } /** * Setter for property m_iTorwart. * * @param m_iTorwart New value of property m_iTorwart. */ public void setTorwart(int m_iTorwart) { this.m_iTorwart = m_iTorwart; } /** * Getter for property m_iTorwart. * * @return Value of property m_iTorwart. */ public int getGKskill() { return m_iTorwart; } /** * Setter for property m_iTrainer. * * @param m_iTrainer New value of property m_iTrainer. */ public void setTrainerSkill(Integer m_iTrainer) { this.m_iTrainer = m_iTrainer; } /** * Getter for property m_iTrainer. * * @return Value of property m_iTrainer. */ public int getTrainerSkill() { return m_iTrainer; } /** * gibt an ob der Player Trainer ist */ public boolean isTrainer() { return m_iTrainer > 0 && m_iTrainerTyp != null; } /** * Setter for property m_iTrainerTyp. * * @param m_iTrainerTyp New value of property m_iTrainerTyp. */ public void setTrainerTyp(TrainerType m_iTrainerTyp) { this.m_iTrainerTyp = m_iTrainerTyp; } /** * Getter for property m_iTrainerTyp. * * @return Value of property m_iTrainerTyp. */ public TrainerType getTrainerTyp() { return m_iTrainerTyp; } /** * Last match * @return date */ public String getLastMatchDate(){ return m_lastMatchDate; } /** * Last match * @return rating */ public Integer getLastMatchRating(){ return m_lastMatchRating; } /** * Last match id * @return id */ public Integer getLastMatchId(){ return m_lastMatchId; } /** * Returns the {@link MatchType} of the last match. */ public MatchType getLastMatchType() { return lastMatchType; } /** * Sets the value of <code>lastMatchType</code> to <code>matchType</code>. */ public void setLastMatchType(MatchType matchType) { this.lastMatchType = matchType; } /** * Setter for property m_iTransferlisted. * * @param m_iTransferlisted New value of property m_iTransferlisted. */ public void setTransferlisted(int m_iTransferlisted) { this.m_iTransferlisted = m_iTransferlisted; } /** * Getter for property m_iTransferlisted. * * @return Value of property m_iTransferlisted. */ public int getTransferlisted() { return m_iTransferlisted; } /** * Setter for property m_iTrikotnummer. * * @param m_iTrikotnummer New value of property m_iTrikotnummer. */ public void setShirtNumber(int m_iTrikotnummer) { this.shirtNumber = m_iTrikotnummer; } /** * Getter for property m_iTrikotnummer. * * @return Value of property m_iTrikotnummer. */ public int getTrikotnummer() { return shirtNumber; } /** * Setter for property m_iU20Laenderspiele. * * @param m_iU20Laenderspiele New value of property m_iU20Laenderspiele. */ public void setU20Laenderspiele(int m_iU20Laenderspiele) { this.m_iU20Laenderspiele = m_iU20Laenderspiele; } /** * Getter for property m_iU20Laenderspiele. * * @return Value of property m_iU20Laenderspiele. */ public int getU20Laenderspiele() { return m_iU20Laenderspiele; } public void setHrfId(int hrf_id) { this.hrf_id=hrf_id; } public int getHrfId() { return this.hrf_id; } public void setLastMatchDate(String v) { this.m_lastMatchDate = v; } public void setLastMatchRating(Integer v) { this.m_lastMatchRating=v; } public void setLastMatchId(Integer v) { this.m_lastMatchId = v; } public Integer getHtms28() { if ( htms28 == null){ htms28 = Htms.htms28(getSkills(), this.m_iAlter, this.m_iAgeDays); } return htms28; } public Integer getHtms(){ if (htms == null){ htms= Htms.htms(getSkills()); } return htms; } private Map<Integer, Integer> getSkills() { var ret = new HashMap<Integer, Integer>(); ret.put(KEEPER, getGKskill()); ret.put(DEFENDING, getDEFskill()); ret.put(PLAYMAKING, getPMskill()); ret.put(WINGER, getWIskill()); ret.put(PASSING, getPSskill()); ret.put(SCORING, getSCskill()); ret.put(SET_PIECES, getSPskill()); return ret; } public boolean isLineupDisabled() { return lineupDisabled; } public void setLineupDisabled(Boolean lineupDisabled) { this.lineupDisabled = Objects.requireNonNullElse(lineupDisabled, false); } public static class Notes extends AbstractTable.Storable{ public Notes(){} private int playerId; public Notes(int playerId) { this.playerId = playerId; } public int getUserPos() { return userPos; } private int userPos = IMatchRoleID.UNKNOWN; public String getManuelSmilie() { return manuelSmilie; } public String getNote() { return note; } public boolean isEligibleToPlay() { return eligibleToPlay; } public String getTeamInfoSmilie() { return teamInfoSmilie; } public boolean isFired() { return isFired; } private String manuelSmilie=""; private String note=""; private boolean eligibleToPlay=true; private String teamInfoSmilie=""; private boolean isFired=false; public void setPlayerId(int playerId) { this.playerId=playerId; } public void setNote(String note) { this.note=note; } public void setEligibleToPlay(boolean spielberechtigt) { this.eligibleToPlay=spielberechtigt; } public void setTeamInfoSmilie(String teamInfoSmilie) { this.teamInfoSmilie=teamInfoSmilie; } public void setManuelSmilie(String manuellerSmilie) { this.manuelSmilie=manuellerSmilie; } public void setUserPos(int userPos) { this.userPos=userPos; } public void setIsFired(boolean isFired) { this.isFired=isFired; } public int getPlayerId() { return this.playerId; } } private Notes notes; private Notes getNotes(){ if ( notes==null){ notes = DBManager.instance().loadPlayerNotes(this.getPlayerID()); } return notes; } public void setUserPosFlag(byte flag) { getNotes().setUserPos(flag); DBManager.instance().storePlayerNotes(notes); this.setCanBeSelectedByAssistant(flag != IMatchRoleID.UNSELECTABLE); } public void setIsFired(boolean b) { getNotes().setIsFired(b); DBManager.instance().storePlayerNotes(notes); } public boolean isFired() { return getNotes().isFired(); } /** * liefert User Notiz zum Player */ public int getUserPosFlag() { return getNotes().getUserPos(); } public String getNote() {return getNotes().getNote();} public void setNote(String text) { getNotes().setNote(text); DBManager.instance().storePlayerNotes(notes); } /** * get Skillvalue 4 skill */ public int getValue4Skill(int skill) { return switch (skill) { case KEEPER -> m_iTorwart; case PLAYMAKING -> m_iSpielaufbau; case DEFENDING -> m_iVerteidigung; case PASSING -> m_iPasspiel; case WINGER -> m_iFluegelspiel; case SCORING -> m_iTorschuss; case SET_PIECES -> m_iStandards; case STAMINA -> m_iKondition; case EXPERIENCE -> m_iErfahrung; case FORM -> m_iForm; case LEADERSHIP -> m_iFuehrung; case LOYALTY -> m_iLoyalty; default -> 0; }; } public float getSkillValue(int skill){ return getSub4Skill(skill) + getValue4Skill(skill); } public void setSkillValue(int skill, float value){ int intVal = (int)value; setValue4Skill(skill, intVal); setSubskill4PlayerSkill(skill, value - intVal); } /** * set Skillvalue 4 skill * * @param skill the skill to change * @param value the new skill value */ public void setValue4Skill(int skill, int value) { switch (skill) { case KEEPER -> setTorwart(value); case PLAYMAKING -> setSpielaufbau(value); case PASSING -> setPasspiel(value); case WINGER -> setFluegelspiel(value); case DEFENDING -> setVerteidigung(value); case SCORING -> setTorschuss(value); case SET_PIECES -> setStandards(value); case STAMINA -> setStamina(value); case EXPERIENCE -> setExperience(value); case FORM -> setForm(value); case LEADERSHIP -> setLeadership(value); case LOYALTY -> setLoyalty(value); } } /** * Setter for property m_iVerletzt. * * @param m_iVerletzt New value of property m_iVerletzt. */ public void setInjuryWeeks(int m_iVerletzt) { this.m_iInjuryWeeks = m_iVerletzt; } /** * Getter for property m_iVerletzt. * * @return Value of property m_iVerletzt. */ public int getInjuryWeeks() { return m_iInjuryWeeks; } /** * Setter for property m_iVerteidigung. * * @param m_iVerteidigung New value of property m_iVerteidigung. */ public void setVerteidigung(int m_iVerteidigung) { this.m_iVerteidigung = m_iVerteidigung; } /** * Getter for property m_iVerteidigung. * * @return Value of property m_iVerteidigung. */ public int getDEFskill() { return m_iVerteidigung; } public float getImpactWeatherEffect(Weather weather) { return PlayerSpeciality.getImpactWeatherEffect(weather, iPlayerSpecialty); } /** * Calculates training effect for each skill * * @param train Trainingweek giving the matches that should be calculated * * @return TrainingPerPlayer */ public TrainingPerPlayer calculateWeeklyTraining(TrainingPerWeek train) { final int playerID = this.getPlayerID(); TrainingPerPlayer ret = new TrainingPerPlayer(this); ret.setTrainingWeek(train); if (train == null || train.getTrainingType() < 0) { return ret; } WeeklyTrainingType wt = WeeklyTrainingType.instance(train.getTrainingType()); if (wt != null) { try { var matches = train.getMatches(); int myID = HOVerwaltung.instance().getModel().getBasics().getTeamId(); TrainingWeekPlayer tp = new TrainingWeekPlayer(this); for (var match : matches) { var details = match.getMatchdetails(); if ( details != null ) { //Get the MatchLineup by id MatchLineupTeam mlt = details.getOwnTeamLineup(); if ( mlt != null) { MatchType type = mlt.getMatchType(); boolean walkoverWin = details.isWalkoverMatchWin(myID); if (type != MatchType.MASTERS) { // MASTERS counts only for experience tp.addFullTrainingMinutes(mlt.getTrainingMinutesPlayedInSectors(playerID, wt.getFullTrainingSectors(), walkoverWin)); tp.addBonusTrainingMinutes(mlt.getTrainingMinutesPlayedInSectors(playerID, wt.getBonusTrainingSectors(), walkoverWin)); tp.addPartlyTrainingMinutes(mlt.getTrainingMinutesPlayedInSectors(playerID, wt.getPartlyTrainingSectors(), walkoverWin)); tp.addOsmosisTrainingMinutes(mlt.getTrainingMinutesPlayedInSectors(playerID, wt.getOsmosisTrainingSectors(), walkoverWin)); } var minutes = mlt.getTrainingMinutesPlayedInSectors(playerID, null, walkoverWin); tp.addPlayedMinutes(minutes); ret.addExperience(match.getExperienceIncrease(min(90, minutes))); } else { HOLogger.instance().error(getClass(), "no lineup found in match " + match.getMatchSchedule().toLocaleDateTime() + " " + match.getHomeTeamName() + " - " + match.getGuestTeamName() ); } } } TrainingPoints trp = new TrainingPoints(wt, tp); // get experience increase of national team matches var id = this.getNationalTeamID(); if ( id != null && id != 0 && id != myID){ // TODO check if national matches are stored in database var nationalMatches = train.getNTmatches(); for (var match : nationalMatches){ MatchLineupTeam mlt = DBManager.instance().loadMatchLineupTeam(match.getMatchType().getId(), match.getMatchID(), this.getNationalTeamID()); var minutes = mlt.getTrainingMinutesPlayedInSectors(playerID, null, false); if ( minutes > 0 ) { ret.addExperience(match.getExperienceIncrease(min(90,minutes))); } } } ret.setTrainingPair(trp); } catch (Exception e) { HOLogger.instance().log(getClass(),e); } } return ret; } /** * Calculate the player strength on a specific lineup position * with or without form * * @param fo FactorObject with the skill weights for this position * @param useForm consider form? * @param normalized absolute or normalized contribution? * @return the player strength on this position */ float calcPosValue(FactorObject fo, boolean useForm, boolean normalized, @Nullable Weather weather, boolean useWeatherImpact) { if ((fo == null) || (fo.getSum() == 0.0f)) { return -1.0f; } // The stars formulas are changed by the user -> clear the cache if (!PlayerAbsoluteContributionCache.containsKey("lastChange") || ((Date) PlayerAbsoluteContributionCache.get("lastChange")).before(FormulaFactors.getLastChange())) { // System.out.println ("Clearing stars cache"); PlayerAbsoluteContributionCache.clear(); PlayerRelativeContributionCache.clear(); PlayerAbsoluteContributionCache.put("lastChange", new Date()); } /* * Create a key for the Hashtable cache * We cache every star rating to speed up calculation * (calling RPM.calcPlayerStrength() is quite expensive and this method is used very often) */ float loy = RatingPredictionManager.getLoyaltyHomegrownBonus(this); String key = fo.getPosition() + ":" + Helper.round(getGKskill() + getSub4Skill(KEEPER) + loy, 2) + "|" + Helper.round(getPMskill() + getSub4Skill(PLAYMAKING) + loy, 2) + "|" + Helper.round(getDEFskill() + getSub4Skill(DEFENDING) + loy, 2) + "|" + Helper.round(getWIskill() + getSub4Skill(WINGER) + loy, 2) + "|" + Helper.round(getPSskill() + getSub4Skill(PASSING) + loy, 2) + "|" + Helper.round(getSPskill() + getSub4Skill(SET_PIECES) + loy, 2) + "|" + Helper.round(getSCskill() + getSub4Skill(SCORING) + loy, 2) + "|" + getForm() + "|" + getStamina() + "|" + getExperience() + "|" + getPlayerSpecialty(); // used for Technical DefFW // Check if the key already exists in cache if (PlayerAbsoluteContributionCache.containsKey(key)) { // System.out.println ("Using star rating from cache, key="+key+", tablesize="+starRatingCache.size()); float rating = normalized ? (float) PlayerRelativeContributionCache.get(key) : (Float) PlayerAbsoluteContributionCache.get(key); if(useWeatherImpact){ rating *= getImpactWeatherEffect(weather); } return rating; } // Compute contribution float gkValue = fo.getGKfactor() * RatingPredictionManager.calcPlayerStrength(-2, this, KEEPER, useForm, false); float pmValue = fo.getPMfactor() * RatingPredictionManager.calcPlayerStrength(-2, this, PLAYMAKING, useForm, false); float deValue = fo.getDEfactor() * RatingPredictionManager.calcPlayerStrength(-2, this, DEFENDING, useForm, false); float wiValue = fo.getWIfactor() * RatingPredictionManager.calcPlayerStrength(-2, this, WINGER, useForm, false); float psValue = fo.getPSfactor() * RatingPredictionManager.calcPlayerStrength(-2, this, PASSING, useForm, false); float spValue = fo.getSPfactor() * RatingPredictionManager.calcPlayerStrength(-2, this, SET_PIECES, useForm, false); float scValue = fo.getSCfactor() * RatingPredictionManager.calcPlayerStrength(-2, this, SCORING, useForm, false); float val = gkValue + pmValue + deValue + wiValue + psValue + spValue + scValue; float absVal = val * 10; // multiplied by 10 for improved visibility float normVal = val / fo.getNormalizationFactor() * 100; // scaled between 0 and 100% // Put to cache PlayerAbsoluteContributionCache.put(key, absVal); PlayerRelativeContributionCache.put(key, normVal); // System.out.println ("Star rating put to cache, key="+key+", val="+val+", tablesize="+starRatingCache.size()); if (normalized) { return normVal; } else { return absVal; } } public float calcPosValue(byte pos, boolean useForm, boolean normalized, @Nullable Weather weather, boolean useWeatherImpact) { return calcPosValue(pos, useForm, normalized, UserParameter.instance().nbDecimals, weather, useWeatherImpact); } public float calcPosValue(byte pos, boolean useForm, @Nullable Weather weather, boolean useWeatherImpact) { return calcPosValue(pos, useForm, false, weather, useWeatherImpact); } /** * Calculate the player strength on a specific lineup position * with or without form * * @param pos position from IMatchRoleID (TORWART.. POS_ZUS_INNENV) * @param useForm consider form? * @return the player strength on this position */ public float calcPosValue(byte pos, boolean useForm, boolean normalized, int nb_decimals, @Nullable Weather weather, boolean useWeatherImpact) { float es; FactorObject factor = FormulaFactors.instance().getPositionFactor(pos); // Fix for TDF if (pos == IMatchRoleID.FORWARD_DEF && this.getPlayerSpecialty() == PlayerSpeciality.TECHNICAL) { factor = FormulaFactors.instance().getPositionFactor(IMatchRoleID.FORWARD_DEF_TECH); } if (factor != null) { es = calcPosValue(factor, useForm, normalized, weather, useWeatherImpact); } else { // For Coach or factor not found return 0 return 0.0f; } return Helper.round(es, nb_decimals); } /** * Copy the skills of old player. * Used by training * * @param old player to copy from */ public void copySkills(Player old) { for (int skillType = 0; skillType <= LOYALTY; skillType++) { setValue4Skill(skillType, old.getValue4Skill(skillType)); } } ////////////////////////////////////////////////////////////////////////////////// //equals ///////////////////////////////////////////////////////////////////////////////// @Override public boolean equals(Object obj) { boolean equals = false; if (obj instanceof Player) { equals = ((Player) obj).getPlayerID() == m_iSpielerID; } return equals; } /** * Does this player have a training block? * * @return training block */ public boolean hasTrainingBlock() { return m_bTrainingBlock; } /** * Set the training block of this player (true/false) * * @param isBlocked new value */ public void setTrainingBlock(boolean isBlocked) { this.m_bTrainingBlock = isBlocked; } public Integer getNationalTeamID() { return nationalTeamId; } public void setNationalTeamId( Integer id){ this.nationalTeamId=id; } public double getSubExperience() { return this.subExperience; } public void setSubExperience( Double experience){ if ( experience != null ) this.subExperience = experience; else this.subExperience=0; } public List<FuturePlayerTraining> getFuturePlayerTrainings(){ if ( futurePlayerTrainings == null){ futurePlayerTrainings = DBManager.instance().getFuturePlayerTrainings(this.getPlayerID()); if (futurePlayerTrainings.size()>0) { var start = HOVerwaltung.instance().getModel().getBasics().getHattrickWeek(); var remove = new ArrayList<FuturePlayerTraining>(); for (var t : futurePlayerTrainings) { if (t.endsBefore(start)){ remove.add(t); } } futurePlayerTrainings.removeAll(remove); } } return futurePlayerTrainings; } /** * Get the training priority of a hattrick week. If user training plan is given for the week this user selection is * returned. If no user plan is available, the training priority is determined by the player's best position. * * @param wt * used to get priority depending from the player's best position. * @param trainingDate * the training week * @return * the training priority */ public FuturePlayerTraining.Priority getTrainingPriority(WeeklyTrainingType wt, HODateTime trainingDate) { for ( var t : getFuturePlayerTrainings()) { if (t.contains(trainingDate)) { return t.getPriority(); } } // get Prio from best position int position = HelperWrapper.instance().getPosition(this.getIdealPosition()); for ( var p: wt.getTrainingSkillBonusPositions()){ if ( p == position) return FuturePlayerTraining.Priority.FULL_TRAINING; } for ( var p: wt.getTrainingSkillPositions()){ if ( p == position) { if ( wt.getTrainingType() == TrainingType.SET_PIECES) return FuturePlayerTraining.Priority.PARTIAL_TRAINING; return FuturePlayerTraining.Priority.FULL_TRAINING; } } for ( var p: wt.getTrainingSkillPartlyTrainingPositions()){ if ( p == position) return FuturePlayerTraining.Priority.PARTIAL_TRAINING; } for ( var p: wt.getTrainingSkillOsmosisTrainingPositions()){ if ( p == position) return FuturePlayerTraining.Priority.OSMOSIS_TRAINING; } return null; // No training } /** * Set training priority for a time interval. * Previously saved trainings of this interval are overwritten or deleted. * @param prio new training priority for the given time interval * @param from first week with new training priority * @param to last week with new training priority, null means open end */ public void setFutureTraining(FuturePlayerTraining.Priority prio, HODateTime from, HODateTime to) { var removeIntervals = new ArrayList<FuturePlayerTraining>(); for (var t : getFuturePlayerTrainings()) { if (t.cut(from, to) || t.cut(HODateTime.HT_START, HOVerwaltung.instance().getModel().getBasics().getHattrickWeek())) { removeIntervals.add(t); } } futurePlayerTrainings.removeAll(removeIntervals); if (prio != null) { futurePlayerTrainings.add(new FuturePlayerTraining(this.getPlayerID(), prio, from, to)); } DBManager.instance().storeFuturePlayerTrainings(futurePlayerTrainings); } public String getBestPositionInfo(@Nullable Weather weather, boolean useWeatherImpact) { return MatchRoleID.getNameForPosition(getIdealPosition()) + " (" + getIdealPositionStrength(true, true, 1, weather, useWeatherImpact) + "%)"; } /** * training priority information of the training panel * * @param nextWeek training priorities after this week will be considered * @return if there is one user selected priority, the name of the priority is returned * if there are more than one selected priorities, "individual priorities" is returned * if is no user selected priority, the best position information is returned */ public String getTrainingPriorityInformation(HODateTime nextWeek) { String ret=null; for ( var t : getFuturePlayerTrainings()) { // if ( !t.endsBefore(nextWeek)){ if ( ret != null ){ ret = HOVerwaltung.instance().getLanguageString("trainpre.individual.prios"); break; } ret = t.getPriority().toString(); } } if ( ret != null ) return ret; return getBestPositionInfo(null, false); } private static final int[] trainingSkills= { KEEPER, SET_PIECES, DEFENDING, SCORING, WINGER, PASSING, PLAYMAKING }; /** * Calculates skill status of the player * * @param previousID Id of the previous download. Previous player status is loaded by this id. * @param trainingWeeks List of training week information */ public void calcSubskills(int previousID, List<TrainingPerWeek> trainingWeeks) { var playerBefore = DBManager.instance().getSpieler(previousID).stream() .filter(i -> i.getPlayerID() == this.getPlayerID()).findFirst().orElse(null); if (playerBefore == null) { playerBefore = this.CloneWithoutSubskills(); } // since we don't want to work with temp player objects we calculate skill by skill // whereas experience is calculated within the first skill boolean experienceSubDone = this.getExperience() > playerBefore.getExperience(); // Do not calculate sub on experience skill up var experienceSub = experienceSubDone ? 0 : playerBefore.getSubExperience(); // set sub to 0 on skill up for (var skill : trainingSkills) { var sub = playerBefore.getSub4Skill(skill); var valueBeforeTraining = playerBefore.getValue4Skill(skill); var valueAfterTraining = this.getValue4Skill(skill); if (trainingWeeks.size() > 0) { for (var training : trainingWeeks) { var trainingPerPlayer = calculateWeeklyTraining(training); if (trainingPerPlayer != null) { if (!this.hasTrainingBlock()) {// player training is not blocked (blocking is no longer possible) sub += trainingPerPlayer.calcSubskillIncrement(skill, valueBeforeTraining + sub, training.getTrainingDate()); if (valueAfterTraining > valueBeforeTraining) { if (sub > 1) { sub -= 1.; } else { sub = 0.f; } } else if (valueAfterTraining < valueBeforeTraining) { if (sub < 0) { sub += 1.f; } else { sub = .99f; } } else { if (sub > 0.99f) { sub = 0.99f; } else if (sub < 0f) { sub = 0f; } } valueBeforeTraining = valueAfterTraining; } if (!experienceSubDone) { var inc = trainingPerPlayer.getExperienceSub(); experienceSub += inc; if (experienceSub > 0.99) experienceSub = 0.99; var minutes = 0; var tp =trainingPerPlayer.getTrainingPair(); if ( tp != null){ minutes = tp.getTrainingDuration().getPlayedMinutes(); } else { HOLogger.instance().warning(getClass(), "no training info found"); } HOLogger.instance().info(getClass(), "Training " + training.getTrainingDate().toLocaleDateTime() + "; Minutes= " + minutes + "; Experience increment of " + this.getFullName() + "; increment: " + inc + "; new sub value=" + experienceSub ); } } } experienceSubDone = true; } if (valueAfterTraining < valueBeforeTraining) { sub = .99f; } else if (valueAfterTraining > valueBeforeTraining) { sub = 0; HOLogger.instance().error(getClass(), "skill up without training"); // missing training in database } this.setSubskill4PlayerSkill(skill, sub); this.setSubExperience(experienceSub); } } private Player CloneWithoutSubskills() { var ret = new Player(); ret.setHrfId(this.hrf_id); ret.copySkills(this); ret.setPlayerID(getPlayerID()); ret.setAge(getAlter()); ret.setLastName(getLastName()); return ret; } public PlayerCategory getPlayerCategory() { return playerCategory; } public void setPlayerCategory(PlayerCategory playerCategory) { this.playerCategory = playerCategory; } public String getPlayerStatement() { return playerStatement; } public void setPlayerStatement(String playerStatement) { this.playerStatement = playerStatement; } public String getOwnerNotes() { return ownerNotes; } public void setOwnerNotes(String ownerNotes) { this.ownerNotes = ownerNotes; } public Integer getLastMatchPosition() { return lastMatchPosition; } public void setLastMatchPosition(Integer lastMatchPosition) { this.lastMatchPosition = lastMatchPosition; } public Integer getLastMatchMinutes() { return lastMatchMinutes; } public void setLastMatchMinutes(Integer lastMatchMinutes) { this.lastMatchMinutes = lastMatchMinutes; } /** * Rating at end of game * @return Integer number of half rating stars */ public Integer getLastMatchRatingEndOfGame() { return lastMatchRatingEndOfGame; } /** * Rating at end of game * @param lastMatchRatingEndOfGame number of half rating stars */ public void setLastMatchRatingEndOfGame(Integer lastMatchRatingEndOfGame) { this.lastMatchRatingEndOfGame = lastMatchRatingEndOfGame; } public void setMotherClubId(Integer teamID) { this.motherclubId = teamID; } public void setMotherClubName(String teamName) { this.motherclubName = teamName; } public void setMatchesCurrentTeam(Integer matchesCurrentTeam) { this.matchesCurrentTeam=matchesCurrentTeam; } public Integer getMatchesCurrentTeam() { return this.matchesCurrentTeam; } static class PositionContribute { private final float m_rating; private final byte clPositionID; public PositionContribute(float rating, byte clPostionID) { m_rating = rating; clPositionID = clPostionID; } public float getRating() { return m_rating; } public byte getClPostionID() { return clPositionID; } } /** * Create a clone of the player with modified skill values if man marking is switched on. * Values of Defending, Winger, Playmaking, Scoring and Passing are reduced depending of the distance * between man marker and opponent man marked player * * @param manMarkingPosition * null - no man marking changes * Opposite - reduce skills by 50% * NotOpposite - reduce skills by 65% * NotInLineup - reduce skills by 10% * @return * this player, if no man marking changes are selected * New modified player, if man marking changes are selected */ public Player createManMarker(ManMarkingPosition manMarkingPosition) { if ( manMarkingPosition == null) return this; var ret = new Player(); var skillFactor = (float)(1 - manMarkingPosition.value / 100.); ret.setPlayerSpecialty(this.getPlayerSpecialty()); ret.setAgeDays(this.getAgeDays()); ret.setAge(this.getAlter()); ret.setAgressivitaet(this.getAgressivitaet()); ret.setAnsehen(this.getAnsehen()); ret.setCharakter(this.getCharakter()); ret.setExperience(this.getExperience()); ret.setSubExperience(this.getSubExperience()); ret.setFirstName(this.getFirstName()); ret.setLastName(this.getLastName()); ret.setForm(this.getForm()); ret.setLeadership(this.getLeadership()); ret.setStamina(this.getStamina()); ret.setLoyalty(this.getLoyalty()); ret.setHomeGrown(this.isHomeGrown()); ret.setPlayerID(this.getPlayerID()); ret.setInjuryWeeks(this.getInjuryWeeks()); ret.setSkillValue(KEEPER, this.getSkillValue(KEEPER)); ret.setSkillValue(DEFENDING, skillFactor * this.getSkillValue(DEFENDING)); ret.setSkillValue(WINGER, skillFactor * this.getSkillValue(WINGER)); ret.setSkillValue(PLAYMAKING, skillFactor * this.getSkillValue(PLAYMAKING)); ret.setSkillValue(SCORING, skillFactor * this.getSkillValue(SCORING)); ret.setSkillValue(PASSING, skillFactor * this.getSkillValue(PASSING)); ret.setSkillValue(STAMINA, this.getSkillValue(STAMINA)); ret.setSkillValue(FORM, this.getSkillValue(FORM)); ret.setSkillValue(SET_PIECES, this.getSkillValue(SET_PIECES)); ret.setSkillValue(LEADERSHIP, this.getSkillValue(LEADERSHIP)); ret.setSkillValue(LOYALTY, this.getSkillValue(LOYALTY)); return ret; } public enum ManMarkingPosition { /** * central defender versus attack * wingback versus winger * central midfield versus central midfield */ Opposite(50), /** * central defender versus winger, central midfield * wingback versus attack, central midfield * central midfield versus central attack, winger */ NotOpposite(65), /** * opponent player is not in lineup or * any other combination */ NotInLineup(10); private final int value; ManMarkingPosition(int v){this.value=v;} public static ManMarkingPosition fromId(int id) { return switch (id) { case 50 -> Opposite; case 65 -> NotOpposite; case 10 -> NotInLineup; default -> null; }; } public int getValue() {return value;} } }
ddusann/HO
src/main/java/core/model/player/Player.java
214,391
/** * ShapeChange - processing application schemas for geographic information * * This file is part of ShapeChange. ShapeChange takes a ISO 19109 * Application Schema from a UML model and translates it into a * GML Application Schema or other implementation representations. * * Additional information about the software can be found at * http://shapechange.net/ * * (c) 2002-2015 interactive instruments GmbH, Bonn, Germany * * 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/>. * * Contact: * interactive instruments GmbH * Trierer Strasse 70-72 * 53115 Bonn * Germany */ package de.interactive_instruments.ShapeChange.FOL; /** * @author Johannes Echterhoff */ public class Not extends LogicalPredicate { private Predicate predicate; public Not() { } /** * @return the predicate */ public Predicate getPredicate() { return predicate; } /** * @param predicate * the predicate to set */ public void setPredicate(Predicate predicate) { this.predicate = predicate; } @Override public String toString() { return "not (" + predicate.toString() + ")"; } }
ShapeChange/ShapeChange
src/main/java/de/interactive_instruments/ShapeChange/FOL/Not.java
214,392
/** * ShapeChange - processing application schemas for geographic information * * This file is part of ShapeChange. ShapeChange takes a ISO 19109 * Application Schema from a UML model and translates it into a * GML Application Schema or other implementation representations. * * Additional information about the software can be found at * http://shapechange.net/ * * (c) 2002-2020 interactive instruments GmbH, Bonn, Germany * * 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/>. * * Contact: * interactive instruments GmbH * Trierer Strasse 70-72 * 53115 Bonn * Germany */ package de.interactive_instruments.ShapeChange; /** * Processes a UML model that has been loaded by ShapeChange. * * @author Johannes Echterhoff (echterhoff at interactive-instruments dot de) * */ public interface Process { }
ShapeChange/ShapeChange
src/main/java/de/interactive_instruments/ShapeChange/Process.java
214,393
package model.entity; import javafx.scene.image.Image; import java.nio.file.Paths; /** * Timestretcher bonus to slow down the game screen speed for a while when it is collected */ public class TimeStretcher extends Collectible { /** * Constructor for Collectible item TimeStretcher */ public TimeStretcher(){ Image[] images = new Image[1]; images[0] = new Image(Paths.get("./images/bonus/timestrechter.png").toUri().toString()); super.setImages(images); } }
okeremd/1C.Icy-Tower
src/model/entity/TimeStretcher.java
214,395
/******************************************************************************* * Copyright (C) 2009-2012 Stefan Waldherr, Dominik Jain. * * This file is part of ProbCog. * * ProbCog 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. * * ProbCog 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 ProbCog. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package probcog.bayesnets.inference; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Vector; import probcog.bayesnets.core.BeliefNetworkEx; import probcog.bayesnets.inference.IJGP.JoinGraph.Arc; import probcog.exception.ProbCogException; import edu.ksu.cis.bnj.ver3.core.BeliefNode; import edu.ksu.cis.bnj.ver3.core.CPF; import edu.tum.cs.util.StringTool; import edu.tum.cs.util.datastruct.MutableDouble; /** * The Iterative Join-Graph Propagation algorithm as described by Dechter, Kask and Mateescu (2002) * @author Stefan Waldherr * @author Dominik Jain */ public class IJGP extends Sampler { protected JoinGraph jg; Vector<JoinGraph.Node> jgNodes; protected BeliefNode[] nodes; protected final boolean debug = false; protected int ibound; protected boolean verbose = true; public IJGP(BeliefNetworkEx bn) throws ProbCogException { super(bn); } @Override protected void _initialize() { // detect minimum bound ibound = 1; for (BeliefNode n : nodes) { int l = n.getCPF().getDomainProduct().length; if (l > ibound) ibound = l; } // construct join-graph if(verbose) out.printf("constructing join-graph with i-bound %d...\n", ibound); jg = new JoinGraph(bn, ibound); //jg.writeDOT(new File("jg.dot")); } @Override public String getAlgorithmName() { return String.format("IJGP[i-bound %d]", this.ibound); } /* * public IJGP(BeliefNetworkEx bn, int bound) { super(bn); this.nodes = * bn.bn.getNodes(); jg = new JoinGraph(bn, bound); jg.print(out); * jgNodes = jg.getTopologicalorder(); // construct join-graph } */ protected IDistributionBuilder createDistributionBuilder() { return new ImmediateDistributionBuilder(); } @Override public void _infer() throws ProbCogException { // Create topological order if(verbose) out.println("determining order..."); jgNodes = jg.getTopologicalorder(); if(debug) { out.println("Topological Order: "); for (int i = 0; i < jgNodes.size(); i++) { out.println(jgNodes.get(i).getShortName()); } } // process observed variables if(verbose) out.println("processing observed variables..."); for (JoinGraph.Node n : jgNodes) { Vector<BeliefNode> nodes = new Vector<BeliefNode>(n.getNodes()); for (BeliefNode belNode : nodes) { int nodeIdx = bn.getNodeIndex(belNode); int domainIdx = evidenceDomainIndices[nodeIdx]; if (domainIdx > -1) n.nodes.remove(belNode); } } out.printf("running propagation (%d steps)...\n", this.numSamples); for (int step = 1; step <= this.numSamples; step++) { out.printf("step %d\n", step); // for every node in JG in topological order and back: int s = jgNodes.size(); boolean direction = true; for (int j = 0; j < 2 * s; j++) { int i; if (j < s) i = j; else { i = 2 * s - j - 1; direction = false; } JoinGraph.Node u = jgNodes.get(i); //out.printf("step %d, %d/%d: %-60s\r", step, j, 2*s, u.getShortName()); int topIndex = jgNodes.indexOf(u); for (JoinGraph.Node v : u.getNeighbors()) { if ((direction && jgNodes.indexOf(v) < topIndex) || (!direction && jgNodes.indexOf(v) > topIndex)) { continue; } Arc arc = u.getArcToNode(v); arc.clearOutMessages(u); // construct cluster_v(u) Cluster cluster_u = new Cluster(u, v); // Include in cluster_H each function in cluster_u which // scope does not contain variables in elim(u,v) HashSet<BeliefNode> elim = new HashSet<BeliefNode>(u.nodes); // out.println(" Node " + u.getShortName() + // " and node " +v.getShortName() + " have separator " + // StringTool.join(", ", arc.separator)); elim.removeAll(arc.separator); Cluster cluster_H = cluster_u.getReducedCluster(elim); // denote by cluster_A the remaining functions Cluster cluster_A = cluster_u.copy(); cluster_A.subtractCluster(cluster_H); // DEBUG OUTPUT if (debug) { out.println(" cluster_v(u): \n" + cluster_u); out.println(" A: \n" + cluster_A); out.println(" H_(u,v): \n" + cluster_H); } // convert eliminator into varsToSumOver int[] varsToSumOver = new int[elim.size()]; int k = 0; for (BeliefNode n : elim) varsToSumOver[k++] = bn.getNodeIndex(n); // create message function and send to v MessageFunction m = new MessageFunction(arc.separator, varsToSumOver, cluster_A); m.calcuSave(evidenceDomainIndices.clone()); arc.addOutMessage(u, m); for (MessageFunction mf : cluster_H.functions) { mf.calcuSave(evidenceDomainIndices.clone()); arc.addOutMessage(u, mf); } for (BeliefNode n : cluster_H.cpts) { arc.addCPTOutMessage(u, n); } } } } // compute probabilities and store results in distribution out.println("computing results..."); SampledDistribution dist = createDistribution(); dist.Z = 1.0; for (int i = 0; i < nodes.length; i++) { //out.println("Computing: " + nodes[i].getName() + "\n"); if (evidenceDomainIndices[i] >= 0) { dist.values[i][evidenceDomainIndices[i]] = 1.0; continue; } // For every node X let u be a vertex in the join graph such that X // is in u // out.println(nodes[i]); JoinGraph.Node u = null; for (JoinGraph.Node node : jgNodes) { if (node.nodes.contains(nodes[i])) { u = node; break; } } if (u == null) throw new ProbCogException( "Could not find vertex in join graph containing variable " + nodes[i].getName()); // out.println("\nCalculating results for " + nodes[i]); // out.println(u); // compute sum for each domain value of i-th node int domSize = dist.values[i].length; double Z = 0.0; int[] nodeDomainIndices = evidenceDomainIndices.clone(); for (int j = 0; j < domSize; j++) { nodeDomainIndices[i] = j; MutableDouble sum = new MutableDouble(0.0); BeliefNode[] nodesToSumOver = u.nodes .toArray(new BeliefNode[u.nodes.size()]); computeSum(0, nodesToSumOver, nodes[i], new Cluster(u), nodeDomainIndices, sum); Z += (dist.values[i][j] = sum.value); } // normalize for (int j = 0; j < domSize; j++) dist.values[i][j] /= Z; } // dist.print(out); ((ImmediateDistributionBuilder)distributionBuilder).setDistribution(dist); } protected void computeSum(int i, BeliefNode[] varsToSumOver, BeliefNode excludedNode, Cluster u, int[] nodeDomainIndices, MutableDouble result) { if (i == varsToSumOver.length) { result.value += u.product(nodeDomainIndices); return; } if (varsToSumOver[i] == excludedNode) computeSum(i + 1, varsToSumOver, excludedNode, u, nodeDomainIndices, result); else { for (int j = 0; j < varsToSumOver[i].getDomain().getOrder(); j++) { nodeDomainIndices[this.getNodeIndex(varsToSumOver[i])] = j; computeSum(i + 1, varsToSumOver, excludedNode, u, nodeDomainIndices, result); } } } protected class Cluster { HashSet<BeliefNode> cpts = new HashSet<BeliefNode>(); HashSet<MessageFunction> functions = new HashSet<MessageFunction>(); JoinGraph.Node node; public Cluster(JoinGraph.Node u) { // Constructor for cluster(u) this.node = u; // add to the cluster all CPTs of the given node for (CPF cpf : u.functions) cpts.add(cpf.getDomainProduct()[0]); // add all incoming messages of n for (JoinGraph.Node nb : u.getNeighbors()) { JoinGraph.Arc arc = u.arcs.get(nb); HashSet<MessageFunction> m = arc.getInMessage(u); if (!m.isEmpty()) functions.addAll(m); HashSet<BeliefNode> bn = arc.getCPTInMessage(u); if (!bn.isEmpty()) cpts.addAll(bn); } } public Cluster(JoinGraph.Node u, JoinGraph.Node v) { // Constructor for cluster_v(u) this.node = u; // add to the cluster all CPTs of the given node for (CPF cpf : u.functions) cpts.add(cpf.getDomainProduct()[0]); // add all incoming messages of n for (JoinGraph.Node nb : u.getNeighbors()) { if (!nb.equals(v)) { JoinGraph.Arc arc = u.arcs.get(nb); HashSet<MessageFunction> m = arc.getInMessage(u); if (!m.isEmpty()) functions.addAll(m); HashSet<BeliefNode> bn = arc.getCPTInMessage(u); if (!bn.isEmpty()) cpts.addAll(bn); } } } public Cluster() { } public String toString() { StringBuffer sb = new StringBuffer(); sb.append(StringTool.join(", ", this.cpts)); sb.append("; "); sb.append(StringTool.join(", ", this.functions)); return sb.toString(); } public void excludeMessagesFrom(JoinGraph.Node n) { JoinGraph.Arc arc = node.arcs.get(n); for (MessageFunction mf : arc.getInMessage(node)) { if (functions.contains(mf)) functions.remove(mf); } for (BeliefNode bn : arc.getCPTInMessage(node)) { if (cpts.contains(bn)) functions.remove(bn); } } public Cluster copy() { Cluster copyCluster = new Cluster(); for (BeliefNode cpt : cpts) { copyCluster.cpts.add(cpt); } for (MessageFunction f : functions) { copyCluster.functions.add(f); } return copyCluster; } public Cluster getReducedCluster(HashSet<BeliefNode> nodes) throws ProbCogException { // deletes all functions and arcs in the cluster whose scope // contains the given nodes Cluster redCluster = this.copy(); for (BeliefNode bn : nodes) { HashSet<BeliefNode> foo = (HashSet<BeliefNode>) cpts.clone(); for (BeliefNode n : foo) { BeliefNode[] domProd = n.getCPF().getDomainProduct(); /* * if (bn.equals(n)){ redCluster.cpts.remove(n); } */ for (int i = 0; i < domProd.length; i++) { if (bn.equals(domProd[i])) { redCluster.cpts.remove(n); break; } } } for (MessageFunction m : ((HashSet<MessageFunction>) functions.clone())) { if (m.scope.contains(bn)) redCluster.functions.remove(m); } } return redCluster; } public void subtractCluster(Cluster c2) { // deletes all functions and arcs of the cluster that are also in // cluster c2 for (BeliefNode n : ((HashSet<BeliefNode>) c2.cpts.clone())) { // TODO // nonsense cpts.remove(n); } for (MessageFunction m : ((HashSet<MessageFunction>) c2.functions .clone())) { functions.remove(m); } } public double product(int[] nodeDomainIndices) { double ret = 1.0; for (BeliefNode n : cpts) { // out.println(" " + n.getCPF().toString()); ret *= getCPTProbability(n, nodeDomainIndices); } for (MessageFunction f : this.functions) { // out.println(" " + f); ret *= f.compute(nodeDomainIndices); } return ret; } } protected class MessageFunction { protected int[] varsToSumOver; protected MessageTable table; HashSet<BeliefNode> cpts; Iterable<MessageFunction> childFunctions; HashSet<BeliefNode> scope; public MessageFunction(HashSet<BeliefNode> scope, int[] varsToSumOver, Cluster cluster) { this.scope = scope; this.varsToSumOver = varsToSumOver; this.cpts = cluster.cpts; this.childFunctions = cluster.functions; this.table = null; } public void calcuSave(int[] nodeDomainIndices) { table = new MessageTable(new Vector<BeliefNode>(scope), 0); int[] scopeToSumOver = new int[scope.size()]; int k = 0; for (BeliefNode n : scope) scopeToSumOver[k++] = bn.getNodeIndex(n); calcuSave(scopeToSumOver, 0, nodeDomainIndices.clone()); } public void calcuSave(int[] scopeToSumOver, int i, int[] nodeDomainIndices) { if (i == scope.size()) { table.addEntry(nodeDomainIndices, compute(nodeDomainIndices)); return; } else { int idxVar = scopeToSumOver[i]; for (int v = 0; v < nodes[idxVar].getDomain().getOrder(); v++) { nodeDomainIndices[idxVar] = v; calcuSave(scopeToSumOver, i + 1, nodeDomainIndices); } } } public double compute(int[] nodeDomainIndices) { if (!table.containsEntry(nodeDomainIndices)) { MutableDouble sum = new MutableDouble(0.0); compute(varsToSumOver, 0, nodeDomainIndices, sum); return sum.value; } else { return table.getEntry(nodeDomainIndices); } } protected void compute(int[] varsToSumOver, int i, int[] nodeDomainIndices, MutableDouble sum) { if (i == varsToSumOver.length) { double result = 1.0; for (BeliefNode node : cpts) result *= getCPTProbability(node, nodeDomainIndices); for (MessageFunction h : childFunctions) result *= h.compute(nodeDomainIndices); sum.value += result; return; } int idxVar = varsToSumOver[i]; for (int v = 0; v < nodes[idxVar].getDomain().getOrder(); v++) { nodeDomainIndices[idxVar] = v; compute(varsToSumOver, i + 1, nodeDomainIndices, sum); } } public String toString() { StringBuffer sb = new StringBuffer("MF["); sb.append("scope: " + StringTool.join(", ", scope)); sb.append("; CPFs:"); int i = 0; for (BeliefNode n : this.cpts) { if (i++ > 0) sb.append("; "); sb.append(n.getCPF().toString()); } sb.append("; children: "); sb.append(StringTool.join("; ", this.childFunctions)); sb.append("]"); return sb.toString(); } protected class MessageTable { protected Vector<BeliefNode> scope; protected boolean leaf; protected MessageTable[] map; protected Double[] result; public MessageTable(Vector<BeliefNode> scope, int i) { int domSize = scope.get(i).getDomain().getOrder(); this.map = new MessageTable[domSize]; this.scope = scope; if (i == scope.size() - 1) { leaf = true; result = new Double[domSize]; } else { leaf = false; result = null; for (int j = 0; j < scope.get(i).getDomain().getOrder(); j++) { map[j] = new MessageTable(scope, i + 1); } } } public void addEntry(int[] domainIndices, double entry) { addEntry(domainIndices, 0, entry); } public void addEntry(int[] domainIndices, int i, double entry) { if (i != scope.size() - 1) { int idx = domainIndices[bn.getNodeIndex(scope.get(i))]; map[idx].addEntry(domainIndices, i + 1, entry); } else { int idx = domainIndices[bn.getNodeIndex(scope.get(i))]; result[idx] = entry; } } public double getEntry(int[] domainIndices) { return getEntry(domainIndices, 0); } public double getEntry(int[] domainIndices, int i) { if (i != scope.size() - 1) { int idx = domainIndices[bn.getNodeIndex(scope.get(i))]; return map[idx].getEntry(domainIndices, i + 1); } else { int idx = domainIndices[bn.getNodeIndex(scope.get(i))]; return result[idx]; } } public boolean containsEntry(int[] domainIndices){ return containsEntry(domainIndices, 0); } public boolean containsEntry(int[] domainIndices, int i){ if (i != scope.size() - 1){ int idx = domainIndices[bn.getNodeIndex(scope.get(i))]; if (map[idx] == null){ return false; } else{ return map[idx].containsEntry(domainIndices, i+1); } } else{ int idx = domainIndices[bn.getNodeIndex(scope.get(i))]; return (result[idx] != null); } } } } protected static class BucketVar { public HashSet<BeliefNode> nodes; public CPF cpf = null; public Vector<MiniBucket> parents; public BeliefNode idxVar; public BucketVar(HashSet<BeliefNode> nodes) { this(nodes, null); } public BucketVar(HashSet<BeliefNode> nodes, MiniBucket parent) { this.nodes = nodes; if (nodes.size() == 0) throw new RuntimeException( "Must provide non-empty set of nodes."); this.parents = new Vector<MiniBucket>(); if (parent != null) parents.add(parent); } public void setFunction(CPF cpf) { this.cpf = cpf; } public void addInArrow(MiniBucket parent) { parents.add(parent); } public BeliefNode getMaxNode(BeliefNetworkEx bn) { // returns the BeliefNode of a bucket variable highest in the // topological order BeliefNode maxNode = null; int[] topOrder = bn.getTopologicalOrder(); for (int i = topOrder.length - 1; i > -1; i--) { for (BeliefNode node : nodes) { if (bn.getNodeIndex(node) == topOrder[i]) { return node; } } } return maxNode; } public String toString() { return "[" + StringTool.join(" ", this.nodes) + "]"; } public boolean equals(BucketVar other) { if (other.nodes.size() != this.nodes.size()) return false; for (BeliefNode n : nodes) if (!other.nodes.contains(n)) return false; return true; } } protected static class MiniBucket { public HashSet<BucketVar> items; public Bucket bucket; public HashSet<MiniBucket> parents; public BucketVar child; public MiniBucket(Bucket bucket) { this.items = new HashSet<BucketVar>(); this.bucket = bucket; this.child = null; this.parents = new HashSet<MiniBucket>(); } public void addVar(BucketVar bv) { items.add(bv); for (MiniBucket p : bv.parents) parents.add(p); } public String toString() { return "Minibucket[" + StringTool.join(" ", items) + "]"; } } protected static class Bucket { public BeliefNode bucketNode; public HashSet<BucketVar> vars = new HashSet<BucketVar>(); public Vector<MiniBucket> minibuckets = new Vector<MiniBucket>(); public Bucket(BeliefNode bucketNode) { this.bucketNode = bucketNode; } public void addVar(BucketVar bv) { for (BucketVar v : vars) if (v.equals(bv)) { for (MiniBucket p : bv.parents) v.addInArrow(p); return; } vars.add(bv); } /** * create minibuckets of size bound * * @param bound */ public void partition(int bound) { minibuckets.add(new MiniBucket(this)); HashSet<BeliefNode> count = new HashSet<BeliefNode>(); for (BucketVar bv : vars) { int newNodes = 0; for (BeliefNode n : bv.nodes) { if (!count.contains(n)) { newNodes++; } } if (count.size() + newNodes > bound) { // create a new // minibucket minibuckets.add(new MiniBucket(this)); count.clear(); count.addAll(bv.nodes); } else { count.addAll(bv.nodes); } minibuckets.lastElement().addVar(bv); } } public HashSet<BucketVar> createScopeFunctions() { HashSet<BucketVar> newVars = new HashSet<BucketVar>(); for (MiniBucket mb : minibuckets) { HashSet<BeliefNode> nodes = new HashSet<BeliefNode>(); for (BucketVar bv : mb.items) { for (BeliefNode bn : bv.nodes) { if (bn != bucketNode) nodes.add(bn); } } if (nodes.size() != 0) { // TODO check correctness BucketVar newBucketVar = new BucketVar(nodes, mb); newVars.add(newBucketVar); } } return newVars; } public String toString() { return StringTool.join(" ", vars); } } protected static class SchematicMiniBucket { public HashMap<BeliefNode, Bucket> bucketMap; public BeliefNetworkEx bn; public SchematicMiniBucket(BeliefNetworkEx bn, int bound) { this.bn = bn; bucketMap = new HashMap<BeliefNode, Bucket>(); // order the variables from X_1 to X_n BeliefNode[] nodes = bn.bn.getNodes(); int[] topOrder = bn.getTopologicalOrder(); // place each CPT in the bucket of the highest index for (int i = topOrder.length - 1; i > -1; i--) { Bucket bucket = new Bucket(nodes[topOrder[i]]); int[] cpt = bn.getDomainProductNodeIndices(nodes[topOrder[i]]); HashSet<BeliefNode> cptNodes = new HashSet<BeliefNode>(); for (int j : cpt) { cptNodes.add(nodes[j]); } BucketVar bv = new BucketVar(cptNodes); bv.setFunction(nodes[topOrder[i]].getCPF()); bucket.addVar(bv); bucketMap.put(nodes[topOrder[i]], bucket); } // partition buckets and create arcs for (int i = topOrder.length - 1; i > -1; i--) { Bucket oldVar = bucketMap.get(nodes[topOrder[i]]); oldVar.partition(bound); HashSet<BucketVar> scopes = oldVar.createScopeFunctions(); for (BucketVar bv : scopes) { // add new variables to the bucket with the highest index BeliefNode node = bv.getMaxNode(bn); bucketMap.get(node).addVar(bv); } } } public void print(PrintStream out) { BeliefNode[] nodes = bn.bn.getNodes(); int[] order = bn.getTopologicalOrder(); for (int i = nodes.length - 1; i >= 0; i--) { BeliefNode n = nodes[order[i]]; out.printf("%s: %s\n", n.toString(), bucketMap.get(n)); } } public Vector<MiniBucket> getMiniBuckets() { Vector<MiniBucket> mb = new Vector<MiniBucket>(); for (Bucket b : bucketMap.values()) { mb.addAll(b.minibuckets); } return mb; } public Vector<Bucket> getBuckets() { return new Vector<Bucket>(bucketMap.values()); } } protected static class JoinGraph { HashSet<Node> nodes; HashMap<MiniBucket, Node> bucket2node = new HashMap<MiniBucket, Node>(); public JoinGraph(BeliefNetworkEx bn, int bound) { nodes = new HashSet<Node>(); // apply procedure schematic mini-bucket(bound) SchematicMiniBucket smb = new SchematicMiniBucket(bn, bound); // out.println("\nJoin graph decomposition:"); // smb.print(out); Vector<MiniBucket> minibuckets = smb.getMiniBuckets(); // associate each minibucket with a node // out.println("\nJoin graph nodes:"); for (MiniBucket mb : minibuckets) { // out.println(mb); Node newNode = new Node(mb); // out.println(newNode); nodes.add(newNode); bucket2node.put(mb, newNode); } // copy parent structure for (MiniBucket mb : minibuckets) { for (MiniBucket p : mb.parents) { bucket2node.get(mb).parents.add(bucket2node.get(p)); } } // keep the arcs and label them by regular separator for (MiniBucket mb : minibuckets) { for (MiniBucket par : mb.parents) { Node n1 = bucket2node.get(par); Node n2 = bucket2node.get(mb); new Arc(n1, n2); } } // connect the mini-bucket clusters for (MiniBucket mb1 : minibuckets) { for (MiniBucket mb2 : minibuckets) { if (mb1 != mb2 && mb1.bucket == mb2.bucket) { new Arc(bucket2node.get(mb1), bucket2node.get(mb2)); } } } } public void print(PrintStream out) { int i = 0; for (Node n : nodes) { out.printf("Node%d: %s\n", i++, StringTool.join(", ", n.nodes)); for (CPF cpf : n.functions) { out.printf(" CPFS: %s | %s\n", cpf.getDomainProduct()[0], StringTool.join(", ", cpf.getDomainProduct())); } } } public void writeDOT(File f) throws FileNotFoundException { PrintStream ps = new PrintStream(f); ps.println("graph {"); for (Node n : nodes) { for (Node n2 : n.getNeighbors()) { ps.printf("\"%s\" -- \"%s\";\n", n.getShortName(), n2 .getShortName()); } } ps.println("}"); } public Vector<Node> getTopologicalorder() { Vector<Node> topOrder = new Vector<Node>(); HashSet<Node> nodesLeft = new HashSet<Node>(); nodesLeft.addAll(nodes); for (Node n : nodes) { if (n.parents.isEmpty()) { topOrder.add(n); nodesLeft.remove(n); } } // out.println("Start topological order with " // +StringTool.join(", ", topOrder)); int i = 0; while (!nodesLeft.isEmpty() && i < 10) { HashSet<Node> removeNodes = new HashSet<Node>(); // out.println(" Current order: " +StringTool.join(", ", // topOrder)); for (Node n : nodesLeft) { // out.println(" - Check for " + n.getShortName() + // " with parents " + StringTool.join(", ", n.mb.parents)); if (topOrder.containsAll(n.parents)) { // out.println(" -- Can be inserted!"); topOrder.add(n); removeNodes.add(n); } } nodesLeft.removeAll(removeNodes); // i++; } return topOrder; } public static class Arc { HashSet<BeliefNode> separator = new HashSet<BeliefNode>(); // messages between Nodes Vector<Node> nodes = new Vector<Node>(); HashMap<Node, HashSet<MessageFunction>> outMessage = new HashMap<Node, HashSet<MessageFunction>>(); HashMap<Node, HashSet<BeliefNode>> outCPTMessage = new HashMap<Node, HashSet<BeliefNode>>(); public Arc(Node n0, Node n1) { if (n0 != n1) { // create separator /* * if (n0.mb.bucket == n1.mb.bucket) * separator.add(n0.mb.bucket.bucketNode); else { */ separator = (HashSet<BeliefNode>) n0.nodes.clone(); separator.retainAll(n1.nodes); // } // arc informations nodes.add(n0); nodes.add(n1); n0.addArc(n1, this); n1.addArc(n0, this); outMessage.put(n0, new HashSet<MessageFunction>()); outMessage.put(n1, new HashSet<MessageFunction>()); outCPTMessage.put(n0, new HashSet<BeliefNode>()); outCPTMessage.put(n1, new HashSet<BeliefNode>()); } else throw new RuntimeException("1-node loop in graph"); } public Node getNeighbor(Node n) { // needs to throw exception when n not in nodes return nodes.get((nodes.indexOf(n) + 1) % 2); } public void addOutMessage(Node n, MessageFunction m) { outMessage.get(n).add(m); } public HashSet<MessageFunction> getOutMessages(Node n) { return outMessage.get(n); } public HashSet<MessageFunction> getInMessage(Node n) { return this.getOutMessages(this.getNeighbor(n)); } public void addCPTOutMessage(Node n, BeliefNode bn) { outCPTMessage.get(n).add(bn); } public HashSet<BeliefNode> getCPTOutMessages(Node n) { return outCPTMessage.get(n); } public HashSet<BeliefNode> getCPTInMessage(Node n) { return this.getCPTOutMessages(this.getNeighbor(n)); } public void clearOutMessages(Node n) { outMessage.get(n).clear(); outCPTMessage.get(n).clear(); } } public static class Node { MiniBucket mb; Vector<CPF> functions = new Vector<CPF>(); HashSet<BeliefNode> nodes = new HashSet<BeliefNode>(); HashSet<Node> parents; HashMap<Node, Arc> arcs = new HashMap<Node, Arc>(); public Node(MiniBucket mb) { this.mb = mb; this.parents = new HashSet<Node>(); for (BucketVar var : mb.items) { nodes.addAll(var.nodes); if (var.cpf != null) functions.add(var.cpf); } } public void addArc(Node n, Arc arc) { arcs.put(n, arc); } public HashSet<Node> getNeighbors() { return new HashSet<Node>(arcs.keySet()); } public Arc getArcToNode(Node n) { return arcs.get(n); } public Collection<BeliefNode> getNodes() { return nodes; } public String toString() { return "Supernode[" + StringTool.join(",", nodes) + "; " + StringTool.join("; ", this.functions) + "]"; } public String getShortName() { return StringTool.join(",", nodes); } } } }
opcode81/ProbCog
src/main/java/probcog/bayesnets/inference/IJGP.java
214,396
/** * ShapeChange - processing application schemas for geographic information * * This file is part of ShapeChange. ShapeChange takes a ISO 19109 * Application Schema from a UML model and translates it into a * GML Application Schema or other implementation representations. * * Additional information about the software can be found at * http://shapechange.net/ * * (c) 2002-2013 interactive instruments GmbH, Bonn, Germany * * 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/>. * * Contact: * interactive instruments GmbH * Trierer Strasse 70-72 * 53115 Bonn * Germany */ package de.interactive_instruments.ShapeChange; /** * @author Johannes Echterhoff (echterhoff at interactive-instruments dot * de) */ public class Namespace { private String ns; private String location; private String nsabr; public Namespace(String nsabr, String ns, String location) { super(); this.nsabr = nsabr; this.ns = ns; this.location = location; } public String getNsabr() { return nsabr; } public String getNs() { return ns; } public String getLocation() { return location; } }
ShapeChange/ShapeChange
src/main/java/de/interactive_instruments/ShapeChange/Namespace.java
214,397
/** * ShapeChange - processing application schemas for geographic information * * This file is part of ShapeChange. ShapeChange takes a ISO 19109 * Application Schema from a UML model and translates it into a * GML Application Schema or other implementation representations. * * Additional information about the software can be found at * http://shapechange.net/ * * (c) 2002-2015 interactive instruments GmbH, Bonn, Germany * * 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/>. * * Contact: * interactive instruments GmbH * Trierer Strasse 70-72 * 53115 Bonn * Germany */ package de.interactive_instruments.ShapeChange.FOL; /** * @author Johannes Echterhoff */ public class IsNull extends UnaryComparisonPredicate { public IsNull() { super(); } @Override public String toString() { return "is-null("+expr.toString()+")"; } }
ShapeChange/ShapeChange
src/main/java/de/interactive_instruments/ShapeChange/FOL/IsNull.java
214,398
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package aufgabentexte; /** * * @author simon */ public class VigenereAufgaben extends Aufgaben { public VigenereAufgaben() { super(15); for(int i = 0; i < anweisungstext.length; i = i+1) { verschluesselungstyp[i] = 1; } //Aufgabe 1: anweisungstext[0] = "Vigenere"; schluessel[0] = "ab"; aufgabentyp[0] = 1; //Aufgabe 2: anweisungstext[1] = "entschluesselt"; schluessel[1] = "ex"; aufgabentyp[1] = 2; //Aufgabe 3: anweisungstext[2] = "Sie wurde im 16. Jahrhundert entwickelt"; schluessel[2] = "muwd"; aufgabentyp[2] = 2; //Aufgabe 4: anweisungstext[3] = "Und nach ihrem Erfinder Blaise de Vigenere benannt"; schluessel[3] = "blaise"; aufgabentyp[3] = 1; //Aufgabe 5: anweisungstext[4] = "Sie galt lange Zeit als nicht knackbar"; schluessel[4] = "ebs"; aufgabentyp[4] = 3; //Aufgabe 6: anweisungstext[5] = "Deshalb wurde sie auch le chiffre indechiffrable genannt"; schluessel[5] = "wfgdhx"; aufgabentyp[5] = 1; //Aufgabe 7: anweisungstext[6] = "Das heißt auf Deutsch übersetzt die unentzifferbare Verschluesselung"; schluessel[6] = "deutsch"; aufgabentyp[6] = 2; //Aufgabe 8: anweisungstext[7] = "1854 gelang aber das erste mal die Entzifferung"; schluessel[7] = "abcefh"; aufgabentyp[7] = 3; //Aufgabe 9: anweisungstext[8] = "Diese Entzifferung ist aber nur bei schlechten schluesseln möglich"; schluessel[8] = "schluessel"; aufgabentyp[8] = 1; //Aufgabe 10: anweisungstext[9] = "Verwendet man hingegen einen schluessel der aus vielen zufällig zusammengesetzten Zeichen besteht, ist die Verschluesselung immer noch unknakcbar"; schluessel[9] = "nsuaabxnk"; aufgabentyp[9] = 2; //Aufgabe 11: anweisungstext[10] = "Eine gute schluessellänge ist die Länge des Eingabetextes. Die wird auch bei der One Time Pad Verschluesselung verwirklicht"; schluessel[10] = "onetimepad"; aufgabentyp[10] = 2; //Aufgabe 12: anweisungstext[11] = "Mehr Informationen zur One Time Pad Verschluesselung findest du in unserem Programm unter One Time Pad"; schluessel[11] = "yxdcba"; aufgabentyp[11] = 3; //Aufgabe 13: anweisungstext[12] = "Ein schlechter Schlussel ist ein zu kurzer Schluessel oder ein leicht erratbarer schluessel"; schluessel[12] = "nfnsbxdk"; aufgabentyp[12] = 1; //Aufgabe 14: anweisungstext[13] = "Vigenere ist beispielsweise ein schlechter schluessel"; schluessel[13] = "vigenere"; aufgabentyp[13] = 3; //Aufgabe 15: anweisungstext[14] = "Jetzt solltet ihr ja wissen, worauf es beim schluessel der Vigenere Verschluesselung ankommt um diese schwer knackbar zu machen"; schluessel[14] = "hnfxlgutvbrnm"; aufgabentyp[14] = 2; } }
PSeminarKryptographie/MonkeyCrypt
src/aufgabentexte/VigenereAufgaben.java
214,399
/** * ShapeChange - processing application schemas for geographic information * * This file is part of ShapeChange. ShapeChange takes a ISO 19109 * Application Schema from a UML model and translates it into a * GML Application Schema or other implementation representations. * * Additional information about the software can be found at * http://shapechange.net/ * * (c) 2002-2015 interactive instruments GmbH, Bonn, Germany * * 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/>. * * Contact: * interactive instruments GmbH * Trierer Strasse 70-72 * 53115 Bonn * Germany */ package de.interactive_instruments.ShapeChange.FOL; /** * @author Johannes Echterhoff */ public abstract class Literal extends Expression { }
ShapeChange/ShapeChange
src/main/java/de/interactive_instruments/ShapeChange/FOL/Literal.java
214,400
/** * ShapeChange - processing application schemas for geographic information * * This file is part of ShapeChange. ShapeChange takes a ISO 19109 * Application Schema from a UML model and translates it into a * GML Application Schema or other implementation representations. * * Additional information about the software can be found at * http://shapechange.net/ * * (c) 2002-2015 interactive instruments GmbH, Bonn, Germany * * 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/>. * * Contact: * interactive instruments GmbH * Trierer Strasse 70-72 * 53115 Bonn * Germany */ package de.interactive_instruments.ShapeChange.FOL; /** * @author Johannes Echterhoff */ public class EqualTo extends BinaryComparisonPredicate { public EqualTo() { super(); } @Override public String toString() { return exprLeft.toString() + " = "+exprRight.toString(); } }
ShapeChange/ShapeChange
src/main/java/de/interactive_instruments/ShapeChange/FOL/EqualTo.java
214,402
/** * ShapeChange - processing application schemas for geographic information * * This file is part of ShapeChange. ShapeChange takes a ISO 19109 * Application Schema from a UML model and translates it into a * GML Application Schema or other implementation representations. * * Additional information about the software can be found at * http://shapechange.net/ * * (c) 2002-2015 interactive instruments GmbH, Bonn, Germany * * 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/>. * * Contact: * interactive instruments GmbH * Trierer Strasse 70-72 * 53115 Bonn * Germany */ package de.interactive_instruments.ShapeChange.FOL; /** * @author Johannes Echterhoff */ public class IsTypeOf extends BinaryComparisonPredicate { public IsTypeOf() { super(); } @Override public String toString() { return exprLeft.toString() + " is-type-of " + exprRight.toString(); } }
ShapeChange/ShapeChange
src/main/java/de/interactive_instruments/ShapeChange/FOL/IsTypeOf.java
214,403
/** * ShapeChange - processing application schemas for geographic information * * This file is part of ShapeChange. ShapeChange takes a ISO 19109 * Application Schema from a UML model and translates it into a * GML Application Schema or other implementation representations. * * Additional information about the software can be found at * http://shapechange.net/ * * (c) 2002-2013 interactive instruments GmbH, Bonn, Germany * * 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/>. * * Contact: * interactive instruments GmbH * Trierer Strasse 70-72 * 53115 Bonn * Germany */ package de.interactive_instruments.ShapeChange; import java.util.Comparator; import org.apache.commons.lang3.StringUtils; /** * @author Johannes Echterhoff (echterhoff at interactive-instruments dot de) */ public class XmlNamespace { public static final Comparator<XmlNamespace> comparator = Comparator .comparing(XmlNamespace::getNsabr, Comparator.nullsFirst(Comparator.naturalOrder())) .thenComparing(XmlNamespace::getNs, Comparator.nullsFirst(Comparator.naturalOrder())) .thenComparing(XmlNamespace::getLocation, Comparator.nullsFirst(Comparator.naturalOrder())) .thenComparing(XmlNamespace::getPackageName, Comparator.nullsFirst(Comparator.naturalOrder())); private String ns; private String location; private String packageName; private String nsabr; public XmlNamespace(String nsabr, String ns, String location, String packageName) { super(); this.nsabr = nsabr; this.ns = ns; this.location = location; this.packageName = packageName; } public String getNsabr() { return nsabr; } public String getNs() { return ns; } public String getLocation() { return location; } public boolean hasLocation() { return StringUtils.isNotBlank(location); } public String getPackageName() { return packageName; } public boolean hasPackageName() { return StringUtils.isNotBlank(packageName); } }
ShapeChange/ShapeChange
src/main/java/de/interactive_instruments/ShapeChange/XmlNamespace.java
214,404
/** * ShapeChange - processing application schemas for geographic information * * This file is part of ShapeChange. ShapeChange takes a ISO 19109 * Application Schema from a UML model and translates it into a * GML Application Schema or other implementation representations. * * Additional information about the software can be found at * http://shapechange.net/ * * (c) 2002-2015 interactive instruments GmbH, Bonn, Germany * * 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/>. * * Contact: * interactive instruments GmbH * Trierer Strasse 70-72 * 53115 Bonn * Germany */ package de.interactive_instruments.ShapeChange.FOL; import java.util.List; /** * @author Johannes Echterhoff * @param <T> tbd */ public class Function<T> extends Expression { private String name; private List<Expression> args; public Function() { } public T evaluate() { return null; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(name); sb.append("("); if(args != null && !args.isEmpty()) { sb.append(args.get(0).toString()); for(int i=1; i<args.size(); i++) { sb.append(","); sb.append(args.get(i).toString()); } } sb.append(")"); return sb.toString(); } }
ShapeChange/ShapeChange
src/main/java/de/interactive_instruments/ShapeChange/FOL/Function.java
214,405
/** * ShapeChange - processing application schemas for geographic information * * This file is part of ShapeChange. ShapeChange takes a ISO 19109 * Application Schema from a UML model and translates it into a * GML Application Schema or other implementation representations. * * Additional information about the software can be found at * http://shapechange.net/ * * (c) 2002-2013 interactive instruments GmbH, Bonn, Germany * * 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/>. * * Contact: * interactive instruments GmbH * Trierer Strasse 70-72 * 53115 Bonn * Germany */ package de.interactive_instruments.ShapeChange; import java.util.List; import org.apache.commons.lang3.StringUtils; /** * @author Johannes Echterhoff (echterhoff at interactive-instruments * dot de) */ public class XsdMapEntry { private String type; private List<String> encodingRules; private String xmlType; private String xmlTypeContent; private String xmlTypeType; private String xmlTypeNilReason; private String xmlElement; private String xmlPropertyType; private String xmlAttribute; private String xmlAttributeGroup; private Boolean xmlReferenceable = null; private Boolean xmlElementHasSimpleContent = null; private String nsabr; public XsdMapEntry(String type, List<String> encodingRules, String xmlType, String xmlTypeContent, String xmlTypeType, String xmlTypeNilReason, String xmlElement, String xmlPropertyType, String xmlAttribute, String xmlAttributeGroup, String xmlReferenceable, String xmlElementHasSimpleContent, String nsabr) { super(); this.type = type; this.encodingRules = encodingRules; this.xmlType = xmlType; this.xmlTypeContent = xmlTypeContent; this.xmlTypeType = xmlTypeType; this.xmlTypeNilReason = xmlTypeNilReason; this.xmlElement = xmlElement; this.xmlPropertyType = xmlPropertyType; this.xmlAttribute = xmlAttribute; this.xmlAttributeGroup = xmlAttributeGroup; if (xmlReferenceable != null) { this.xmlReferenceable = parseBoolean(xmlReferenceable); } if (xmlElementHasSimpleContent != null) { this.xmlElementHasSimpleContent = parseBoolean( xmlElementHasSimpleContent); } this.nsabr = nsabr; } private boolean parseBoolean(String s) { if (s.equals("0") || s.equalsIgnoreCase("false")) { return false; } else { return true; } } public String getType() { return type; } public List<String> getEncodingRules() { return encodingRules; } public String getXmlType() { return xmlType; } public String getXmlTypeContent() { return xmlTypeContent; } public String getXmlTypeType() { return xmlTypeType; } public String getXmlTypeNilReason() { return xmlTypeNilReason; } public String getXmlElement() { return xmlElement; } public boolean hasXmlElement() { return StringUtils.isNotBlank(xmlElement); } public String getXmlPropertyType() { return xmlPropertyType; } public String getXmlAttribute() { return xmlAttribute; } public String getXmlAttributeGroup() { return xmlAttributeGroup; } /** * @return the value of XsdMapEntry/@xmlReferenceable; can be * <code>null</code> if that attribute was not set in the map entry */ public Boolean getXmlReferenceable() { return xmlReferenceable; } /** * @return the value of XsdMapEntry/@xmlElementHasSimpleContent; can be * <code>null</code> if that attribute was not set in the map entry */ public Boolean getXmlElementHasSimpleContent() { return xmlElementHasSimpleContent; } public String getNsabr() { return nsabr; } }
ShapeChange/ShapeChange
src/main/java/de/interactive_instruments/ShapeChange/XsdMapEntry.java
214,407
package org.drip.graph.astar; /* * -*- mode: java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /*! * Copyright (C) 2022 Lakshmi Krishnamurthy * Copyright (C) 2021 Lakshmi Krishnamurthy * Copyright (C) 2020 Lakshmi Krishnamurthy * * This file is part of DROP, an open-source library targeting analytics/risk, transaction cost analytics, * asset liability management analytics, capital, exposure, and margin analytics, valuation adjustment * analytics, and portfolio construction analytics within and across fixed income, credit, commodity, * equity, FX, and structured products. It also includes auxiliary libraries for algorithm support, * numerical analysis, numerical optimization, spline builder, model validation, statistical learning, * graph builder/navigator, and computational support. * * https://lakshmidrip.github.io/DROP/ * * DROP is composed of three modules: * * - DROP Product Core - https://lakshmidrip.github.io/DROP-Product-Core/ * - DROP Portfolio Core - https://lakshmidrip.github.io/DROP-Portfolio-Core/ * - DROP Computational Core - https://lakshmidrip.github.io/DROP-Computational-Core/ * * DROP Product Core implements libraries for the following: * - Fixed Income Analytics * - Loan Analytics * - Transaction Cost Analytics * * DROP Portfolio Core implements libraries for the following: * - Asset Allocation Analytics * - Asset Liability Management Analytics * - Capital Estimation Analytics * - Exposure Analytics * - Margin Analytics * - XVA Analytics * * DROP Computational Core implements libraries for the following: * - Algorithm Support * - Computation Support * - Function Analysis * - Graph Algorithm * - Model Validation * - Numerical Analysis * - Numerical Optimizer * - Spline Builder * - Statistical Learning * * Documentation for DROP is Spread Over: * * - Main => https://lakshmidrip.github.io/DROP/ * - Wiki => https://github.com/lakshmiDRIP/DROP/wiki * - GitHub => https://github.com/lakshmiDRIP/DROP * - Repo Layout Taxonomy => https://github.com/lakshmiDRIP/DROP/blob/master/Taxonomy.md * - Javadoc => https://lakshmidrip.github.io/DROP/Javadoc/index.html * - Technical Specifications => https://github.com/lakshmiDRIP/DROP/tree/master/Docs/Internal * - Release Versions => https://lakshmidrip.github.io/DROP/version.html * - Community Credits => https://lakshmidrip.github.io/DROP/credits.html * - Issues Catalog => https://github.com/lakshmiDRIP/DROP/issues * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * limitations under the License. */ /** * <i>StaticWeightFHeuristic</i> implements the Statically Weighted A<sup>*</sup> F-Heuristic Value at a * Vertex. The References are: * * <br><br> * <ul> * <li> * Dechter, R., and J. Pearl (1985): Generalized Best-first Search Strategies and the Optimality of * A<sup>*</sup> <i>Journal of the ACM</i> <b>32 (3)</b> 505-536 * </li> * <li> * Hart, P. E., N. J. Nilsson, and B. Raphael (1968): A Formal Basis for the Heuristic Determination * of the Minimum Cost Paths <i>IEEE Transactions on Systems Sciences and Cybernetics</i> <b>4 * (2)</b> 100-107 * </li> * <li> * Kagan, E., and I. Ben-Gal (2014): A Group Testing Algorithm with Online Informational Learning * <i>IIE Transactions</i> <b>46 (2)</b> 164-184 * </li> * <li> * Russell, S. J. and P. Norvig (2018): <i>Artificial Intelligence: A Modern Approach 4<sup>th</sup> * Edition</i> <b>Pearson</b> * </li> * <li> * Wikipedia (2020): A<sup>*</sup> Search Algorithm * https://en.wikipedia.org/wiki/A*_search_algorithm * </li> * </ul> * * <br><br> * <ul> * <li><b>Module </b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/ComputationalCore.md">Computational Core Module</a></li> * <li><b>Library</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/GraphAlgorithmLibrary.md">Graph Algorithm Library</a></li> * <li><b>Project</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/graph/README.md">Graph Optimization and Tree Construction Algorithms</a></li> * <li><b>Package</b> = <a href = "https://github.com/lakshmiDRIP/DROP/tree/master/src/main/java/org/drip/graph/astar/README.md">A<sup>*</sup> Heuristic Shortest Path Family</a></li> * </ul> * <br><br> * * @author Lakshmi Krishnamurthy */ public class StaticWeightFHeuristic extends org.drip.graph.astar.FHeuristic { private double _epsilon = java.lang.Double.NaN; /** * StaticWeightFHeuristic Constructor * * @param gHeuristic The G Heuristic * @param hHeuristic The H Heuristic * @param epsilon Epsilon * * @throws java.lang.Exception Thrown if the Inputs are Invalid */ public StaticWeightFHeuristic ( final org.drip.graph.astar.VertexFunction gHeuristic, final org.drip.graph.astar.VertexFunction hHeuristic, final double epsilon) throws java.lang.Exception { super ( gHeuristic, hHeuristic ); if (!org.drip.numerical.common.NumberUtil.IsValid ( _epsilon = epsilon ) || 1. >= _epsilon ) { throw new java.lang.Exception ( "StaticWeightFHeuristic Constructor => Invalid Inputs" ); } } /** * Retrieve the "Epsilon" Weight * * @return The "Epsilon" Weight */ public double epsilon() { return _epsilon; } @Override public double evaluate ( final org.drip.graph.core.Vertex vertex) throws java.lang.Exception { return gHeuristic().evaluate ( vertex ) + _epsilon * hHeuristic().evaluate ( vertex ); } }
lakshmiDRIP/DROP
src/main/java/org/drip/graph/astar/StaticWeightFHeuristic.java
214,409
/** * ShapeChange - processing application schemas for geographic information * * This file is part of ShapeChange. ShapeChange takes a ISO 19109 * Application Schema from a UML model and translates it into a * GML Application Schema or other implementation representations. * * Additional information about the software can be found at * http://shapechange.net/ * * (c) 2002-2015 interactive instruments GmbH, Bonn, Germany * * 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/>. * * Contact: * interactive instruments GmbH * Trierer Strasse 70-72 * 53115 Bonn * Germany */ package de.interactive_instruments.ShapeChange.FOL; /** * @author Johannes Echterhoff */ public enum AndOrType { and, or }
ShapeChange/ShapeChange
src/main/java/de/interactive_instruments/ShapeChange/FOL/AndOrType.java
214,410
/** * ShapeChange - processing application schemas for geographic information * * This file is part of ShapeChange. ShapeChange takes a ISO 19109 * Application Schema from a UML model and translates it into a * GML Application Schema or other implementation representations. * * Additional information about the software can be found at * http://shapechange.net/ * * (c) 2002-2015 interactive instruments GmbH, Bonn, Germany * * 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/>. * * Contact: * interactive instruments GmbH * Trierer Strasse 70-72 * 53115 Bonn * Germany */ package de.interactive_instruments.ShapeChange.FOL; /** * @author Johannes Echterhoff */ public abstract class Predicate extends FolExpression { }
ShapeChange/ShapeChange
src/main/java/de/interactive_instruments/ShapeChange/FOL/Predicate.java
214,411
/** * ShapeChange - processing application schemas for geographic information * * This file is part of ShapeChange. ShapeChange takes a ISO 19109 * Application Schema from a UML model and translates it into a * GML Application Schema or other implementation representations. * * Additional information about the software can be found at * http://shapechange.net/ * * (c) 2002-2015 interactive instruments GmbH, Bonn, Germany * * 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/>. * * Contact: * interactive instruments GmbH * Trierer Strasse 70-72 * 53115 Bonn * Germany */ package de.interactive_instruments.ShapeChange.FOL; import de.interactive_instruments.ShapeChange.Model.ClassInfo; /** * @author Johannes Echterhoff */ public class ClassCall extends SchemaCall { private ClassInfo schemaElement; public ClassCall() { super(); } /** * @return the schemaElement */ public ClassInfo getSchemaElement() { return schemaElement; } /** * @param schemaElement * the schemaElement to set */ public void setSchemaElement(ClassInfo schemaElement) { this.schemaElement = schemaElement; } }
ShapeChange/ShapeChange
src/main/java/de/interactive_instruments/ShapeChange/FOL/ClassCall.java
214,412
/** * ShapeChange - processing application schemas for geographic information * * This file is part of ShapeChange. ShapeChange takes a ISO 19109 * Application Schema from a UML model and translates it into a * GML Application Schema or other implementation representations. * * Additional information about the software can be found at * http://shapechange.net/ * * (c) 2002-2015 interactive instruments GmbH, Bonn, Germany * * 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/>. * * Contact: * interactive instruments GmbH * Trierer Strasse 70-72 * 53115 Bonn * Germany */ package de.interactive_instruments.ShapeChange.FOL; /** * @author Johannes Echterhoff * */ public class LowerThan extends BinaryComparisonPredicate { @Override public String toString() { return exprLeft.toString() + " < "+exprRight.toString(); } }
ShapeChange/ShapeChange
src/main/java/de/interactive_instruments/ShapeChange/FOL/LowerThan.java
214,414
/******************************************************************************* * Copyright (C) 2009-2012 Dominik Jain. * * This file is part of ProbCog. * * ProbCog 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. * * ProbCog 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 ProbCog. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package probcog.bayesnets.inference; import java.math.BigInteger; import java.util.HashMap; import java.util.Vector; import probcog.bayesnets.core.BeliefNetworkEx; import probcog.exception.ProbCogException; import edu.ksu.cis.bnj.ver3.core.BeliefNode; import edu.ksu.cis.bnj.ver3.core.CPF; import edu.tum.cs.util.Stopwatch; import edu.tum.cs.util.datastruct.Map2D; /** * Simple implementation of the SampleSearch algorithm by Gogate & Dechter. * <p>The implementation will apply an unbiased estimator (which uses more memory) * only if enabled via {@link #setUseProperWeighting}.</p> * * @author Dominik Jain */ public class SampleSearch extends Sampler { protected int[] nodeOrder; protected int currentStep; protected double[] samplingProb; protected boolean useProperWeighting = false; protected boolean usingTopologicalOrdering = true; protected ImportanceFunction importanceFunction = ImportanceFunction.Prior; protected SampledDistribution importanceDist = null; protected int importanceFunctionSteps = 2; protected enum ImportanceFunction { Prior, BP, IJGP; } public SampleSearch(BeliefNetworkEx bn) throws ProbCogException { super(bn); this.paramHandler.add("importanceFunction", "setImportanceFunction"); this.paramHandler.add("ifSteps", "setImportanceFunctionSteps"); this.paramHandler.add("bpSteps", "setImportanceFunctionSteps"); this.paramHandler.add("ijgpSteps", "setImportanceFunctionSteps"); this.paramHandler.add("unbiased", "setUseProperWeighting"); } @Override protected void _initialize() throws ProbCogException { // TODO could help to guarantee for BLNs that formula nodes appear as early as possible nodeOrder = computeNodeOrdering(); samplingProb = new double[nodes.length]; if(importanceFunction != ImportanceFunction.Prior) { if(verbose) System.out.println("computing importance function with " + importanceFunction + "..."); Sampler s = importanceFunction == ImportanceFunction.BP ? new BeliefPropagation(this.bn) : new IJGP(bn); s.setNumSamples(importanceFunctionSteps); s.setEvidence(this.evidenceDomainIndices); importanceDist = s.infer(); if(debug) { System.out.println("importance distribution:"); importanceDist.print(System.out); } } } public void setImportanceFunction(String name) { importanceFunction = ImportanceFunction.valueOf(name); } public void setImportanceFunctionSteps(int steps) { this.importanceFunctionSteps = steps; } protected int[] computeNodeOrdering() throws ProbCogException { return bn.getTopologicalOrder(); } public void setUseProperWeighting(boolean enabled){ useProperWeighting = enabled; } protected void info(int step) { out.println(" step " + step); } @Override public void _infer() throws ProbCogException { // sample Stopwatch sw = new Stopwatch(); out.println("sampling..."); sw.start(); WeightedSample s = new WeightedSample(bn); for(int i = 1; i <= numSamples; i++) { currentStep = i; if(i % infoInterval == 0) info(i); WeightedSample ret = getWeightedSample(s, nodeOrder, evidenceDomainIndices); if(ret != null) { addSample(ret); /* // debugging of weighting out.print("w=" + ret.weight); double prod = 1.0; for(int j = 0; j < evidenceDomainIndices.length; j++) if(true || evidenceDomainIndices[j] == -1) { BeliefNode node = nodes[j]; out.print(" " + node.getName() + "=" + node.getDomain().getName(s.nodeDomainIndices[j])); double p = bn.getCPTProbability(node, s.nodeDomainIndices); out.printf(" %f", p); if(p == 0.0) throw new ProbCogException("Sample has 0 probability."); prod *= p; if(prod == 0.0) throw new ProbCogException("Precision loss - product became 0"); } out.println(); */ } if(converged()) break; } SampledDistribution dist = distributionBuilder.getDistribution(); report(String.format("time taken: %.2fs (%.4fs per sample, %.1f trials/sample, %.4f*N assignments/sample, %d samples)\n", sw.getElapsedTimeSecs(), sw.getElapsedTimeSecs()/numSamples, dist.getTrialsPerStep(), (float)dist.operations/nodes.length/numSamples, dist.steps)); } public WeightedSample getWeightedSample(WeightedSample s, int[] nodeOrder, int[] evidenceDomainIndices) throws ProbCogException { s.trials = 1; s.operations = 0; s.weight = 1.0; // assign values to the nodes in order HashMap<Integer, boolean[]> domExclusions = new HashMap<Integer, boolean[]>(); for(int i=0; i < nodeOrder.length;) { s.operations++; int nodeIdx = nodeOrder[i]; int domainIdx = evidenceDomainIndices[nodeIdx]; // get domain exclusions boolean[] excluded = domExclusions.get(nodeIdx); if(excluded == null) { excluded = new boolean[nodes[nodeIdx].getDomain().getOrder()]; domExclusions.put(nodeIdx, excluded); } // debug info if(debug) { int numex = 0; for(int j=0; j<excluded.length; j++) if(excluded[j]) numex++; out.printf(" step %d, node %d '%s' (%d/%d exclusions)\n", currentStep, i, nodes[nodeIdx].getName(), numex, excluded.length); } // for evidence nodes, we can continue if the evidence probability was non-zero if(domainIdx >= 0) { s.nodeDomainIndices[nodeIdx] = domainIdx; samplingProb[nodeIdx] = 1.0; double prob = getCPTProbability(nodes[nodeIdx], s.nodeDomainIndices); if(prob != 0.0) { ++i; continue; } else { if(debug) out.println(" evidence with probability 0.0; backtracking..."); } } // for non-evidence nodes, do forward sampling else { SampledAssignment sa = sampleForward(nodes[nodeIdx], s.nodeDomainIndices, excluded); if(sa != null) { domainIdx = sa.domIdx; samplingProb[nodeIdx] = sa.probability; s.nodeDomainIndices[nodeIdx] = domainIdx; ++i; continue; } else if(debug) out.println(" impossible case; backtracking..."); } // if we get here, we need to backtrack to the last non-evidence node s.trials++; do { // kill the current node's exclusions domExclusions.remove(nodeIdx); // add the previous node's setting as an exclusion --i; if(i < 0) throw new ProbCogException("Could not find a sample with non-zero probability. Most likely, the evidence specified has 0 probability."); nodeIdx = nodeOrder[i]; boolean[] prevExcl = domExclusions.get(nodeIdx); prevExcl[s.nodeDomainIndices[nodeIdx]] = true; // proceed with previous node... } while(evidenceDomainIndices[nodeIdx] != -1); } return s; } public class SampledAssignment { public int domIdx; public double probability; public SampledAssignment(int domainIdx, double p) { domIdx = domainIdx; probability = p; } } /** * samples forward, i.e. samples a value for 'node' given its parents * @param node the node for which to sample a value * @param nodeDomainIndices array of domain indices for all nodes in the network; the values for the parents of 'node' must be set already * @return the index of the domain element of 'node' that is sampled, or -1 if sampling is impossible because all entries in the relevant column are 0 */ protected SampledAssignment sampleForwardPrior(BeliefNode node, int[] nodeDomainIndices, boolean[] excluded) { CPF cpf = node.getCPF(); BeliefNode[] domProd = cpf.getDomainProduct(); int[] addr = new int[domProd.length]; // get the addresses of the first two relevant fields and the difference between them for(int i = 1; i < addr.length; i++) addr[i] = nodeDomainIndices[this.nodeIndices.get(domProd[i])]; addr[0] = 0; // (the first element in the index into the domain of the node we are sampling) int realAddr = cpf.addr2realaddr(addr); addr[0] = 1; int diff = cpf.addr2realaddr(addr) - realAddr; // diff is the address difference between two consecutive entries in the relevant column // get probabilities for outcomes double[] cpt_entries = new double[domProd[0].getDomain().getOrder()]; double sum = 0; for(int i = 0; i < cpt_entries.length; i++) { double value; if(excluded[i]) value = 0.0; else value = cpf.getDouble(realAddr); cpt_entries[i] = value; sum += value; realAddr += diff; } // if the column contains only zeros, it is an impossible case -> cannot sample if(sum == 0) return null; int domIdx = sample(cpt_entries, sum, generator); return new SampledAssignment(domIdx, cpt_entries[domIdx]/sum); } protected SampledAssignment sampleForward(BeliefNode node, int[] nodeDomainIndices, boolean[] excluded) { if(this.importanceDist == null) return sampleForwardPrior(node, nodeDomainIndices, excluded); CPF cpf = node.getCPF(); BeliefNode[] domProd = cpf.getDomainProduct(); int[] addr = new int[domProd.length]; // get the addresses of the first two relevant fields and the difference between them for(int i = 1; i < addr.length; i++) addr[i] = nodeDomainIndices[this.nodeIndices.get(domProd[i])]; addr[0] = 0; // (the first element in the index into the domain of the node we are sampling) int realAddr = cpf.addr2realaddr(addr); addr[0] = 1; int diff = cpf.addr2realaddr(addr) - realAddr; // diff is the address difference between two consecutive entries in the relevant column // get probabilities for outcomes // If we are sampling in top. order, we always additionally filter // values that are zero given the parents double[] samplingDist = importanceDist.getDistribution(getNodeIndex(node)); double sum = 0; for(int i = 0; i < samplingDist.length; i++) { Double cptValue = null; if(usingTopologicalOrdering) cptValue = cpf.getDouble(realAddr); if(excluded[i] || (cptValue != null && cptValue.equals(0.0))) samplingDist[i] = 0.0; sum += samplingDist[i]; realAddr += diff; } // if the column contains only zeros, it is an impossible case -> cannot sample if(sum == 0) return null; int domIdx = sample(samplingDist, sum, generator); return new SampledAssignment(domIdx, samplingDist[domIdx]/sum); } @Override public String getAlgorithmName() { return super.getAlgorithmName() + "[" + importanceFunction + "]"; } @Override protected IDistributionBuilder createDistributionBuilder() throws ProbCogException { if(useProperWeighting) return new UnbiasedEstimator(); else return new BiasedEstimator(); } /** * simple but biased estimator */ protected class BiasedEstimator extends DirectDistributionBuilder { public BiasedEstimator() throws ProbCogException { super(createDistribution()); } @Override public void addSample(WeightedSample s) { // do weighting s.weight = 1.0; for(int i = 0; i < nodes.length; i++) { s.weight *= getCPTProbability(nodes[i], s.nodeDomainIndices) / samplingProb[i]; } // directly add to distribution super.addSample(s); } } /** * unbiased "max"-estimator (additional storage space and computation time required) */ protected class UnbiasedEstimator implements IDistributionBuilder { protected Map2D<Integer,BigInteger,Double> maxQ; protected Vector<WeightedSample> samples; protected SampledDistribution dist; protected boolean dirty = false; public UnbiasedEstimator() throws ProbCogException { maxQ = new Map2D<Integer,BigInteger,Double>(); samples = new Vector<WeightedSample>(); } @Override public synchronized void addSample(WeightedSample s) throws ProbCogException { BigInteger partAssign = BigInteger.valueOf(0); Vector<Integer> partAssign2 = new Vector<Integer>(); for(int i = 0; i < nodeOrder.length; i++) { int nodeIdx = nodeOrder[i]; if(evidenceDomainIndices[nodeIdx] < 0) { partAssign = partAssign.multiply(BigInteger.valueOf(nodes[nodeIdx].getDomain().getOrder())); partAssign = partAssign.add(BigInteger.valueOf(s.nodeDomainIndices[nodeIdx])); partAssign2.add(s.nodeDomainIndices[nodeIdx]); Double p = maxQ.get(i, partAssign); if(p == null || samplingProb[nodeIdx] > p) { this.maxQ.put(i, partAssign, samplingProb[nodeIdx]); } } } try { samples.add(s.clone()); } catch (CloneNotSupportedException e) { throw new ProbCogException(e); } dirty = true; } @Override public synchronized SampledDistribution getDistribution() throws ProbCogException { if(!dirty) return dist; System.out.println("unbiased sample weighting..."); dist = createDistribution(); for(WeightedSample s : samples) { s.weight = 1.0; BigInteger partAssign = BigInteger.valueOf(0); for(int i = 0; i < nodeOrder.length; i++) { int nodeIdx = nodeOrder[i]; if(evidenceDomainIndices[nodeIdx] < 0) { partAssign = partAssign.multiply(BigInteger.valueOf(nodes[nodeIdx].getDomain().getOrder())); partAssign = partAssign.add(BigInteger.valueOf(s.nodeDomainIndices[nodeIdx])); s.weight *= getCPTProbability(nodes[nodeIdx], s.nodeDomainIndices) / maxQ.get(i, partAssign); } else s.weight *= getCPTProbability(nodes[nodeIdx], s.nodeDomainIndices); } dist.addSample(s); } dirty = false; return dist; } } }
opcode81/ProbCog
src/main/java/probcog/bayesnets/inference/SampleSearch.java
214,415
/** * ShapeChange - processing application schemas for geographic information * * This file is part of ShapeChange. ShapeChange takes a ISO 19109 * Application Schema from a UML model and translates it into a * GML Application Schema or other implementation representations. * * Additional information about the software can be found at * http://shapechange.net/ * * (c) 2002-2015 interactive instruments GmbH, Bonn, Germany * * 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/>. * * Contact: * interactive instruments GmbH * Trierer Strasse 70-72 * 53115 Bonn * Germany */ package de.interactive_instruments.ShapeChange.FOL; /** * @author Johannes Echterhoff * */ public class HigherThan extends BinaryComparisonPredicate{ @Override public String toString() { return exprLeft.toString() + " > "+exprRight.toString(); } }
ShapeChange/ShapeChange
src/main/java/de/interactive_instruments/ShapeChange/FOL/HigherThan.java