repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
breandan/java-algebra-system
trc/edu/jas/application/WordIdealTest.java
9507
/* * $Id$ */ package edu.jas.application; import java.util.ArrayList; import java.util.List; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import org.apache.log4j.BasicConfigurator; import edu.jas.arith.BigRational; import edu.jas.gb.WordGroebnerBase; import edu.jas.gb.WordGroebnerBaseSeq; // import edu.jas.kern.ComputerThreads; import edu.jas.poly.GenWordPolynomial; import edu.jas.poly.GenWordPolynomialRing; import edu.jas.poly.PolynomialList; import edu.jas.poly.TermOrder; /** * WordIdeal tests with JUnit. * @author Heinz Kredel. */ public class WordIdealTest extends TestCase { //private static final Logger logger = Logger.getLogger(WordIdealTest.class); /** * main */ public static void main(String[] args) { BasicConfigurator.configure(); junit.textui.TestRunner.run(suite()); } /** * Constructs a <CODE>WordIdealTest</CODE> object. * @param name String. */ public WordIdealTest(String name) { super(name); } /** * suite. */ public static Test suite() { TestSuite suite = new TestSuite(WordIdealTest.class); return suite; } TermOrder to; GenWordPolynomialRing<BigRational> fac; List<GenWordPolynomial<BigRational>> L, M; PolynomialList<BigRational> F; List<GenWordPolynomial<BigRational>> G; WordGroebnerBase<BigRational> bb; GenWordPolynomial<BigRational> a, b, c, d, e; int kl = 3; //10 int ll = 5; //7 int el = 2; @Override protected void setUp() { BigRational coeff = new BigRational(17, 1); to = new TermOrder( /*TermOrder.INVLEX*/); String[] vars = new String[] { "x", "y", "z" }; //WordFactory wf = new WordFactory(vars); fac = new GenWordPolynomialRing<BigRational>(coeff, vars); bb = new WordGroebnerBaseSeq<BigRational>(); //bb = GBFactory.getImplementation(coeff); a = b = c = d = e = null; } @Override protected void tearDown() { a = b = c = d = e = null; fac = null; bb = null; //ComputerThreads.terminate(); } /** * Test Ideal sum. */ public void testIdealSum() { WordIdeal<BigRational> I, J, K; L = new ArrayList<GenWordPolynomial<BigRational>>(); a = fac.random(kl, ll, el); b = fac.random(kl, ll, el); c = fac.random(kl, ll, el); d = fac.random(kl, ll, el); e = d; //fac.random(kl, ll, el); //System.out.println("a = " + a); //System.out.println("b = " + b); //System.out.println("c = " + c); //System.out.println("d = " + d); L.add(a); //System.out.println("L = " + L.size() ); I = new WordIdeal<BigRational>(fac, L, true); assertTrue("isGB( I )", I.isGB()); I = new WordIdeal<BigRational>(fac, L, false); assertTrue("isGB( I )", I.isGB()); L = bb.GB(L); assertTrue("isGB( { a } )", bb.isGB(L)); I = new WordIdeal<BigRational>(fac, L, true); assertTrue("isGB( I )", I.isGB()); I = new WordIdeal<BigRational>(fac, L, false); assertTrue("isGB( I )", I.isGB()); //if (!true) { // return; //} //assertTrue("not isZERO( b )", !b.isZERO()); L.add(b); //System.out.println("L = " + L.size() ); I = new WordIdeal<BigRational>(fac, L, false); assertTrue("not isZERO( I )", !I.isZERO()); //assertTrue("not isONE( I )", !I.isONE() ); //assertTrue("not isGB( I )", !I.isGB() ); L = bb.GB(L); assertTrue("isGB( { a, b } )", bb.isGB(L)); I = new WordIdeal<BigRational>(fac, L, true); assertTrue("not isZERO( I )", !I.isZERO()); // assertTrue("not isONE( I )", !I.isONE() ); assertTrue("isGB( I )", I.isGB()); J = I; K = J.sum(I); //assertTrue("not isZERO( K )", !K.isZERO()); assertTrue("isGB( K )", K.isGB()); assertTrue("equals( K, I )", K.equals(I)); L = new ArrayList<GenWordPolynomial<BigRational>>(); L.add(c); assertTrue("isGB( { c } )", bb.isGB(L)); J = new WordIdeal<BigRational>(fac, L, true); K = J.sum(I); assertTrue("isGB( K )", K.isGB()); assertTrue("K contains(I)", K.contains(I)); assertTrue("K contains(J)", K.contains(J)); L = new ArrayList<GenWordPolynomial<BigRational>>(); L.add(d); assertTrue("isGB( { d } )", bb.isGB(L)); J = new WordIdeal<BigRational>(fac, L, true); I = K; K = J.sum(I); assertTrue("isGB( K )", K.isGB()); assertTrue("K contains(I)", K.contains(I)); assertTrue("K contains(J)", K.contains(J)); L = new ArrayList<GenWordPolynomial<BigRational>>(); L.add(e); assertTrue("isGB( { e } )", bb.isGB(L)); J = new WordIdeal<BigRational>(fac, L, true); I = K; K = J.sum(I); assertTrue("isGB( K )", K.isGB()); assertTrue("equals( K, I )", K.equals(I)); assertTrue("K contains(J)", K.contains(I)); assertTrue("I contains(K)", I.contains(K)); } /** * Test WordIdeal product. Sometimes non-terminating. */ public void testWordIdealProduct() { WordIdeal<BigRational> I, J, K, H, G; a = fac.random(kl, ll, el); b = fac.random(kl, ll, el); c = fac.random(kl, ll, el); d = c; //fac.random(kl, ll, el); e = d; //fac.random(kl, ll, el); //System.out.println("a = " + a); //System.out.println("b = " + b); //System.out.println("c = " + c); //System.out.println("d = " + d); L = new ArrayList<GenWordPolynomial<BigRational>>(); L.add(a); I = new WordIdeal<BigRational>(fac, L, false); assertTrue("not isONE( I )", !I.isONE() || a.isConstant()); assertTrue("isGB( I )", I.isGB()); L = new ArrayList<GenWordPolynomial<BigRational>>(); L.add(b); J = new WordIdeal<BigRational>(fac, L, false); assertTrue("not isONE( J )", !J.isONE() || a.isConstant() || b.isConstant()); assertTrue("isGB( J )", J.isGB()); K = I.product(J); //System.out.println("I = " + I); //System.out.println("J = " + J); //System.out.println("K = " + K); H = J.product(I); //System.out.println("H = " + H); G = K.sum(H); //System.out.println("G = " + G); //assertTrue("not isZERO( K )", !K.isZERO()); assertTrue("isGB( K )", K.isGB()); assertTrue("isGB( H )", H.isGB()); assertTrue("isGB( G )", G.isGB()); //non-com assertTrue("I contains(K)", I.contains(K)); assertTrue("J contains(K)", J.contains(K)); //if (true) { // TODO // return; //} /* H = I.intersect(J); assertTrue("not isZERO( H )", !H.isZERO()); assertTrue("isGB( H )", H.isGB()); assertTrue("I contains(H)", I.contains(H)); assertTrue("J contains(H)", J.contains(H)); //non-com assertTrue("H contains(K)", H.contains(K)); */ /* L = new ArrayList<GenWordPolynomial<BigRational>>(); L.add(a); L.add(c); L = bb.GB(L); I = new WordIdeal<BigRational>(fac, L, true); //assertTrue("not isZERO( I )", !I.isZERO()); //assertTrue("not isONE( I )", !I.isONE() ); assertTrue("isGB( I )", I.isGB()); K = I.product(J); //System.out.println("I = " + I); //System.out.println("J = " + J); //System.out.println("K = " + K); //assertTrue("not isZERO( K )", !K.isZERO()); assertTrue("isGB( K )", K.isGB()); //non-com assertTrue("I contains(K)", I.contains(K)); assertTrue("J contains(K)", J.contains(K)); */ } /** * Test WordIdeal common zeros. */ @SuppressWarnings("cast") public void testWordIdealCommonZeros() { WordIdeal<BigRational> I, J; L = new ArrayList<GenWordPolynomial<BigRational>>(); I = new WordIdeal<BigRational>(fac, L, true); assertEquals("commonZeroTest( I )", I.commonZeroTest(), 1); a = fac.getZERO(); L.add(a); I = new WordIdeal<BigRational>(fac, L, true); assertEquals("commonZeroTest( I )", I.commonZeroTest(), 1); b = fac.getONE(); L.add(b); I = new WordIdeal<BigRational>(fac, L, true); assertEquals("commonZeroTest( I )", I.commonZeroTest(), -1); L = new ArrayList<GenWordPolynomial<BigRational>>(); a = fac.random(kl, ll, el); if (!a.isZERO() && !a.isConstant()) { L.add(a); I = new WordIdeal<BigRational>(fac, L, true); assertEquals("commonZeroTest( I )", I.commonZeroTest(), 1); } L = (List<GenWordPolynomial<BigRational>>) fac.univariateList(); //System.out.println("L = " + L); I = new WordIdeal<BigRational>(fac, L, true); assertEquals("commonZeroTest( I )", I.commonZeroTest(), 0); J = I.product(I); //System.out.println("J = " + J); assertEquals("commonZeroTest( J )", J.commonZeroTest(), 0); L.remove(0); I = new WordIdeal<BigRational>(fac, L, true); assertEquals("commonZeroTest( I )", I.commonZeroTest(), 1); } }
gpl-2.0
belyabl9/teammates
src/test/java/teammates/test/cases/ui/InstructorCourseEnrollSaveActionTest.java
16320
package teammates.test.cases.ui; import java.util.List; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import teammates.common.datatransfer.DataBundle; import teammates.common.datatransfer.InstructorAttributes; import teammates.common.datatransfer.StudentAttributes; import teammates.common.datatransfer.StudentAttributesFactory; import teammates.common.datatransfer.StudentUpdateStatus; import teammates.common.util.Const; import teammates.common.util.FieldValidator; import teammates.common.util.Sanitizer; import teammates.logic.core.CoursesLogic; import teammates.logic.core.StudentsLogic; import teammates.test.driver.AssertHelper; import teammates.ui.controller.InstructorCourseEnrollPageData; import teammates.ui.controller.InstructorCourseEnrollResultPageData; import teammates.ui.controller.InstructorCourseEnrollSaveAction; import teammates.ui.controller.ShowPageResult; import teammates.ui.template.EnrollResultPanel; public class InstructorCourseEnrollSaveActionTest extends BaseActionTest { private final DataBundle dataBundle = getTypicalDataBundle(); @BeforeClass public static void classSetUp() throws Exception { printTestClassHeader(); removeAndRestoreTypicalDataInDatastore(); uri = Const.ActionURIs.INSTRUCTOR_COURSE_ENROLL_SAVE; } @Test public void testExecuteAndPostProcess() throws Exception { String enrollString = ""; String[] submissionParams = new String[]{}; InstructorAttributes instructor1OfCourse1 = dataBundle.instructors.get("instructor1OfCourse1"); String instructorId = instructor1OfCourse1.googleId; String courseId = instructor1OfCourse1.courseId; gaeSimulation.loginAsInstructor(instructorId); ______TS("Typical case: add and edit students for non-empty course"); enrollString = "Section | Team | Name | Email | Comment" + Const.EOL // A new student + "Section 3 \t Team 1\tJean Wong\tjean@email.tmt\tExchange student" + Const.EOL // A new student with extra spaces in the team and name + "Section 3 \t Team 1\tstudent with extra spaces \t" + "studentWithExtraSpaces@gmail.tmt\t" + Const.EOL // A student to be modified + "Section 2 \t Team 1.3\tstudent1 In Course1</td></div>'\"\tstudent1InCourse1@gmail.tmt\t" + "New comment added" + Const.EOL // An existing student with no modification + "Section 1 \t Team 1.1</td></div>'\"\tstudent2 In Course1\tstudent2InCourse1@gmail.tmt\t" + Const.EOL // An existing student, now with extra spaces, should cause no modification + "Section 1 \t Team 1.1</td></div>'\"\tstudent3 In Course1 \tstudent3InCourse1@gmail.tmt\t"; submissionParams = new String[]{ Const.ParamsNames.COURSE_ID, courseId, Const.ParamsNames.STUDENTS_ENROLLMENT_INFO, enrollString }; InstructorCourseEnrollSaveAction enrollAction = getAction(submissionParams); ShowPageResult pageResult = getShowPageResult(enrollAction); assertEquals(Const.ViewURIs.INSTRUCTOR_COURSE_ENROLL_RESULT + "?error=false&user=idOfInstructor1OfCourse1", pageResult.getDestinationWithParams()); assertFalse(pageResult.isError); assertEquals("", pageResult.getStatusMessage()); verifySpecifiedTasksAdded(enrollAction, Const.TaskQueue.FEEDBACK_RESPONSE_ADJUSTMENT_QUEUE_NAME, 6); InstructorCourseEnrollResultPageData pageData = (InstructorCourseEnrollResultPageData) pageResult.data; assertEquals(courseId, pageData.getCourseId()); StudentAttributes newStudent = new StudentAttributes("jean", "jean@email.tmt", "Jean Wong", "Exchange student", courseId, "Team 1", "Section 3"); newStudent.updateStatus = StudentUpdateStatus.NEW; verifyStudentEnrollmentStatus(newStudent, pageData.getEnrollResultPanelList()); StudentAttributes newStudentWithExtraSpaces = new StudentAttributes("student", "studentWithExtraSpaces@gmail.tmt", "student with extra spaces", "", courseId, "Team 1", "Section 3"); newStudentWithExtraSpaces.updateStatus = StudentUpdateStatus.NEW; verifyStudentEnrollmentStatus(newStudentWithExtraSpaces, pageData.getEnrollResultPanelList()); StudentAttributes modifiedStudent = dataBundle.students.get("student1InCourse1"); modifiedStudent.comments = "New comment added"; modifiedStudent.section = "Section 2"; modifiedStudent.team = "Team 1.3"; modifiedStudent.updateStatus = StudentUpdateStatus.MODIFIED; verifyStudentEnrollmentStatus(modifiedStudent, pageData.getEnrollResultPanelList()); StudentAttributes unmodifiedStudent = dataBundle.students.get("student2InCourse1"); unmodifiedStudent.updateStatus = StudentUpdateStatus.UNMODIFIED; verifyStudentEnrollmentStatus(unmodifiedStudent, pageData.getEnrollResultPanelList()); StudentAttributes unmodifiedStudentWithExtraSpaces = dataBundle.students.get("student3InCourse1"); unmodifiedStudentWithExtraSpaces.updateStatus = StudentUpdateStatus.UNMODIFIED; verifyStudentEnrollmentStatus(unmodifiedStudentWithExtraSpaces, pageData.getEnrollResultPanelList()); String expectedLogSegment = "Students Enrolled in Course <span class=\"bold\">[" + courseId + "]" + ":</span><br>" + Sanitizer.sanitizeForHtml(enrollString).replace("\n", "<br>"); AssertHelper.assertContains(expectedLogSegment, enrollAction.getLogMessage()); ______TS("Masquerade mode, enrollment into empty course"); if (CoursesLogic.inst().isCoursePresent("new-course")) { CoursesLogic.inst().deleteCourseCascade("new-course"); } courseId = "new-course"; CoursesLogic.inst().createCourseAndInstructor(instructorId, courseId, "New course", "UTC"); gaeSimulation.loginAsAdmin("admin.user"); String headerRow = "Name\tEmail\tTeam\tComment"; String studentsInfo = "Jean Wong\tjean@email.tmt\tTeam 1\tExchange student" + Const.EOL + "James Tan\tjames@email.tmt\tTeam 2\t"; enrollString = headerRow + Const.EOL + studentsInfo; submissionParams = new String[]{ Const.ParamsNames.USER_ID, instructorId, Const.ParamsNames.COURSE_ID, courseId, Const.ParamsNames.STUDENTS_ENROLLMENT_INFO, enrollString }; enrollAction = getAction(submissionParams); pageResult = getShowPageResult(enrollAction); assertEquals(Const.ViewURIs.INSTRUCTOR_COURSE_ENROLL_RESULT + "?error=false&user=idOfInstructor1OfCourse1", pageResult.getDestinationWithParams()); assertFalse(pageResult.isError); assertEquals("", pageResult.getStatusMessage()); verifyNoTasksAdded(enrollAction); pageData = (InstructorCourseEnrollResultPageData) pageResult.data; assertEquals(courseId, pageData.getCourseId()); StudentAttributes student1 = new StudentAttributes("jean", "jean@email.tmt", "Jean Wong", "Exchange student", courseId, "Team 1", "None"); student1.updateStatus = StudentUpdateStatus.NEW; verifyStudentEnrollmentStatus(student1, pageData.getEnrollResultPanelList()); StudentAttributes student2 = new StudentAttributes("james", "james@email.tmt", "James Tan", "", courseId, "Team 2", "None"); student2.updateStatus = StudentUpdateStatus.NEW; verifyStudentEnrollmentStatus(student2, pageData.getEnrollResultPanelList()); expectedLogSegment = "Students Enrolled in Course <span class=\"bold\">[" + courseId + "]:</span>" + "<br>" + enrollString.replace("\n", "<br>"); AssertHelper.assertContains(expectedLogSegment, enrollAction.getLogMessage()); ______TS("Failure case: enrollment failed due to invalid lines"); gaeSimulation.loginAsInstructor(instructorId); String studentWithoutEnoughParam = "Team 1\tStudentWithNoEmailInput"; String studentWithInvalidEmail = "Team 2\tBenjamin Tan\tinvalid.email.tmt"; String invalidEmail = "invalid.email.tmt"; enrollString = "Team | Name | Email" + Const.EOL + studentWithoutEnoughParam + Const.EOL + studentWithInvalidEmail; submissionParams = new String[]{ Const.ParamsNames.COURSE_ID, courseId, Const.ParamsNames.STUDENTS_ENROLLMENT_INFO, enrollString }; enrollAction = getAction(submissionParams); pageResult = getShowPageResult(enrollAction); assertEquals(Const.ViewURIs.INSTRUCTOR_COURSE_ENROLL, pageResult.destination); assertTrue(pageResult.isError); String expectedStatusMessage = "<p>" + "<span class=\"bold\">Problem in line : " + "<span class=\"invalidLine\">" + Sanitizer.sanitizeForHtml(studentWithoutEnoughParam) + "</span>" + "</span>" + "<br>" + "<span class=\"problemDetail\">&bull; " + StudentAttributesFactory.ERROR_ENROLL_LINE_TOOFEWPARTS + "</span>" + "</p>" + "<br>" + "<p>" + "<span class=\"bold\">Problem in line : " + "<span class=\"invalidLine\">" + Sanitizer.sanitizeForHtml(studentWithInvalidEmail) + "</span>" + "</span>" + "<br>" + "<span class=\"problemDetail\">&bull; " + Sanitizer.sanitizeForHtml( getPopulatedErrorMessage( FieldValidator.EMAIL_ERROR_MESSAGE, invalidEmail, FieldValidator.EMAIL_FIELD_NAME, FieldValidator.REASON_INCORRECT_FORMAT, FieldValidator.EMAIL_MAX_LENGTH)) + "</span>" + "</p>"; assertEquals(expectedStatusMessage, pageResult.getStatusMessage()); verifyNoTasksAdded(enrollAction); InstructorCourseEnrollPageData enrollPageData = (InstructorCourseEnrollPageData) pageResult.data; assertEquals(courseId, enrollPageData.getCourseId()); assertEquals(enrollString, enrollPageData.getEnrollStudents()); expectedLogSegment = expectedStatusMessage + "<br>Enrollment string entered by user:<br>" + enrollString.replace("\n", "<br>"); AssertHelper.assertContains(expectedLogSegment, enrollAction.getLogMessage()); ______TS("Boundary test for size limit per enrollment"); //TODO: sync this var with SIZE_LIMIT_PER_ENROLLMENT defined in StudentsLogic, by putting it in config or Const class int sizeLimitBoundary = 150; //can enroll, if within the size limit StringBuilder enrollStringBuilder = new StringBuilder(200); enrollStringBuilder.append("Section\tTeam\tName\tEmail"); for (int i = 0; i < sizeLimitBoundary; i++) { enrollStringBuilder.append(Const.EOL).append("section" + i + "\tteam" + i + "\tname" + i + "\temail" + i + "@nonexistemail.nonexist"); } submissionParams = new String[]{ Const.ParamsNames.COURSE_ID, courseId, Const.ParamsNames.STUDENTS_ENROLLMENT_INFO, enrollStringBuilder.toString() }; enrollAction = getAction(submissionParams); pageResult = getShowPageResult(enrollAction); assertFalse(pageResult.isError); assertEquals("", pageResult.getStatusMessage()); verifyNoTasksAdded(enrollAction); //fail to enroll, if exceed the range enrollStringBuilder.append(Const.EOL).append("section" + sizeLimitBoundary + "\tteam" + sizeLimitBoundary + "\tname" + sizeLimitBoundary + "\temail" + sizeLimitBoundary + "@nonexistemail.nonexist"); submissionParams = new String[]{ Const.ParamsNames.COURSE_ID, courseId, Const.ParamsNames.STUDENTS_ENROLLMENT_INFO, enrollStringBuilder.toString() }; enrollAction = getAction(submissionParams); pageResult = getShowPageResult(enrollAction); assertEquals(Const.ViewURIs.INSTRUCTOR_COURSE_ENROLL, pageResult.destination); assertTrue(pageResult.isError); assertEquals(Const.StatusMessages.QUOTA_PER_ENROLLMENT_EXCEED, pageResult.getStatusMessage()); verifyNoTasksAdded(enrollAction); ______TS("Failure case: empty input"); enrollString = ""; submissionParams = new String[]{ Const.ParamsNames.COURSE_ID, courseId, Const.ParamsNames.STUDENTS_ENROLLMENT_INFO, enrollString }; enrollAction = getAction(submissionParams); pageResult = getShowPageResult(enrollAction); assertEquals(Const.ViewURIs.INSTRUCTOR_COURSE_ENROLL + "?error=true&user=idOfInstructor1OfCourse1", pageResult.getDestinationWithParams()); assertTrue(pageResult.isError); assertEquals(Const.StatusMessages.ENROLL_LINE_EMPTY, pageResult.getStatusMessage()); verifyNoTasksAdded(enrollAction); enrollPageData = (InstructorCourseEnrollPageData) pageResult.data; assertEquals(courseId, enrollPageData.getCourseId()); assertEquals(enrollString, enrollPageData.getEnrollStudents()); AssertHelper.assertContains(Const.StatusMessages.ENROLL_LINE_EMPTY, enrollAction.getLogMessage()); CoursesLogic.inst().deleteCourseCascade("new-course"); StudentsLogic.inst().deleteStudentsForCourseWithoutDocument(instructor1OfCourse1.courseId); } /** * Verify if <code>student exists in the <code>studentsAfterEnrollment */ private void verifyStudentEnrollmentStatus(StudentAttributes student, List<EnrollResultPanel> panelList) { boolean result = false; StudentUpdateStatus status = student.updateStatus; for (StudentAttributes s : panelList.get(status.numericRepresentation).getStudentList()) { if (s.isEnrollInfoSameAs(student)) { result = true; break; } } assertTrue(result); } private InstructorCourseEnrollSaveAction getAction(String... params) { return (InstructorCourseEnrollSaveAction) gaeSimulation.getActionObject(uri, params); } }
gpl-2.0
jinshiyi11/TestAndroid
app/src/main/java/com/shuai/test/okhttp/GitHubService.java
261
package com.shuai.test.okhttp; import java.util.List; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path; public interface GitHubService { @GET("users/{user}/repos") Call<List<Repo>> listRepos(@Path("user") String user); }
gpl-2.0
atasco88/spark-hls-analyzer
src/test/java/com/tasco/hls/file/LocalFileSystemTest.java
903
package com.tasco.hls.file; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.net.URI; import java.net.URISyntaxException; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import com.tasco.hls.file.filesystem.FileSystem; import com.tasco.hls.file.filesystem.LocalFileSystem; public class LocalFileSystemTest { @Before public void setUp() throws Exception {} @Test public void testCanReadFile() throws URISyntaxException, IOException { final URI uri = LocalFileSystemTest.class.getClassLoader().getResource("data.txt").toURI(); final FileSystem fs = new LocalFileSystem(); final File file = fs.getFile(uri); final BufferedReader br = new BufferedReader(new FileReader(file)); Assert.assertEquals("abc", br.readLine()); br.close(); } }
gpl-2.0
pantelis60/L2Scripts_Underground
gameserver/src/main/java/l2s/gameserver/model/base/MultiSellEntry.java
1612
package l2s.gameserver.model.base; import java.util.ArrayList; import java.util.List; public class MultiSellEntry { private int _entryId; private List<MultiSellIngredient> _ingredients = new ArrayList<MultiSellIngredient>(); private List<MultiSellIngredient> _production = new ArrayList<MultiSellIngredient>(); private long _tax; public MultiSellEntry() {} public MultiSellEntry(int id) { _entryId = id; } /** * @param entryId The entryId to set. */ public void setEntryId(int entryId) { _entryId = entryId; } /** * @return Returns the entryId. */ public int getEntryId() { return _entryId; } /** * @param ingredients The ingredients to set. */ public void addIngredient(MultiSellIngredient ingredient) { _ingredients.add(ingredient); } /** * @return Returns the ingredients. */ public List<MultiSellIngredient> getIngredients() { return _ingredients; } /** * @param ingredients The ingredients to set. */ public void addProduct(MultiSellIngredient ingredient) { _production.add(ingredient); } /** * @return Returns the ingredients. */ public List<MultiSellIngredient> getProduction() { return _production; } public long getTax() { return _tax; } public void setTax(long tax) { _tax = tax; } @Override public int hashCode() { return _entryId; } @Override public MultiSellEntry clone() { MultiSellEntry ret = new MultiSellEntry(_entryId); for(MultiSellIngredient i : _ingredients) ret.addIngredient(i.clone()); for(MultiSellIngredient i : _production) ret.addProduct(i.clone()); return ret; } }
gpl-3.0
langera/libresonic
libresonic-main/src/main/java/org/libresonic/player/controller/SettingsController.java
1759
/* This file is part of Libresonic. Libresonic 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. Libresonic 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 Libresonic. If not, see <http://www.gnu.org/licenses/>. Copyright 2016 (C) Libresonic Authors Based upon Subsonic, Copyright 2009 (C) Sindre Mehus */ package org.libresonic.player.controller; import org.libresonic.player.domain.*; import org.libresonic.player.service.*; import org.springframework.web.servlet.*; import org.springframework.web.servlet.view.*; import org.springframework.web.servlet.mvc.*; import javax.servlet.http.*; /** * Controller for the main settings page. * * @author Sindre Mehus */ public class SettingsController extends AbstractController { private SecurityService securityService; protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { User user = securityService.getCurrentUser(request); // Redirect to music folder settings if admin. String view = user.isAdminRole() ? "musicFolderSettings.view" : "personalSettings.view"; return new ModelAndView(new RedirectView(view)); } public void setSecurityService(SecurityService securityService) { this.securityService = securityService; } }
gpl-3.0
filipemb/siesp
app/br/com/core/conversor/NoticiaConversor.java
3302
/******************************************************************************* * This file is part of Educatio. * * Educatio 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. * * Educatio 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 Educatio. If not, see <http://www.gnu.org/licenses/>. * * Authors: * Filipe Marinho de Brito - filipe.marinho.brito@gmail.com * Rodrigo de Souza Ataides - rodrigoataides@gmail.com *******************************************************************************/ package br.com.core.conversor; import br.com.core.conversor.utils.ConversorUtils; import br.com.core.jdbc.dao.publico.NoticiaTable; import br.com.core.modelo.publico.Arquivo; import br.com.core.modelo.publico.Noticia; import br.com.core.modelo.publico.enumerator.TipoNoticia; import flexjson.JSONDeserializer; import flexjson.JSONSerializer; public class NoticiaConversor { public static NoticiaTable converterModeloParaTabela(Noticia modelo){ NoticiaTable noticiaTable = new NoticiaTable(); noticiaTable.setId(modelo.getId()); Arquivo arquivo = modelo.getArquivo(); if(arquivo!=null && arquivo.getId()!=null){ noticiaTable.setArquivo(arquivo.getId()); } TipoNoticia tipoNoticia = modelo.getTipoNoticia(); if(tipoNoticia!=null ){ noticiaTable.setTipoNoticia(tipoNoticia.name()); } noticiaTable.setTitulo(modelo.getTitulo()); noticiaTable.setNoticia(modelo.getNoticia()); noticiaTable.setVersion(modelo.getVersion()); noticiaTable.setDataPostagem(modelo.getDataPostagem()); noticiaTable.setAtivo(modelo.getAtivo()); return noticiaTable; } public static Noticia converterTabelaParaModelo(NoticiaTable tabela){ Noticia noticia = new Noticia(); Arquivo arquivo = new Arquivo(); arquivo.setId(tabela.getArquivo()); noticia.setArquivo(arquivo); noticia.setId(tabela.getId()); noticia.setVersion(tabela.getVersion()); if(tabela.getTipoNoticia() !=null && !tabela.getTipoNoticia().isEmpty() ){ TipoNoticia tipoNoticia = TipoNoticia.valueOf(tabela.getTipoNoticia()); noticia.setTipoNoticia(tipoNoticia); } noticia.setTitulo(tabela.getTitulo()); noticia.setNoticia(tabela.getNoticia()); noticia.setDataPostagem(tabela.getDataPostagem()); noticia.setAtivo(tabela.getAtivo()); return noticia; } public static String converterModeloParaJson(Noticia noticia){ JSONSerializer serializer = ConversorUtils.getJsonSerializer(); String json = serializer.serialize(noticia); return json; } @SuppressWarnings("rawtypes") public static Noticia converterJsonParaModelo(String json){ JSONDeserializer deserializer = ConversorUtils.getJsonDeserializer(); Object objeto = deserializer.use(null, Noticia.class).deserialize(json); Noticia noticia = (Noticia) objeto; return noticia; } }
gpl-3.0
InspectorIncognito/androidApp
app/src/main/java/cl/smartcities/isci/transportinspector/dialogs/SavingUserSettingsDialog.java
1557
package cl.smartcities.isci.transportinspector.dialogs; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.os.Bundle; import android.support.v7.app.AlertDialog; /** * Created by Agustin on 11/5/2017. */ public class SavingUserSettingsDialog extends DialogFragment { OnButtonClickListener listener; public void setListener(OnButtonClickListener listener) { this.listener = listener; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setMessage("No se han guardado sus preferencias, seguro quiere salir?") .setTitle("¡Cuidado!"); builder.setPositiveButton("Salir", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { if(listener != null) { listener.onPositiveButtonClick(); } // User clicked OK button } }); builder.setNegativeButton("Guardar primero", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { if(listener != null) { listener.onNegativeButtonClick(); } } }); return builder.create(); } public interface OnButtonClickListener { void onPositiveButtonClick(); void onNegativeButtonClick(); } }
gpl-3.0
kuiwang/my-dev
src/main/java/com/taobao/api/domain/SHotel.java
8749
package com.taobao.api.domain; import java.util.Date; import com.taobao.api.TaobaoObject; import com.taobao.api.internal.mapping.ApiField; /** * 酒店的标准酒店信息 * * @author auto create * @since 1.0, null */ public class SHotel extends TaobaoObject { private static final long serialVersionUID = 6134921747937915975L; /** * 酒店地址 */ @ApiField("address") private String address; /** * brand */ @ApiField("brand") private String brand; /** * business */ @ApiField("business") private String business; /** * 城市编码 */ @ApiField("city") private Long city; /** * 地区标签 */ @ApiField("city_tag") private String cityTag; /** * 国家编码 */ @ApiField("country") private String country; /** * 创建时间 */ @ApiField("created_time") private Date createdTime; /** * 装修年份 */ @ApiField("decorate_time") private String decorateTime; /** * 酒店介绍 */ @ApiField("desc") private String desc; /** * 区域编码 */ @ApiField("district") private Long district; /** * 0:国内;1:国外 */ @ApiField("domestic") private Long domestic; /** * 扩展信息的JSON */ @ApiField("extend") private String extend; /** * 传真 */ @ApiField("fax") private String fax; /** * 酒店设施 */ @ApiField("hotel_facilities") private String hotelFacilities; /** * latitude */ @ApiField("latitude") private String latitude; /** * 酒店级别 */ @ApiField("level") private String level; /** * longitude */ @ApiField("longitude") private String longitude; /** * 修改时间 */ @ApiField("modified_time") private Date modifiedTime; /** * name */ @ApiField("name") private String name; /** * 开业年份 */ @ApiField("opening_time") private String openingTime; /** * 酒店图片url */ @ApiField("pic_url") private String picUrl; /** * position_type */ @ApiField("position_type") private Long positionType; /** * 邮编 */ @ApiField("postal_code") private String postalCode; /** * 省份编码 */ @ApiField("province") private Long province; /** * 房间设施 */ @ApiField("room_facilities") private String roomFacilities; /** * 房间数 */ @ApiField("rooms") private Long rooms; /** * 交通距离与设施服务。JSON格式。 */ @ApiField("service") private String service; /** * 酒店ID */ @ApiField("shid") private Long shid; /** * 状态: 0:待系统匹配 1:已系统匹配,匹配成功,待卖家确认 2:已系统匹配,匹配失败,待人工匹配 3:已人工匹配,匹配成功,待卖家确认 * 4:已人工匹配,匹配失败 5:卖家已确认,确认“YES” 6:卖家已确认,确认“NO” 7:停售 */ @ApiField("status") private Long status; /** * 楼层数 */ @ApiField("storeys") private String storeys; /** * 酒店电话 */ @ApiField("tel") private String tel; /** * 酒店类型 */ @ApiField("type") private String type; /** * used_name */ @ApiField("used_name") private String usedName; public String getAddress() { return this.address; } public String getBrand() { return this.brand; } public String getBusiness() { return this.business; } public Long getCity() { return this.city; } public String getCityTag() { return this.cityTag; } public String getCountry() { return this.country; } public Date getCreatedTime() { return this.createdTime; } public String getDecorateTime() { return this.decorateTime; } public String getDesc() { return this.desc; } public Long getDistrict() { return this.district; } public Long getDomestic() { return this.domestic; } public String getExtend() { return this.extend; } public String getFax() { return this.fax; } public String getHotelFacilities() { return this.hotelFacilities; } public String getLatitude() { return this.latitude; } public String getLevel() { return this.level; } public String getLongitude() { return this.longitude; } public Date getModifiedTime() { return this.modifiedTime; } public String getName() { return this.name; } public String getOpeningTime() { return this.openingTime; } public String getPicUrl() { return this.picUrl; } public Long getPositionType() { return this.positionType; } public String getPostalCode() { return this.postalCode; } public Long getProvince() { return this.province; } public String getRoomFacilities() { return this.roomFacilities; } public Long getRooms() { return this.rooms; } public String getService() { return this.service; } public Long getShid() { return this.shid; } public Long getStatus() { return this.status; } public String getStoreys() { return this.storeys; } public String getTel() { return this.tel; } public String getType() { return this.type; } public String getUsedName() { return this.usedName; } public void setAddress(String address) { this.address = address; } public void setBrand(String brand) { this.brand = brand; } public void setBusiness(String business) { this.business = business; } public void setCity(Long city) { this.city = city; } public void setCityTag(String cityTag) { this.cityTag = cityTag; } public void setCountry(String country) { this.country = country; } public void setCreatedTime(Date createdTime) { this.createdTime = createdTime; } public void setDecorateTime(String decorateTime) { this.decorateTime = decorateTime; } public void setDesc(String desc) { this.desc = desc; } public void setDistrict(Long district) { this.district = district; } public void setDomestic(Long domestic) { this.domestic = domestic; } public void setExtend(String extend) { this.extend = extend; } public void setFax(String fax) { this.fax = fax; } public void setHotelFacilities(String hotelFacilities) { this.hotelFacilities = hotelFacilities; } public void setLatitude(String latitude) { this.latitude = latitude; } public void setLevel(String level) { this.level = level; } public void setLongitude(String longitude) { this.longitude = longitude; } public void setModifiedTime(Date modifiedTime) { this.modifiedTime = modifiedTime; } public void setName(String name) { this.name = name; } public void setOpeningTime(String openingTime) { this.openingTime = openingTime; } public void setPicUrl(String picUrl) { this.picUrl = picUrl; } public void setPositionType(Long positionType) { this.positionType = positionType; } public void setPostalCode(String postalCode) { this.postalCode = postalCode; } public void setProvince(Long province) { this.province = province; } public void setRoomFacilities(String roomFacilities) { this.roomFacilities = roomFacilities; } public void setRooms(Long rooms) { this.rooms = rooms; } public void setService(String service) { this.service = service; } public void setShid(Long shid) { this.shid = shid; } public void setStatus(Long status) { this.status = status; } public void setStoreys(String storeys) { this.storeys = storeys; } public void setTel(String tel) { this.tel = tel; } public void setType(String type) { this.type = type; } public void setUsedName(String usedName) { this.usedName = usedName; } }
gpl-3.0
MHTaleb/Encologim
lib/JasperReport/src/net/sf/jasperreports/components/barcode4j/DataMatrixComponent.java
1866
/* * JasperReports - Free Java Reporting Library. * Copyright (C) 2001 - 2016 TIBCO Software Inc. All rights reserved. * http://www.jaspersoft.com * * Unless you have purchased a commercial license agreement from Jaspersoft, * the following license terms apply: * * This program is part of JasperReports. * * JasperReports is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * JasperReports 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 JasperReports. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.jasperreports.components.barcode4j; import net.sf.jasperreports.engine.JRConstants; import org.krysalis.barcode4j.impl.datamatrix.SymbolShapeHint; /** * * @author Lucian Chirita (lucianc@users.sourceforge.net) */ public class DataMatrixComponent extends Barcode4jComponent { private static final long serialVersionUID = JRConstants.SERIAL_VERSION_UID; public static final String PROPERTY_SHAPE = "shape"; private String shape; @Override public void receive(BarcodeVisitor visitor) { visitor.visitDataMatrix(this); } public String getShape() { return shape; } public void setShape(String shape) { Object old = this.shape; this.shape = shape; getEventSupport().firePropertyChange(PROPERTY_SHAPE, old, this.shape); } public void setShape(SymbolShapeHint shape) { setShape(shape == null ? null : shape.getName()); } }
gpl-3.0
freecores/usb_fpga_1_2
examples/usb-fpga-1.15y/ucecho/UCEcho.java
5876
/*!2 ucecho -- uppercase conversion example for ZTEX USB-FPGA Module 1.15b Copyright (C) 2009-2011 ZTEX GmbH. http://www.ztex.de This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 3 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; if not, see http://www.gnu.org/licenses/. !*/ import java.io.*; import java.util.*; import ch.ntb.usb.*; import ztex.*; // ***************************************************************************** // ******* ParameterException ************************************************** // ***************************************************************************** // Exception the prints a help message class ParameterException extends Exception { public final static String helpMsg = new String ( "Parameters:\n"+ " -d <number> Device Number (default: 0)\n" + " -f Force uploads\n" + " -p Print bus info\n" + " -w Enable certain workarounds\n"+ " -h This help" ); public ParameterException (String msg) { super( msg + "\n" + helpMsg ); } } // ***************************************************************************** // ******* Test0 *************************************************************** // ***************************************************************************** class UCEcho extends Ztex1v1 { // ******* UCEcho ************************************************************** // constructor public UCEcho ( ZtexDevice1 pDev ) throws UsbException { super ( pDev ); } // ******* echo **************************************************************** // writes a string to Endpoint 4, reads it back from Endpoint 2 and writes the output to System.out public void echo ( int fpga, String input ) throws UsbException, InvalidFirmwareException, IndexOutOfBoundsException { byte buf[] = input.getBytes(); selectFpga(fpga); int i = LibusbJava.usb_bulk_write(handle(), 0x04, buf, buf.length, 1000); if ( i<0 ) throw new UsbException("Error sending data: " + LibusbJava.usb_strerror()); System.out.println("FPGA " + fpga + ": Send "+i+" bytes: `"+input+"'" ); try { Thread.sleep( 10 ); } catch ( InterruptedException e ) { } buf = new byte[1024]; i = LibusbJava.usb_bulk_read(handle(), 0x82, buf, 1024, 1000); if ( i<0 ) throw new UsbException("Error receiving data: " + LibusbJava.usb_strerror()); System.out.println("FPGA " + fpga + ": Read "+i+" bytes: `"+new String(buf,0,i)+"'" ); } // ******* main **************************************************************** public static void main (String args[]) { int devNum = 0; boolean force = false; boolean workarounds = false; try { // init USB stuff LibusbJava.usb_init(); // scan the USB bus ZtexScanBus1 bus = new ZtexScanBus1( ZtexDevice1.ztexVendorId, ZtexDevice1.ztexProductId, true, false, 1); if ( bus.numberOfDevices() <= 0) { System.err.println("No devices found"); System.exit(0); } // scan the command line arguments for (int i=0; i<args.length; i++ ) { if ( args[i].equals("-d") ) { i++; try { if (i>=args.length) throw new Exception(); devNum = Integer.parseInt( args[i] ); } catch (Exception e) { throw new ParameterException("Device number expected after -d"); } } else if ( args[i].equals("-f") ) { force = true; } else if ( args[i].equals("-p") ) { bus.printBus(System.out); System.exit(0); } else if ( args[i].equals("-p") ) { bus.printBus(System.out); System.exit(0); } else if ( args[i].equals("-w") ) { workarounds = true; } else if ( args[i].equals("-h") ) { System.err.println(ParameterException.helpMsg); System.exit(0); } else throw new ParameterException("Invalid Parameter: "+args[i]); } // create the main class UCEcho ztex = new UCEcho ( bus.device(devNum) ); ztex.certainWorkarounds = workarounds; // upload the firmware if necessary if ( force || ! ztex.valid() || ! ztex.dev().productString().equals("ucecho example for UFM 1.15y") ) { System.out.println("Firmware upload time: " + ztex.uploadFirmware( "ucecho.ihx", force ) + " ms"); force=true; } System.out.println("" + ztex.numberOfFpgas() + " FPGA's found"); // upload the bitstream if necessary for (int i=0; i<ztex.numberOfFpgas(); i++ ) { ztex.selectFpga(i); if ( force || ! ztex.getFpgaConfiguration() ) { System.out.print("FPGA "+i+": "); System.out.println("FPGA configuration time: " + ztex.configureFpga( "fpga/ucecho.bit" , force ) + " ms"); } } // claim interface 0 ztex.trySetConfiguration ( 1 ); ztex.claimInterface ( 0 ); // read string from stdin and write it to USB device String str = ""; BufferedReader reader = new BufferedReader( new InputStreamReader( System.in ) ); while ( ! str.equals("quit") ) { System.out.print("Enter a string or `quit' to exit the program: "); str = reader.readLine(); if ( ! str.equals("") ) { for ( int i=0; i<ztex.numberOfFpgas(); i++ ) ztex.echo(i, str); } System.out.println(""); } // release interface 0 ztex.releaseInterface( 0 ); } catch (Exception e) { System.out.println("Error: "+e.getLocalizedMessage() ); } } }
gpl-3.0
meanmail/java_base
section540/lesson12773/step53606/src/MainTest.java
4914
// Don't edit this file import org.junit.BeforeClass; import org.junit.Test; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import static org.junit.Assert.assertEquals; import static org.junit.Assert.fail; /** * @author meanmail */ public class MainTest { private static Method moveRobot; private static Class<?> mainClass; @BeforeClass public static void beforeClass() { mainClass = TestUtils.getUserClass("Main"); moveRobot = TestUtils.getMethod(mainClass, "moveRobot", new int[]{Modifier.PUBLIC | Modifier.STATIC}, Void.TYPE, RobotConnectionManager.class, Integer.TYPE, Integer.TYPE); } @Test(timeout = 8000) public void moveRobotNormal() throws Throwable { RobotConnectionManagerImpl robotConnectionManager = new RobotConnectionManagerImpl(); TestUtils.invokeMethod(mainClass, moveRobot, robotConnectionManager, 100, 500); assertEquals(1, robotConnectionManager.callCount()); } @Test(timeout = 8000) public void moveRobotCloseException() throws Throwable { RobotConnectionManagerImpl robotConnectionManager = new RobotConnectionManagerImpl(); robotConnectionManager.setFailedOnClose(); TestUtils.invokeMethod(mainClass, moveRobot, robotConnectionManager, 100, 500); int callCount = robotConnectionManager.callCount(); int closeCount = robotConnectionManager.closeCount(); assertEquals(String.format("Expected one time getConnection, but was %d", callCount), 1, callCount); assertEquals(String.format("Expected one time close(), but was %d", closeCount), 1, closeCount); } @Test(timeout = 8000) public void moveRobotTry2() throws Throwable { RobotConnectionManagerImpl robotConnectionManager = new RobotConnectionManagerImpl(); robotConnectionManager.setFailedOnClose(); robotConnectionManager.setFailedConnectionCount(1); TestUtils.invokeMethod(mainClass, moveRobot, robotConnectionManager, 100, 500); int callCount = robotConnectionManager.callCount(); int closeCount = robotConnectionManager.closeCount(); assertEquals(String.format("Expected two time getConnection, but was %d", callCount), 2, callCount); assertEquals(String.format("Expected one time close(), but was %d", closeCount), 1, closeCount); } @Test(timeout = 8000) public void moveRobotTry3() throws Throwable { RobotConnectionManagerImpl robotConnectionManager = new RobotConnectionManagerImpl(); robotConnectionManager.setFailedConnectionCount(2); TestUtils.invokeMethod(mainClass, moveRobot, robotConnectionManager, 100, 500); int callCount = robotConnectionManager.callCount(); int closeCount = robotConnectionManager.closeCount(); assertEquals(String.format("Expected three time getConnection(), but was %d", callCount), 3, callCount); assertEquals(String.format("Expected one time close(), but was %d", closeCount), 1, closeCount); } @Test(expected = RobotConnectionException.class, timeout = 8000) public void moveRobotTry4() throws Throwable { RobotConnectionManagerImpl robotConnectionManager = new RobotConnectionManagerImpl(); robotConnectionManager.setFailedOnClose(); robotConnectionManager.setFailedConnectionCount(3); TestUtils.invokeMethod(mainClass, moveRobot, robotConnectionManager, 100, 500); int callCount = robotConnectionManager.callCount(); int closeCount = robotConnectionManager.closeCount(); assertEquals(String.format("Expected three time getConnection(), but was %d", callCount), 3, callCount); assertEquals(String.format("Expected zero time close(), but was %d", closeCount), 0, closeCount); fail("Expected RobotConnectionException"); } @Test(timeout = 8000) public void moveRobotException() throws Exception { RuntimeException expectedException = new RuntimeException(); RobotConnectionManagerImpl robotConnectionManager = new RobotConnectionManagerImpl(); robotConnectionManager.setMoveRobotToException(expectedException); try { TestUtils.invokeMethod(mainClass, moveRobot, robotConnectionManager, 100, 500); } catch (Throwable e) { String message = String.format("Expected RuntimeException, but %s", e.getClass().getSimpleName()); assertEquals(message, expectedException, e); } int callCount = robotConnectionManager.callCount(); int closeCount = robotConnectionManager.closeCount(); assertEquals(String.format("Expected one time getConnection(), but was %d", callCount), 1, callCount); assertEquals(String.format("Expected one time close(), but was %d", closeCount), 1, closeCount); } }
gpl-3.0
LemoProject/Lemo-Application-Server
src/main/java/de/lemo/apps/restws/proxies/questions/QLearningObjectUsage.java
1927
/** * File ./src/main/java/de/lemo/apps/restws/proxies/questions/QLearningObjectUsage.java * Lemo-Application-Server for learning analytics. * Copyright (C) 2015 * Leonard Kappe, Andreas Pursian, Sebastian Schwarzrock, Boris Wenzlaff * * 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 * 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/>. **/ /** * File QLearningObjectUsage.java * Date Feb 14, 2013 */ package de.lemo.apps.restws.proxies.questions; import java.util.List; import javax.ws.rs.FormParam; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import de.lemo.apps.restws.entities.ResultListResourceRequestInfo; import de.lemo.apps.restws.proxies.questions.parameters.MetaParam; /** * Use of learning objects */ public interface QLearningObjectUsage { @POST @Path("learningobjectusage") @Produces(MediaType.APPLICATION_JSON) ResultListResourceRequestInfo compute( @FormParam(MetaParam.COURSE_IDS) List<Long> courseIds, @FormParam(MetaParam.USER_IDS) List<Long> userIds, @FormParam(MetaParam.TYPES) List<String> types, @FormParam(MetaParam.START_TIME) Long startTime, @FormParam(MetaParam.END_TIME) Long endTime, @FormParam(MetaParam.GENDER) List<Long> gender, @FormParam(MetaParam.LEARNING_OBJ_IDS) List<Long> learningObjects); }
gpl-3.0
OutsourcedCoders/SecretProject
src/secretproject/OldRuntime.java
6224
/* * Copyright (C) 2016 Jorge A. Flores-Morales * * This file is part of SecretProject * * SecretProject 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. * * SecretProject 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 SecretProject. If not, see <http://www.gnu.org/licenses/>. */ package secretproject; import static secretproject.resources.Data.*; import secretproject.resources.FileWriting; public class OldRuntime { public static void OldMain(){ //secretproject.resources.WindowsCommands.ClearScreen(); FileWriting fw = new FileWriting(); fw.ChangeFileName("water"); fw.ChangeDirectory("resources"); fw.WriteToFile("Did it work?"); System.out.print("Enter NAME.\n> "); plrNameC = sc.nextLine(); fw.ChangeFileName("name"); fw.ChangeDirectory("savedata"); fw.WriteToFile(plrNameC); //FileWriting name = new FileWriting("name"); //name.WriteToFile(plrNameC, "savedata"); System.out.println("NAME CREATION sucessful."); int loginTries; System.out.print("PASSWORD CREATION.\n> "); plrPswdC = sc.nextLine(); secretproject.resources.WindowsCommands.ClearScreen(); if(plrPswdC.contains(" ")){ System.out.println("NO SPACES"); System.out.println("GOODBYE"); }else{ fw.ChangeFileName("password"); fw.ChangeDirectory("savedata"); fw.WriteToFile(plrPswdC); System.out.println("PASSWORD CREATION sucessful."); for(loginTries = 0; loginTries <= 5; loginTries++){ System.out.print("Enter your PASSWORD.\n> "); if(sc.nextLine().equals(plrPswdC)){ secretproject.resources.WindowsCommands.ClearScreen(); System.out.println("Login sucessful."); break; }else{ secretproject.resources.WindowsCommands.ClearScreen(); System.out.println("Login unsucessful."); System.out.println("Try again."); } } secretproject.resources.WindowsCommands.ClearScreen(); System.out.println("SBURB version 0.0.0.1\n"); System.out.println("SKIANET SYSTEMS INCORPORATED. ALL RIGHTS RESERVED.\n"); System.out.println("SBURB client is running.\n"); System.out.println("Press [ENTER] when ready.\n"); System.out.print("> "); sc.nextLine(); userAnswered = false; while(!userAnswered){ System.out.println("---MENU---"); System.out.println("\tCREATE CHARACTER."); System.out.println("\tQUIT."); userInput = sc.nextLine(); switch(userInput.toUpperCase()){ case "CREATE CHARACTER": userAnswered = true; break; case "QUIT": secretproject.resources.WindowsCommands.ClearScreen(); System.out.print("\n SBURB client shutting down..."); return; } } userAnswered = false; while(!playerCreated) { secretproject.resources.WindowsCommands.ClearScreen(); userInput = sc.nextLine(); System.out.println("PLAYER CREATION running.\n"); while (!userAnswered) { System.out.print("RANDOM or CUSTOM?\n> "); userInput = sc.nextLine(); switch (userInput.toUpperCase()) { case "RANDOM": userInput = sc.nextLine(); switch(userInput.toUpperCase()){ case "YES": break; case "NO": break; default: System.out.println("Not a valid option"); return; } System.out.println("RANDOM GEN CHOSEN\n"); randomChar = true; userAnswered = true; break; case "CUSTOM": System.out.println("CUSTOM NOT FUNCTIONAL\n"); //transition to default... default: System.out.println("Choose \'RANDOM\' or"); System.out.println("\'CUSTOM\'."); break; } } userAnswered = false; if(randomChar){ secretproject.resources.WindowsCommands.ClearScreen(); secretproject.player.PlayerCreation.RandomChar(); secretproject.player.PlayerCreation.classpectGen(); secretproject.lands.LandMain.landGen(); playerCreated = true; }else{ System.out.println("UNFINISHED."); System.out.println("¯\\_(ツ)_/¯"); return; } } System.out.print("\nPress [ENTER] when ready.\n>"); sc.nextLine(); System.out.println("Game starting.\n"); gameStarted = true; while(gameStarted){ System.out.println("You, " + plrNameC + ""); gameStarted = false; } } } }
gpl-3.0
Albertus82/RouterLogger
src/main/java/it/albertus/routerlogger/http/html/RestartHandler.java
2031
package it.albertus.routerlogger.http.html; import java.io.IOException; import java.net.HttpURLConnection; import com.sun.net.httpserver.HttpExchange; import it.albertus.net.httpserver.annotation.Path; import it.albertus.net.httpserver.config.IHttpServerConfig; import it.albertus.net.httpserver.html.HtmlUtils; import it.albertus.routerlogger.engine.RouterLoggerEngine; import it.albertus.routerlogger.resources.Messages; import it.albertus.util.NewLine; @Path("/restart") public class RestartHandler extends AbstractHtmlHandler { public static class Defaults { public static final boolean ENABLED = false; private Defaults() { throw new IllegalAccessError("Constants class"); } } static final String CFG_KEY_ENABLED = "server.handler.restart.enabled"; private final RouterLoggerEngine engine; public RestartHandler(final IHttpServerConfig config, final RouterLoggerEngine engine) { super(config); this.engine = engine; } @Override public void doPost(final HttpExchange exchange) throws IOException { // Headers... setContentTypeHeader(exchange); // Response... final StringBuilder html = new StringBuilder(buildHtmlHeader(Messages.get("lbl.server.restart"))); html.append("<div class=\"page-header\"><h2>").append(HtmlUtils.escapeHtml(Messages.get("lbl.server.restart"))).append("</h2></div>").append(NewLine.CRLF); html.append("<div class=\"alert alert-success alert-h4\" role=\"alert\">").append(HtmlUtils.escapeHtml(Messages.get("msg.server.accepted"))).append("</div>").append(NewLine.CRLF); html.append(buildHtmlFooter()); final byte[] response = html.toString().getBytes(getCharset()); exchange.sendResponseHeaders(HttpURLConnection.HTTP_ACCEPTED, response.length); exchange.getResponseBody().write(response); exchange.getResponseBody().close(); exchange.close(); engine.restart(); } @Override public boolean isEnabled() { return configuration.getBoolean(CFG_KEY_ENABLED, Defaults.ENABLED); } }
gpl-3.0
fact-project/fact-tools
src/main/java/fact/filter/GaussConvolution.java
2129
/** * */ package fact.filter; import fact.Utils; import stream.Data; import stream.ProcessContext; import stream.StatefulProcessor; import stream.annotations.Parameter; /** * @author Kai Bruegge &lt;kai.bruegge@tu-dortmund.de&gt; */ public class GaussConvolution implements StatefulProcessor { @Parameter(required = true) public String key; @Parameter(required = false, defaultValue = "1") public double variance = 1; @Parameter(required = true) public String outputKey; private int numSamples; private double[] coefficents; /** * Returns value of the gaussian function at point x with mean = 0 and variance = variance; * * @param variance the width of your gaussian * @param x the point to evaluate * @return the value at x */ private double gaussKernel(double variance, double x) { variance *= 2; double r = (1 / Math.sqrt(Math.PI * variance)) * Math.exp(-(Math.pow(x, 2) / (variance))); return r; } @Override public void init(ProcessContext context) throws Exception { //see the wikipedia article. apparently this choice is typical numSamples = (int) (4 * Math.sqrt(variance) + 1); coefficents = new double[2 * numSamples + 1]; for (int m = -numSamples; m < numSamples; m++) { coefficents[m + numSamples] = gaussKernel(variance, m); } } @Override public Data process(Data item) { Utils.isKeyValid(item, key, double[].class); // Stopwatch stopwatch = Stopwatch.createUnstarted(); double[] data = (double[]) item.get(key); double[] result = new double[data.length]; for (int i = numSamples; i < result.length - numSamples - 1; i++) { for (int m = -numSamples; m < numSamples; m++) { result[i] += data[i + m] * coefficents[m + numSamples]; } } item.put(outputKey, result); return item; } @Override public void resetState() throws Exception { } @Override public void finish() throws Exception { } }
gpl-3.0
xafero/travelingsales
osmnavigation/src/main/java/org/openstreetmap/travelingsalesman/gps/IGPSProvider.java
4707
/** * IGPSProvider.java * (c) 2007 by <a href="http://Wolschon.biz">Wolschon Softwaredesign und Beratung</a> * This file is part of osmnavigation by Marcus Wolschon <a href="mailto:Marcus@Wolscon.biz">Marcus@Wolscon.biz</a>. * You can purchase support for a sensible hourly rate or * a commercial license of this file (unless modified by others) by contacting him directly. * * osmnavigation 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. * * osmnavigation 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 osmnavigation. If not, see <http://www.gnu.org/licenses/>. * *********************************** * Editing this file: * -For consistent code-quality this file should be checked with the * checkstyle-ruleset enclosed in this project. * -After the design of this file has settled it should get it's own * JUnit-Test that shall be executed regularly. It is best to write * the test-case BEFORE writing this class and to run it on every build * as a regression-test. */ package org.openstreetmap.travelingsalesman.gps; import org.openstreetmap.osm.Plugins.IPlugin; /** * This interface is implemented by plugins that can * provide the current position of the user('s vehicle). * @author <a href="mailto:Marcus@Wolschon.biz">Marcus Wolschon</a> */ public interface IGPSProvider extends IPlugin { /** * Interface for listeners to get informed about * changes of the location of the user. * @author <a href="mailto:Marcus@Wolschon.biz">Marcus Wolschon</a> */ public interface IGPSListener { /** * The location of the user has changed. * @param lat the latitude * @param lon the longitude */ void gpsLocationChanged(final double lat, final double lon); /** * We have no location-fix anymore. */ void gpsLocationLost(); /** * We are have location-fix. */ void gpsLocationObtained(); /** * GPS course over ground has changed. * If course can not derive from gps (NMEA) data directly, * it should be derived from difference latitude and longitude. * * @param course Track angle in degrees */ void gpsCourseChanged(final double course); } /** * Interface for listeners to get informed about * changes of the location and other GPS data, parsed from various gps streams. * @author <a href="mailto:oleg_chubaryov@mail.ru">Oleg Chubaryov</a> */ public interface IExtendedGPSListener extends IGPSListener { /** * GPS date and time has changed. * @param date the date * @param time the time */ void gpsDateTimeChanged(final long date, final long time); /** * GPS fix quality has changed. * @param fixQuality 0 - invalid, 1 - GPS fix, 2 - DGPS fix. */ void gpsFixQualityChanged(final int fixQuality); /** * GPS amount of tracked satellites changed. * @param satellites new amount of used / tracked satellites. */ void gpsUsedSattelitesChanged(final int satellites); /** * GPS altitude has changed. * @param altitude new altitude in meters. */ void gpsAltitudeChanged(final double altitude); /** * GPS Dilution of precision has changed. * @param hdop new horizontal dilution of precision * @param vdop new vertical dilution of precision * @param pdop new position dilution of precision */ void gpsDopChanged(final double hdop, final double vdop, final double pdop); /** * GPS Speed over ground has changed. * @param speed new speed value in knots. */ void gpsSpeedChanged(final double speed); } /** * Add a listener to get informed about * changes of the location of the user. * @param listener the observer */ void addGPSListener(final IGPSListener listener); /** * Remove a listener from informed about changes. * @param listener the observer to remove */ void removeGPSListener(final IGPSListener listener); }
gpl-3.0
CmdrStardust/Alite
src/de/phbouillon/android/games/alite/screens/opengl/ingame/FlightScreen.java
22560
package de.phbouillon.android.games.alite.screens.opengl.ingame; /* Alite - Discover the Universe on your Favorite Android Device * Copyright (C) 2015 Philipp Bouillon * * 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, version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful and * fun, 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://http://www.gnu.org/licenses/gpl-3.0.txt. */ import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.ArrayList; import android.graphics.Rect; import android.opengl.GLES11; import de.phbouillon.android.framework.Game; import de.phbouillon.android.framework.GlScreen; import de.phbouillon.android.framework.Input.TouchEvent; import de.phbouillon.android.framework.Screen; import de.phbouillon.android.framework.impl.AndroidGraphics; import de.phbouillon.android.framework.impl.gl.GlUtils; import de.phbouillon.android.framework.math.Vector3f; import de.phbouillon.android.games.alite.Alite; import de.phbouillon.android.games.alite.AliteLog; import de.phbouillon.android.games.alite.ScreenCodes; import de.phbouillon.android.games.alite.Settings; import de.phbouillon.android.games.alite.model.PlayerCobra; import de.phbouillon.android.games.alite.model.generator.SystemData; import de.phbouillon.android.games.alite.screens.canvas.AliteScreen; import de.phbouillon.android.games.alite.screens.opengl.DefaultCoordinateTransformer; import de.phbouillon.android.games.alite.screens.opengl.IAdditionalGLParameterSetter; import de.phbouillon.android.games.alite.screens.opengl.objects.AliteObject; import de.phbouillon.android.games.alite.screens.opengl.objects.PlanetSpaceObject; import de.phbouillon.android.games.alite.screens.opengl.objects.SphericalSpaceObject; import de.phbouillon.android.games.alite.screens.opengl.objects.space.AIState; import de.phbouillon.android.games.alite.screens.opengl.objects.space.SpaceObject; import de.phbouillon.android.games.alite.screens.opengl.objects.space.ships.Coriolis; import de.phbouillon.android.games.alite.screens.opengl.objects.space.ships.Dodec; import de.phbouillon.android.games.alite.screens.opengl.objects.space.ships.Icosaeder; import de.phbouillon.android.games.alite.screens.opengl.objects.space.ships.TieFighter; import de.phbouillon.android.games.alite.screens.opengl.sprites.AliteHud; import de.phbouillon.android.games.alite.screens.opengl.sprites.buttons.AliteButtons; public class FlightScreen extends GlScreen implements Serializable { private static final long serialVersionUID = -7879686326644011429L; static final Vector3f PLANET_POSITION = new Vector3f(0.0f, 0.0f, 800000.0f); static final Vector3f SHIP_ENTRY_POSITION = new Vector3f(0.0f, 0.0f, 400000.0f); static final float PLANET_SIZE = 80000.0f; static final float SUN_SIZE = 60000.0f; static final float SPACE_STATION_ROTATION_SPEED = 0.2f; private int windowWidth; private int windowHeight; private SphericalSpaceObject star; private SphericalSpaceObject starGlow; private PlanetSpaceObject planet; private InGameManager inGame; private transient AliteScreen informationScreen; private final float [] lightAmbient = { 0.5f, 0.5f, 0.7f, 1.0f }; private final float [] lightDiffuse = { 0.4f, 0.4f, 0.8f, 1.0f }; private final float [] lightSpecular = { 0.5f, 0.5f, 1.0f, 1.0f }; private final float [] lightPosition = { 100.0f, 30.0f, -10.0f, 1.0f }; private final float [] sunLightAmbient = {1.0f, 1.0f, 1.0f, 1.0f}; private final float [] sunLightDiffuse = {1.0f, 1.0f, 1.0f, 1.0f}; private final float [] sunLightSpecular = {1.0f, 1.0f, 1.0f, 1.0f}; private final float [] sunLightPosition = {0.0f, 0.0f, 0.0f, 1.0f}; private final float [] sunLightEmission = {4.0f, 2.8f, 0.0f, 0.0f}; private final float [] noEmission = {0.0f, 0.0f, 0.0f, 0.0f}; private final ArrayList <AliteObject> allObjects = new ArrayList<AliteObject>(); private SpaceObject spaceStation; private boolean resetSpaceStation = true; private boolean fromStation; private boolean witchSpace = false; private boolean paused = false; private long lastPauseCall = -1; private boolean handleUi = true; private boolean needsActivation = true; private transient boolean isSaving = false; private transient long timeToExitTimer = -1; private Vector3f v0 = new Vector3f(0, 0, 0); private Vector3f v1 = new Vector3f(0, 0, 0); private Vector3f v2 = new Vector3f(0, 0, 0); public FlightScreen(Game game, boolean fromStation) { super(game); timeToExitTimer = -1; AliteLog.e("Flight Screen Constructor", "FSC -- fromStation == " + fromStation); SHIP_ENTRY_POSITION.z = Settings.enterInSafeZone ? 685000.0f : 400000.0f; this.fromStation = fromStation; AliteButtons.OVERRIDE_HYPERSPACE = false; AliteButtons.OVERRIDE_INFORMATION = false; AliteButtons.OVERRIDE_MISSILE = false; AliteButtons.OVERRIDE_LASER = false; AliteButtons.OVERRIDE_TORUS = false; InGameManager.OVERRIDE_SPEED = false; ObjectSpawnManager.SHUTTLES_ENABLED = true; ObjectSpawnManager.ASTEROIDS_ENABLED = true; ObjectSpawnManager.CONDITION_RED_OBJECTS_ENABLED = true; ObjectSpawnManager.THARGOIDS_ENABLED = true; ObjectSpawnManager.THARGONS_ENABLED = true; ObjectSpawnManager.TRADERS_ENABLED = true; ObjectSpawnManager.VIPERS_ENABLED = true; } public static FlightScreen createScreen(Alite alite, final DataInputStream dis) throws IOException, ClassNotFoundException { alite.getFileUtils().loadCommander(alite, dis); ObjectInputStream ois = new ObjectInputStream(dis); AliteLog.e("Initializing Flight Screen", "---------------------------------------------------------------"); FlightScreen fs = (FlightScreen) ois.readObject(); fs.needsActivation = false; fs.resetSpaceStation = false; fs.timeToExitTimer = -1; return fs; } public static boolean initialize(Alite alite, final DataInputStream dis) { try { FlightScreen fs = createScreen(alite, dis); alite.setScreen(fs); AliteLog.e("Flight Screen created from state", "---------------------------------------------------------------"); return true; } catch (ClassNotFoundException e) { AliteLog.e("Class not found", e.getMessage(), e); } catch (IOException e) { AliteLog.e("Error in Initializer", e.getMessage(), e); } return false; } private void readObject(ObjectInputStream in) throws IOException { try { AliteLog.e("readObject", "FlightScreen.readObject"); in.defaultReadObject(); AliteLog.e("readObject", "FlightScreen.readObject I"); setPause(true); AliteLog.e("readObject", "FlightScreen.readObject II"); isSaving = false; } catch (ClassNotFoundException e) { AliteLog.e("Class not found", e.getMessage(), e); } } public boolean isDisposed() { return isDisposed; } public void enterWitchSpace() { witchSpace = true; } public void togglePause() { if (inGame != null) { if (lastPauseCall == -1 || (System.nanoTime() - lastPauseCall) > 1000000000) { paused = !paused; inGame.setPaused(paused); lastPauseCall = System.nanoTime(); } } } public void setPause(boolean b) { paused = b; if (inGame != null) { inGame.setPaused(b); } if (b) { lastPauseCall = System.nanoTime(); } } @Override public void onActivation() { if (!needsActivation) { needsActivation = true; Rect visibleArea = ((AndroidGraphics) game.getGraphics()).getVisibleArea(); windowWidth = visibleArea.width(); windowHeight = visibleArea.height(); initializeGl(visibleArea); AliteHud.ct = new DefaultCoordinateTransformer((Alite) game); setPause(true); return; } Rect visibleArea = ((AndroidGraphics) game.getGraphics()).getVisibleArea(); windowWidth = visibleArea.width(); windowHeight = visibleArea.height(); initializeGl(visibleArea); AliteHud.ct = new DefaultCoordinateTransformer((Alite) game); inGame = new InGameManager((Alite) game, new AliteHud((Alite) game), "textures/star_map.png", lightPosition, fromStation, true); PlayerCobra cobra = ((Alite) game).getCobra(); cobra.setMissileTargetting(false); cobra.setMissileLocked(false); cobra.setLaserTemperature(0); cobra.setCabinTemperature(0); cobra.setAltitude(fromStation ? PlayerCobra.MAX_ALTITUDE / 2 : PlayerCobra.MAX_ALTITUDE); cobra.setEnergy(PlayerCobra.MAX_ENERGY); cobra.setFrontShield((int) PlayerCobra.MAX_SHIELD); cobra.setRearShield((int) PlayerCobra.MAX_SHIELD); if (fromStation) { inGame.getShip().applyDeltaRotation(180.0f, 0, 0); } inGame.getShip().setSpeed(-140.0f); initializeObjects(); if (witchSpace) { inGame.enterWitchSpace(); } else { inGame.preMissionCheck(); } } public void setForwardView() { inGame.forceForwardView(); } public void setInformationScreen(AliteScreen newInformationScreen) { if (this.informationScreen != null) { this.informationScreen.dispose(); } this.informationScreen = newInformationScreen; if (this.informationScreen == null) { Rect visibleArea = ((AndroidGraphics) game.getGraphics()).getVisibleArea(); windowWidth = visibleArea.width(); windowHeight = visibleArea.height(); initializeGl(visibleArea); inGame.resetHud(); } ((Alite) game).getNavigationBar().setFlightMode(this.informationScreen != null); } public AliteScreen getInformationScreen() { return informationScreen; } public InGameManager getInGameManager() { return inGame; } private void initializeObjects() { allObjects.clear(); Alite alite = (Alite) game; SystemData currentSystem = alite.getPlayer().getCurrentSystem(); int starTexture = currentSystem == null ? 0 : currentSystem.getStarTexture(); String starTextureName; float sunSize; if (starTexture == 22) { starTextureName = "textures/stars/dwarf/b.png"; sunLightEmission[0] = 0.5f; sunLightEmission[1] = 0.0f; sunLightEmission[2] = 0.0f; sunLightEmission[3] = 1.0f; sunSize = 5000.0f; } else if (starTexture == 21) { starTextureName = "textures/stars/dwarf/a.png"; sunLightEmission[0] = 0.5f; sunLightEmission[1] = 0.0f; sunLightEmission[2] = 0.5f; sunLightEmission[3] = 1.0f; sunSize = 10000.0f; } else { starTextureName = "textures/stars/" + ("123".charAt(starTexture / 7) + "/" + "obafgkm".charAt(starTexture % 7)) + ".png"; sunSize = SUN_SIZE - (starTexture % 7) * 7000.0f; int starType = starTexture % 7; switch (starType) { case 0: sunLightEmission[0] = 0.5f; sunLightEmission[1] = 0.5f; sunLightEmission[2] = 1.0f; sunLightEmission[3] = 1.0f; break; case 1: sunLightEmission[0] = 0.3f; sunLightEmission[1] = 0.3f; sunLightEmission[2] = 1.0f; sunLightEmission[3] = 1.0f; break; case 2: sunLightEmission[0] = 0.1f; sunLightEmission[1] = 0.1f; sunLightEmission[2] = 1.0f; sunLightEmission[3] = 1.0f; break; case 3: sunLightEmission[0] = 0.8f; sunLightEmission[1] = 0.8f; sunLightEmission[2] = 1.0f; sunLightEmission[3] = 1.0f; break; case 4: sunLightEmission[0] = 0.8f; sunLightEmission[1] = 0.8f; sunLightEmission[2] = 0.5f; sunLightEmission[3] = 1.0f; break; case 5: sunLightEmission[0] = 0.8f; sunLightEmission[1] = 0.5f; sunLightEmission[2] = 0.3f; sunLightEmission[3] = 1.0f; break; case 6: sunLightEmission[0] = 1.0f; sunLightEmission[1] = 0.5f; sunLightEmission[2] = 0.5f; sunLightEmission[3] = 1.0f; break; } } star = new SphericalSpaceObject((Alite) game, "Sun", sunSize, 30, starTextureName); star.setVisibleOnHud(false); star.setAdditionalGLParameters(new IAdditionalGLParameterSetter(){ private static final long serialVersionUID = -7931217736505566905L; @Override public void setUp() { GLES11.glMaterialfv(GLES11.GL_FRONT_AND_BACK, GLES11.GL_EMISSION, sunLightEmission, 0); } @Override public void tearDown() { GLES11.glMaterialfv(GLES11.GL_FRONT_AND_BACK, GLES11.GL_EMISSION, noEmission, 0); } }); starGlow = new SphericalSpaceObject((Alite) game, "Glow", sunSize + 60.0f, 30, "textures/glow_mask2.png") { private static final long serialVersionUID = -437275620274071131L; public boolean needsDepthTest() { return false; } }; starGlow.setVisibleOnHud(false); starGlow.setAdditionalGLParameters(new IAdditionalGLParameterSetter() { private static final long serialVersionUID = -7651239619882350365L; @Override public void setUp() { GLES11.glDisable(GLES11.GL_CULL_FACE); GLES11.glEnable(GLES11.GL_BLEND); GLES11.glBlendFunc(GLES11.GL_SRC_ALPHA, GLES11.GL_ONE); } @Override public void tearDown() { GLES11.glEnable(GLES11.GL_CULL_FACE); GLES11.glDisable(GLES11.GL_BLEND); } }); planet = new PlanetSpaceObject(alite, currentSystem, false); planet.applyDeltaRotation(23, 0, 14); planet.setPosition(PLANET_POSITION); if (currentSystem == null) { spaceStation = new Coriolis((Alite) game); } else if (currentSystem.getTechLevel() > 13) { spaceStation = new Icosaeder((Alite) game); } else if (currentSystem.getTechLevel() > 9) { spaceStation = new Dodec((Alite) game); } else { spaceStation = new Coriolis((Alite) game); } spaceStation.setPosition(inGame.getSystemStationPosition()); if (fromStation) { spaceStation.setIdentified(); } else { if (alite.getPlayer().getCurrentSystem() != null && alite.getPlayer().getCurrentSystem().getIndex() == 256) { initializeGameOverParade(); } } allObjects.add(star); allObjects.add(starGlow); allObjects.add(planet); allObjects.add(spaceStation); inGame.setSun(star); inGame.setSunGlow(starGlow); inGame.setPlanet(planet); inGame.setStation(spaceStation); inGame.initializeViperAction(); } private void initializeGameOverParade() { for (int i = 0; i < 20; i++) { allObjects.add(new TieFighter((Alite) game)); } } public void initializeGl(final Rect visibleArea) { float ratio = (float) windowWidth / (float) windowHeight; GlUtils.setViewport(visibleArea); GLES11.glDisable(GLES11.GL_FOG); GLES11.glPointSize(1.0f); GLES11.glLineWidth(1.0f); GLES11.glTexEnvf(GLES11.GL_TEXTURE_ENV, GLES11.GL_TEXTURE_ENV_MODE, GLES11.GL_MODULATE); GLES11.glBlendFunc(GLES11.GL_SRC_ALPHA, GLES11.GL_ONE_MINUS_SRC_ALPHA); GLES11.glDisable(GLES11.GL_BLEND); GLES11.glMatrixMode(GLES11.GL_PROJECTION); GLES11.glLoadIdentity(); GlUtils.gluPerspective(game, 45.0f, ratio, 1.0f, 900000.0f); GLES11.glMatrixMode(GLES11.GL_MODELVIEW); GLES11.glLoadIdentity(); GLES11.glClearColor(0.0f, 0.0f, 0.0f, 0.0f); GLES11.glShadeModel(GLES11.GL_SMOOTH); GLES11.glLightfv(GLES11.GL_LIGHT1, GLES11.GL_AMBIENT, lightAmbient, 0); GLES11.glLightfv(GLES11.GL_LIGHT1, GLES11.GL_DIFFUSE, lightDiffuse, 0); GLES11.glLightfv(GLES11.GL_LIGHT1, GLES11.GL_SPECULAR, lightSpecular, 0); GLES11.glLightfv(GLES11.GL_LIGHT1, GLES11.GL_POSITION, lightPosition, 0); GLES11.glEnable(GLES11.GL_LIGHT1); GLES11.glLightfv(GLES11.GL_LIGHT2, GLES11.GL_AMBIENT, sunLightAmbient, 0); GLES11.glLightfv(GLES11.GL_LIGHT2, GLES11.GL_DIFFUSE, sunLightDiffuse, 0); GLES11.glLightfv(GLES11.GL_LIGHT2, GLES11.GL_SPECULAR, sunLightSpecular, 0); GLES11.glLightfv(GLES11.GL_LIGHT2, GLES11.GL_POSITION, sunLightPosition, 0); GLES11.glEnable(GLES11.GL_LIGHT2); GLES11.glEnable(GLES11.GL_LIGHTING); GLES11.glClear(GLES11.GL_COLOR_BUFFER_BIT); GLES11.glHint(GLES11.GL_PERSPECTIVE_CORRECTION_HINT, GLES11.GL_NICEST); GLES11.glHint(GLES11.GL_POLYGON_SMOOTH_HINT, GLES11.GL_NICEST); GLES11.glEnable(GLES11.GL_TEXTURE_2D); GLES11.glEnable(GLES11.GL_CULL_FACE); } private void performResetSpaceStation() { spaceStation.orientTowards(PLANET_POSITION.x, PLANET_POSITION.y, PLANET_POSITION.z, 0, 1, 0); spaceStation.applyDeltaRotation(0, 180.0f, 0); if (fromStation) { inGame.getShip().orientTowards(PLANET_POSITION.x, PLANET_POSITION.y, PLANET_POSITION.z, 0, 1, 0); float fx = spaceStation.getForwardVector().x * 1800.0f; float fy = spaceStation.getForwardVector().y * 1800.0f; float fz = spaceStation.getForwardVector().z * 1800.0f; inGame.getShip().setPosition(spaceStation.getPosition().x + fx, spaceStation.getPosition().y + fy, spaceStation.getPosition().z + fz); } else { inGame.getShip().applyDeltaRotation(180.0f, 0, 0); inGame.getShip().setPosition(SHIP_ENTRY_POSITION); int count = 0; inGame.getShip().getPosition().copy(v0); inGame.getShip().getRightVector().copy(v1); v1.scale(5000); for (AliteObject ao: allObjects) { if (ao instanceof TieFighter) { if (count % 2 == 0) { v0.add(v1, v2); TieFighter tie = (TieFighter) ao; tie.setPosition(v2); tie.orientTowards(inGame.getShip(), 0); tie.setAIState(AIState.IDLE, (Object []) null); count++; } else { v0.sub(v1, v2); TieFighter tie = (TieFighter) ao; tie.setPosition(v2); tie.orientTowards(inGame.getShip(), 0); tie.setAIState(AIState.IDLE, (Object []) null); inGame.getStation().getPosition().sub(inGame.getShip().getPosition(), v2); v2.scale(0.1f); v0.add(v2); count++; } } } inGame.getShip().applyDeltaRotation((float) Math.random() * 360.0f, (float) Math.random() * 360.0f, (float) Math.random() * 360.0f); inGame.getShip().assertOrthoNormal(); } inGame.initStarDust(); resetSpaceStation = false; } public void setHandleUI(boolean b) { handleUi = b; } public boolean isHandleUi() { return handleUi; } @Override public void performUpdate(float deltaTime) { if (isSaving) { return; } try { if (paused) { for (TouchEvent event: game.getInput().getTouchEvents()) { if (event.type == TouchEvent.TOUCH_UP) { togglePause(); } } return; } if (isDisposed || inGame == null) { return; } if (inGame.isPlayerAlive()) { int tf = ((Alite) game).getTimeFactor(); while (--tf >= 0 && inGame.isPlayerAlive()) { inGame.performUpdate(deltaTime, allObjects); } } else { if (timeToExitTimer == -1) { timeToExitTimer = System.currentTimeMillis(); } if ((System.currentTimeMillis() - timeToExitTimer) > 10000) { // Safeguard for endless loops... inGame.terminateToTitleScreen(); } inGame.performUpdate(deltaTime, allObjects); } if (informationScreen != null) { informationScreen.update(deltaTime); } Screen newScreen = inGame.getNewScreen(); if (newScreen == null && informationScreen == null && handleUi) { for (TouchEvent event: game.getInput().getTouchEvents()) { if (inGame.handleUI(event)) { newScreen = inGame.getNewScreen(); continue; } } } else { game.getInput().getTouchEvents(); } if (newScreen != null) { performScreenChange(newScreen); } else { deltaTime *= ((Alite) game).getTimeFactor(); if (star != null) { star.applyDeltaRotation(0.0f, (float) Math.toDegrees(0.02f * deltaTime), 0.0f); } if (planet != null) { planet.applyDeltaRotation(0.0f, (float) Math.toDegrees(0.015f * deltaTime), 0.0f); } if (spaceStation != null) { if (resetSpaceStation) { performResetSpaceStation(); } spaceStation.applyDeltaRotation(0.0f, 0.0f, (float) Math.toDegrees(SPACE_STATION_ROTATION_SPEED * deltaTime)); } } } catch (NullPointerException e) { if (inGame.isDestroyed()) { // Ok, ignore it. return; } throw e; } } @Override public void performPresent(float deltaTime) { try { if (isDisposed) { return; } if (isSaving) { if (inGame != null) { inGame.renderScroller(deltaTime); } return; } if (informationScreen != null) { informationScreen.present(deltaTime); } else { if (inGame != null) { inGame.render(deltaTime, allObjects); } } } catch (NullPointerException e) { if (inGame.isDestroyed()) { // Ok, ignore it. return; } throw e; } } @Override public void dispose() { super.dispose(); if (inGame != null && inGame.getPostDockingHook() != null) { inGame.getPostDockingHook().execute(0); } if (inGame != null) { inGame.destroy(); } if (planet != null) { planet.dispose(); planet = null; } if (spaceStation != null) { spaceStation.dispose(); spaceStation = null; } } @Override public void postScreenChange() { inGame = null; } @Override public void loadAssets() { } @Override public void pause() { super.pause(); if (inGame != null) { inGame.destroy(); } } @Override public void resume() { super.resume(); Rect visibleArea = ((AndroidGraphics) game.getGraphics()).getVisibleArea(); initializeGl(visibleArea); ((Alite) game).getTextureManager().reloadAllTextures(); } @Override public void postPresent(float deltaTime) { if (informationScreen != null) { informationScreen.postPresent(deltaTime); } } @Override public void renderNavigationBar() { super.renderNavigationBar(); if (informationScreen != null) { informationScreen.renderNavigationBar(); } } @Override public int getScreenCode() { return ScreenCodes.FLIGHT_SCREEN; } @Override public void saveScreenState(DataOutputStream dos) throws IOException { isSaving = true; setPause(true); ((Alite) game).getFileUtils().saveCommander((Alite) game, dos); inGame.clearObjectTransformations(); ObjectOutputStream oos = new ObjectOutputStream(dos); oos.writeObject(this); } public AliteObject findObjectByName(String name) { for (AliteObject ao: allObjects) { if (name.equals(ao.getName())) { return ao; } } return null; } }
gpl-3.0
115kino/Player-progression
src/main/java/com/legacy/player_progression/capabilities/util/CapabilityProvider.java
1277
package com.legacy.player_progression.capabilities.util; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.EnumFacing; import net.minecraftforge.common.capabilities.Capability; import net.minecraftforge.common.capabilities.ICapabilityProvider; import net.minecraftforge.common.util.INBTSerializable; public class CapabilityProvider<C extends Inbt> implements ICapabilityProvider, INBTSerializable<NBTTagCompound> { private C capability; private Capability<?> handler; public CapabilityProvider(C capability, Capability<?> handler) { this.capability = capability; this.handler = handler; } @Override public boolean hasCapability(Capability<?> capability, EnumFacing facing) { return this.capability.getClass() == capability.getDefaultInstance().getClass(); } @Override @SuppressWarnings("unchecked") public <T> T getCapability(Capability<T> capability, EnumFacing facing) { if (capability == handler) { return (T) this.capability; } return null; } @Override public NBTTagCompound serializeNBT() { NBTTagCompound compound = new NBTTagCompound(); this.capability.writeNBTData(compound); return compound; } @Override public void deserializeNBT(NBTTagCompound nbt) { this.capability.readNBTData(nbt); } }
gpl-3.0
waynem77/BSCMail
src/main/java/io/github/waynem77/bscmail/help/HelpFileFromResourceDisplay.java
2908
/* * Copyright © 2019 its authors. See the file "AUTHORS" for details. * * This file is part of BSCMail. * * BSCMail 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. * * BSCMail 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 BSCMail. If not, see <http://www.gnu.org/licenses/>. */ package io.github.waynem77.bscmail.help; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; /** * Displays application help by opening and displaying a file contained within * the application Jar. * * @author Wayne Miller (waynem77@yahoo.com) * @since 4.0 */ public class HelpFileFromResourceDisplay implements HelpDisplay { /** * The name of the resource containing the help file. */ private final String resource; /** * The suffix of the help file. */ private final String fileSuffix; /** * Constructs a new HelpFileFromResourceDisplay object. * * @param resource the name of the resource containing the help file; may * not be null * @throws NullPointerException if {@code resource} is null */ public HelpFileFromResourceDisplay(String resource) { if (resource == null) { throw new NullPointerException("resource may not be null"); } this.resource = resource; char suffixSeparator = '.'; int separatorIndex = resource.lastIndexOf(suffixSeparator); // If the resource name has no separator (separatorIndex == -1) or // begins with the separator (separatorIndex == 0), then there really is // no suffix. Otherwise, we want to store the suffix with the separator. fileSuffix = (separatorIndex > 0) ? resource.substring(separatorIndex) : ""; } // HelpFileDisplay() /** * {@inheritDoc} */ @Override public void displayHelp() throws IOException { final String TEMP_FILE_PREFIX = "bscmail"; Path tempFile = Files.createTempFile(TEMP_FILE_PREFIX, fileSuffix); try (InputStream helpFileInputStream = ClassLoader.getSystemResourceAsStream(resource)) { Files.copy(helpFileInputStream, tempFile, StandardCopyOption.REPLACE_EXISTING); } // try HelpDisplay helpDisplay = new HelpFileDisplay(tempFile.toString()); helpDisplay.displayHelp(); } // displayHelp() } // HelpFileFromResourceDisplay
gpl-3.0
CyberPhysicalSecurityLab/Proviz-Desktop
src/main/java/proviz/library/utilities/FileOperations.java
6221
package proviz.library.utilities; import proviz.ProjectConstants; import proviz.devicedatalibrary.DataManager; import java.io.*; import java.net.URI; import java.net.URL; import java.nio.file.*; import java.security.CodeSource; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.jar.JarFile; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; /** * Created by Burak on 10/11/16. */ public class FileOperations { private static FileOperations fileOperations; public static FileOperations init() { if(fileOperations == null ) fileOperations = new FileOperations(); return fileOperations; } public ArrayList<String> getBoardTypes(String path) { ArrayList<String> files = getResourceFoldersName(path); return files; } public ArrayList<String> getSensors(String path) { return null; } public ArrayList<String> boardNamesInFolder(String folderResourceName) { return null; } public ProjectConstants.OS_TYPE checkOS() { String osName = System.getProperty("os.name"); if(osName.indexOf("Mac") >= 0 || osName.indexOf("darwin") >= 0) { return ProjectConstants.OS_TYPE.OSX; } else if(osName.indexOf("Win") >= 0) { return ProjectConstants.OS_TYPE.WINDOWS; } else if(osName.indexOf("nux") >=0) { return ProjectConstants.OS_TYPE.LINUX; } return null; } private boolean checkProvizFolder() { File folder = new File(ProjectConstants.init().getProvizFolderPath()); if(folder.exists() && folder.isFile() == false) { return true; } return false; } public void initializeProvizFolder() { String provizFolder = ProjectConstants.init().getProvizFolderPath(); if(!checkProvizFolder()) { } File tempFolder= new File(provizFolder+ProjectConstants.init().getFolderSeperator()+"temp"); if(!tempFolder.exists()) tempFolder.mkdir(); } private ArrayList<String> getResourceFoldersName(String path) { ArrayList<String> folderNames = new ArrayList<>(); try{ File file = new File(path); String[] names = file.list(); for(String name : names) { if (new File(path + name).isDirectory()) { folderNames.add(name); } } } catch (Exception ex) { ex.printStackTrace(); } return folderNames; } private ArrayList<File> getResourceFiles(String folderPath) throws IOException { ArrayList<File> files = new ArrayList<>(); InputStream inputStream = getClass().getResourceAsStream(folderPath); try { File file = new File(folderPath); String[] names = file.list(); for (String name : names) { File fl =new File(folderPath + ProjectConstants.init().getFolderSeperator() + name); if (fl.isFile()) { files.add(fl); } } } catch (Exception ex) { ex.printStackTrace(); } return files; } public void getFiles() throws NullPointerException, IOException { if(ProjectConstants.isProd == true) { // JAR file extraction CodeSource codeSource = this.getClass().getProtectionDomain().getCodeSource(); if(codeSource == null) throw new NullPointerException("Protection domain is null"); URL jarPath = codeSource.getLocation(); JarFile jarfile = new JarFile(codeSource.getLocation().getFile()); URI uri = URI.create("jar:file:" + jarfile); Map<String, String> env = new HashMap<>(); env.put("create", "true"); FileSystem fileSystem = FileSystems.newFileSystem(uri, env, null); Path generatedClientPath = fileSystem.getPath("/clientapplication"); ZipInputStream zipInputStream = new ZipInputStream(jarPath.openStream()); while(true) { ZipEntry zipEntry = zipInputStream.getNextEntry(); if(zipEntry == null) break; String name = zipEntry.getName(); if(name.startsWith("sensors/images/") && !zipEntry.isDirectory() ) { // Sensor Images Load DataManager.getInstance().addSensorImages(ImageLoader.LoadImageIconFromJAR(zipEntry,zipInputStream),zipEntry.getName()); } else { if(name.startsWith("sensors/") && !zipEntry.isDirectory() ) { DataManager.getInstance().addSensorFromJSONInputStream(jarfile.getInputStream(zipEntry)); // JSON Sensor File Images } } if(name.startsWith("boards/") && !zipEntry.isDirectory()) { DataManager.getInstance().addBoardFromJSONInputStream(jarfile.getInputStream(zipEntry)); } } } else { //not ProdVersion DataManager.getInstance().addSensorImages(getResourceFiles(this.getClass().getResource("/sensors/images/").getPath())); DataManager.getInstance().addBoards(getResourceFiles(this.getClass().getResource("/boards/arduino").getPath())); if(this.getClass().getResource("/boards/beaglebone")!= null) DataManager.getInstance().addBoards(getResourceFiles(this.getClass().getResource("/boards/beaglebone").getPath())); if(this.getClass().getResource("/boards/raspberrypi")!= null) DataManager.getInstance().addBoards(getResourceFiles(this.getClass().getResource("/boards/raspberrypi").getPath())); DataManager.getInstance().addSensors(getResourceFiles(this.getClass().getResource("/sensors/").getPath())); } } }
gpl-3.0
rpmartin85/NiroSuite
NiroRefinements/src/conn/ConnDataOut.java
438
package conn; import org.json.simple.JSONObject; import logical.ConfigNiro; public class ConnDataOut { private String user; private String password; public ConnDataOut() { JSONObject jO = new JSONObject(); jO = ConfigNiro.getJson(); user = jO.get("user").toString(); password = jO.get("password").toString(); } public String getUser() { return user; } public String getPassword() { return password; } }
gpl-3.0
prdim/jimbot
src/ru/jimbot/modules/anek/DBAneks.java
3682
/** * JimBot - Java IM Bot * Copyright (C) 2006-2009 JimBot project * 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package ru.jimbot.modules.anek; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.Statement; import java.util.Vector; import ru.jimbot.db.DBAdaptor; /** * * @author Prolubnikov Dmitry */ public class DBAneks extends DBAdaptor{ /** Creates a new instance of DBAneks */ public DBAneks() throws Exception { // this.DRIVER = "org.hsqldb.jdbcDriver"; // this.URL = "jdbc:hsqldb:file:"; // this.dbName = "db/aneks"; } public void createDB(){ // if(!MainProps.isExtdb()){ // Log.info("DB aneks not found. Create new DB..."); // try{ // executeQuery("CREATE CACHED TABLE ANEKS(ID INTEGER NOT NULL PRIMARY KEY,TEXT LONGVARCHAR)"); // executeQuery("insert into aneks values (0, 'test')"); //// commit(); // }catch(Exception ex){ // ex.printStackTrace(); // } // } else { // // } } public Aneks getObject(String q){ Aneks an = new Aneks(); Statement stm = null; ResultSet rs = null; try{ // openQuery(q); stm = getDb().createStatement(); rs = stm.executeQuery(q); rs.next(); an.id = rs.getInt(1); an.text = rs.getString(2); // closeQuery(); } catch (Exception ex){ ex.printStackTrace(); } finally { if(rs!=null) try{rs.close();}catch(Exception e){}; if(stm!=null) try{stm.close();}catch(Exception e){}; } return an; } public Vector<Aneks> getObjectVector(String q){ Vector<Aneks> v = new Vector<Aneks>(1); Statement stm = null; ResultSet rs = null; try{ // openQuery(q); stm = getDb().createStatement(); rs = stm.executeQuery(q); while(rs.next()) { Aneks an = new Aneks(); an.id = rs.getInt(1); an.text = rs.getString(2); v.addElement(an); } // closeQuery(); } catch (Exception ex){ ex.printStackTrace(); } finally { if(rs!=null) try{rs.close();}catch(Exception e){}; if(stm!=null) try{stm.close();}catch(Exception e){}; } return v; } public void insertObject(Aneks an){ try{ PreparedStatement pst = getDb().prepareStatement("insert into aneks values (?, ?)"); pst.setInt(1,an.id); pst.setString(2,an.text); pst.execute(); pst.close(); // commit(); } catch (Exception ex){ ex.printStackTrace(); } } }
gpl-3.0
NachoG1985/DisenioDeSistemas2017
tp/SistemaDeApoyoADecisiones/src/main/java/com/sysad/common/entities/Cuenta.java
158
package com.sysad.common.entities; public class Cuenta { private String nombre; private String empresa; private String periodo; private Integer valor; }
gpl-3.0
jmrunge/cipres-legacy
src/main/java/ar/com/zir/cipres/legacy/api/servicios/telefoniacelular/TipoPrefijo.java
5352
/* * 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 ar.com.zir.cipres.legacy.api.servicios.telefoniacelular; import java.io.Serializable; import java.util.Collection; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author jmrunge */ @Entity @Table(name = "TIPO_PREFIJO") @XmlRootElement @NamedQueries({ @NamedQuery(name = "TipoPrefijo.findAll", query = "SELECT t FROM TipoPrefijo t"), @NamedQuery(name = "TipoPrefijo.findByTipoprefijo", query = "SELECT t FROM TipoPrefijo t WHERE t.tipoprefijo = :tipoprefijo"), @NamedQuery(name = "TipoPrefijo.findByDescripcion", query = "SELECT t FROM TipoPrefijo t WHERE t.descripcion = :descripcion"), @NamedQuery(name = "TipoPrefijo.findByPeriodotasacion", query = "SELECT t FROM TipoPrefijo t WHERE t.periodotasacion = :periodotasacion"), @NamedQuery(name = "TipoPrefijo.findByPagatitular", query = "SELECT t FROM TipoPrefijo t WHERE t.pagatitular = :pagatitular"), @NamedQuery(name = "TipoPrefijo.findByHorario", query = "SELECT t FROM TipoPrefijo t WHERE t.horario = :horario")}) public class TipoPrefijo implements Serializable { private static final long serialVersionUID = 1L; @Id @Basic(optional = false) @NotNull @Column(name = "Tipo_prefijo") private Short tipoprefijo; @Basic(optional = false) @NotNull @Size(min = 1, max = 40) @Column(name = "Descripcion") private String descripcion; @Column(name = "Periodo_tasacion") private Short periodotasacion; @Basic(optional = false) @NotNull @Column(name = "Paga_titular") private boolean pagatitular; @Column(name = "Horario") private Short horario; @OneToMany(cascade = CascadeType.ALL, mappedBy = "tipoprefijo") private Collection<PrefijoTelefonico> prefijoTelefonicoCollection; @JoinColumn(name = "Id_clave", referencedColumnName = "Id_clave") @ManyToOne private Clave idclave; @JoinColumn(name = "Id_tipo_dia", referencedColumnName = "Id_tipo_dia") @ManyToOne private TipoDia idtipodia; public TipoPrefijo() { } public TipoPrefijo(Short tipoprefijo) { this.tipoprefijo = tipoprefijo; } public TipoPrefijo(Short tipoprefijo, String descripcion, boolean pagatitular) { this.tipoprefijo = tipoprefijo; this.descripcion = descripcion; this.pagatitular = pagatitular; } public Short getTipoprefijo() { return tipoprefijo; } public void setTipoprefijo(Short tipoprefijo) { this.tipoprefijo = tipoprefijo; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public Short getPeriodotasacion() { return periodotasacion; } public void setPeriodotasacion(Short periodotasacion) { this.periodotasacion = periodotasacion; } public boolean getPagatitular() { return pagatitular; } public void setPagatitular(boolean pagatitular) { this.pagatitular = pagatitular; } public Short getHorario() { return horario; } public void setHorario(Short horario) { this.horario = horario; } @XmlTransient public Collection<PrefijoTelefonico> getPrefijoTelefonicoCollection() { return prefijoTelefonicoCollection; } public void setPrefijoTelefonicoCollection(Collection<PrefijoTelefonico> prefijoTelefonicoCollection) { this.prefijoTelefonicoCollection = prefijoTelefonicoCollection; } public Clave getIdclave() { return idclave; } public void setIdclave(Clave idclave) { this.idclave = idclave; } public TipoDia getIdtipodia() { return idtipodia; } public void setIdtipodia(TipoDia idtipodia) { this.idtipodia = idtipodia; } @Override public int hashCode() { int hash = 0; hash += (tipoprefijo != null ? tipoprefijo.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof TipoPrefijo)) { return false; } TipoPrefijo other = (TipoPrefijo) object; if ((this.tipoprefijo == null && other.tipoprefijo != null) || (this.tipoprefijo != null && !this.tipoprefijo.equals(other.tipoprefijo))) { return false; } return true; } @Override public String toString() { return "ar.com.zir.cipres.legacy.api.servicios.telefoniacelular.TipoPrefijo[ tipoprefijo=" + tipoprefijo + " ]"; } }
gpl-3.0
bhavyanshu/ITM_Android_App
Android/ITM/src/com/wbs/itm/PdfViewActivity.java
2674
/** * Copyright 2013 Bhavyanshu Parasher * This file is part of "ITM University Android Application". * "ITM University Android Application" 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. * "ITM University Android Application" 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 "ITM University Android Application". * If not, see http://www.gnu.org/licenses/. */ /** * This is an initializer for pdf viewer. * Thanks to this github repository -> https://github.com/jblough/Android-Pdf-Viewer-Library */ package com.wbs.itm; import com.google.analytics.tracking.android.EasyTracker; import android.os.Bundle; import net.sf.andpdf.pdfviewer.PdfViewerActivity; public class PdfViewActivity extends PdfViewerActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //setContentView(R.layout.pdfview); } @Override public int getPreviousPageImageResource() { return R.drawable.left_arrow; } @Override public int getNextPageImageResource() { return R.drawable.right_arrow; } @Override public int getZoomInImageResource() { return R.drawable.zoom_in; } @Override public int getZoomOutImageResource() { return R.drawable.zoom_out; } @Override public int getPdfPasswordLayoutResource() { return R.layout.pdf_file_password; } @Override public int getPdfPageNumberResource() { return R.layout.dialog_pagenumber; } @Override public int getPdfPasswordEditField() { return R.id.etPassword; } @Override public int getPdfPasswordOkButton() { return R.id.btOK; } @Override public int getPdfPasswordExitButton() { return R.id.btExit; } @Override public int getPdfPageNumberEditField() { return R.id.pagenum_edit; } @Override protected void onStart() { super.onStart(); EasyTracker.getInstance().activityStart(this); // Add this method } @Override protected void onStop() { super.onStop(); EasyTracker.getInstance().activityStop(this); // Add this method } }
gpl-3.0
JAWolfe04/TerrafirmaPunk-Tweaks
src/main/java/com/JAWolfe/terrafirmapunktweaks/blocks/BlockTFPAltarBlock.java
3950
package com.JAWolfe.terrafirmapunktweaks.blocks; import com.JAWolfe.terrafirmapunktweaks.TerraFirmaPunkTweaks; import com.JAWolfe.terrafirmapunktweaks.reference.GUIs; import com.sirolf2009.necromancy.block.BlockAltarBlock; import net.minecraft.block.Block; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; public class BlockTFPAltarBlock extends BlockAltarBlock { public BlockTFPAltarBlock() { super(); } private TileEntity getTileEntity(World par1World, int x, int y, int z) { switch (par1World.getBlockMetadata(x, y, z)) { case 2: if (par1World.getBlock(x, y, z + 1) == this) return par1World.getTileEntity(x, y, z + 2); else return par1World.getTileEntity(x, y, z + 1); case 0: if (par1World.getBlock(x, y, z - 1) == this) return par1World.getTileEntity(x, y, z - 2); else return par1World.getTileEntity(x, y, z - 1); case 1: if (par1World.getBlock(x + 1, y, z) == this) return par1World.getTileEntity(x + 2, y, z); else return par1World.getTileEntity(x + 1, y, z); case 3: if (par1World.getBlock(x - 1, y, z) == this) return par1World.getTileEntity(x - 2, y, z); else return par1World.getTileEntity(x - 1, y, z); } return null; } @Override public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int idk, float what, float these, float are) { TileEntity tileEntity = getTileEntity(world, x, y, z); if (tileEntity == null || player.isSneaking()) return false; else { player.openGui(TerraFirmaPunkTweaks.instance, GUIs.TFPALTAR.ordinal(), world, tileEntity.xCoord, tileEntity.yCoord, tileEntity.zCoord); return true; } } @Override public void breakBlock(World world, int x, int y, int z, Block block, int meta) { Block altar = null; int metaAltar = 0, x1 = 0, y1 = 0, z1 = 0; switch (meta) { case 2: { if (world.getBlock(x, y, z + 1) == this) { x1 = x; y1 = y; z1 = z + 2; } else { x1 = x; y1 = y; z1 = z + 1; } break; } case 0: { if (world.getBlock(x, y, z - 1) == this) { x1 = x; y1 = y; z1 = z - 2; } else { x1 = x; y1 = y; z1 = z - 1; } break; } case 1: { if (world.getBlock(x + 1, y, z) == this) { x1 = x + 2; y1 = y; z1 = z; } else { x1 = x + 1; y1 = y; z1 = z; } break; } case 3: { if (world.getBlock(x - 1, y, z) == this) { x1 = x - 2; y1 = y; z1 = z; } else { x1 = x - 1; y1 = y; z1 = z; } break; } } altar = world.getBlock(x1, y1, z1); metaAltar = world.getBlockMetadata(x1, y1, z1); if(altar instanceof BlockTFPAltar) { ((BlockTFPAltar)altar).breakBlock(world, x1, y1, z1, altar, metaAltar); } } @Override public void onBlockDestroyedByPlayer(World world, int x, int y, int z, int meta) { } @Override public void registerBlockIcons(IIconRegister register) { this.blockIcon = Blocks.cobblestone.getIcon(0, 0); } }
gpl-3.0
colincarr/home
src/abcl/src/org/armedbear/lisp/mod.java
1937
/* * mod.java * * Copyright (C) 2004 Peter Graves * $Id: mod.java 12254 2009-11-06 20:07:54Z ehuelsmann $ * * 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. * * As a special exception, the copyright holders of this library give you * permission to link this library with independent modules to produce an * executable, regardless of the license terms of these independent * modules, and to copy and distribute the resulting executable under * terms of your choice, provided that you also meet, for each linked * independent module, the terms and conditions of the license of that * module. An independent module is a module which is not derived from * or based on this library. If you modify this library, you may extend * this exception to your version of the library, but you are not * obligated to do so. If you do not wish to do so, delete this * exception statement from your version. */ package org.armedbear.lisp; // ### mod number divisor public final class mod extends Primitive { private mod() { super("mod", "number divisor"); } @Override public LispObject execute(LispObject number, LispObject divisor) { return number.MOD(divisor); } private static final Primitive MOD = new mod(); }
gpl-3.0
malfact/EcoCraft
src/main/java/com/malfact/ecocraft/init/Recipes.java
95
package com.malfact.ecocraft.init; public class Recipes { public static void init(){ } }
gpl-3.0
guilherme-pereira/tassel4-poly
src/net/maizegenetics/stats/PCA/PrincipalComponents.java
4041
package net.maizegenetics.stats.PCA; import cern.colt.matrix.DoubleFactory1D; import cern.colt.matrix.DoubleFactory2D; import cern.colt.matrix.DoubleMatrix1D; import cern.colt.matrix.DoubleMatrix2D; import cern.colt.matrix.linalg.EigenvalueDecomposition; import cern.colt.matrix.linalg.SingularValueDecomposition; import cern.jet.math.Functions; public class PrincipalComponents { private DoubleMatrix2D genotypes; private SingularValueDecomposition svd; private boolean transposed = false; public static final int TYPE_CENTER = 1; public static final int TYPE_CENTER_AND_SCALE = 2; public static final int TYPE_NONE = 3; public PrincipalComponents(DoubleMatrix2D genotypes, int type) { this.genotypes = genotypes; if (type == TYPE_CENTER) centerGenotypesByMarker(); else if (type == TYPE_CENTER_AND_SCALE) centerAndScaleGenotypes(); int nrows = genotypes.rows(); int ncols = genotypes.columns(); if(nrows < ncols) { transposed = true; svd = new SingularValueDecomposition(genotypes.viewDice()); } else svd = new SingularValueDecomposition(genotypes); System.out.println("finished"); } public void centerGenotypesByMarker() { int nrows = genotypes.rows(); int ncols = genotypes.columns(); for (int c = 0; c < ncols; c++) { DoubleMatrix1D marker = genotypes.viewColumn(c); double mean = marker.zSum() / nrows; marker.assign(Functions.minus(mean)); } } public void centerAndScaleGenotypes() { int nrows = genotypes.rows(); int ncols = genotypes.columns(); for (int c = 0; c < ncols; c++) { DoubleMatrix1D marker = genotypes.viewColumn(c); double mean = marker.aggregate(Functions.plus, Functions.identity) / nrows; marker.assign(Functions.minus(mean)); double sd = marker.aggregate(Functions.plus, Functions.square); sd /= marker.size() - 1; sd = Math.sqrt(sd); marker.assign(Functions.div(sd)); } } public DoubleMatrix2D getUS(int n) { if (transposed) { int ncol = svd.getV().columns(); return svd.getV().viewPart(0, 0, ncol, n).zMult(svd.getS().viewPart(0, 0, n, n), null); } else { int ncol = svd.getU().columns(); return svd.getU().viewPart(0, 0, ncol, n).zMult(svd.getS().viewPart(0, 0, n, n), null); } } public DoubleMatrix2D getSV(int n) { if (transposed) { int ncol = svd.getU().columns(); return svd.getU().viewPart(0, 0, ncol, n).zMult(svd.getS().viewPart(0, 0, n, n), null).viewDice().copy(); } else { int ncol = svd.getV().columns(); return svd.getV().viewPart(0, 0, ncol, n).zMult(svd.getS().viewPart(0, 0, n, n), null).viewDice().copy(); } } public DoubleMatrix2D getU() { if (transposed) return svd.getV(); else return svd.getU(); } public DoubleMatrix2D getV() { if (transposed) return svd.getU(); else return svd.getV(); } public DoubleMatrix1D getSingularValues() { return DoubleFactory1D.dense.make(svd.getSingularValues()); } public DoubleMatrix2D getEigenVectors() { if (transposed) return svd.getU(); return svd.getV(); } public DoubleMatrix2D getPrincipalComponents() { if (transposed) return svd.getV().zMult(svd.getS(), null).viewDice().copy(); else return svd.getU().zMult(svd.getS(), null).viewDice().copy(); } public DoubleMatrix1D getEigenValues() { double[] s = svd.getSingularValues(); int n = s.length; int size=genotypes.rows(); double[] eigenvalues = new double[n]; for (int i = 0; i < n; i++) eigenvalues[i] = s[i] * s[i]/(size - 1); return DoubleFactory1D.dense.make(eigenvalues); } }
gpl-3.0
EnKrypt/BroGet
clients/android_app/BroGet/app/src/main/java/in/enkrypt/broget/MainActivity.java
487
package in.enkrypt.broget; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Intent intent = new Intent(this, BackgroundChecker.class); startService(intent); } }
gpl-3.0
bozhbo12/demo-spring-server
spring-game/src/main/java/com/spring/game/game/condtion/conds/YxupCond.java
1147
package com.snail.webgame.game.condtion.conds; import com.snail.webgame.game.common.ActionType; import com.snail.webgame.game.common.ErrorCode; import com.snail.webgame.game.condtion.AbstractConditionCheck; import com.snail.webgame.game.condtion.CheckDataChg; import com.snail.webgame.game.info.RoleInfo; /** * 副将升级 * * @author tangjq * */ public class YxupCond extends AbstractConditionCheck { private int num; public YxupCond() { } public YxupCond(int num) { this.num = num; } @Override public AbstractConditionCheck generate(String[] agrs) { if (agrs.length < 2) { return null; } int num = Integer.parseInt(agrs[1]); return new YxupCond(num); } @Override public int checkCond(RoleInfo roleInfo, int action, CheckDataChg questInProgress, int index, Object obj) { if (questInProgress == null || action != ActionType.action72.getType()) { return 0; } int value = (int) questInProgress.getSpecValue(index); value++; if (value >= num) { updateValue(index, questInProgress, num); return 1; } updateValue(index, questInProgress, value); return ErrorCode.ROLE_TASK_ERROR_2; } }
gpl-3.0
l2jserver2/l2jserver2
l2jserver2-gameserver/l2jserver2-gameserver-core/src/main/java/com/l2jserver/service/game/template/XMLTemplateServiceConfiguration.java
2045
/* * This file is part of l2jserver2 <l2jserver2.com>. * * l2jserver2 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. * * l2jserver2 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 l2jserver2. If not, see <http://www.gnu.org/licenses/>. */ package com.l2jserver.service.game.template; import com.l2jserver.service.configuration.XMLConfigurationService.ConfigurationXPath; import com.l2jserver.service.game.template.TemplateService.TemplateServiceConfiguration; /** * XML {@link TemplateService} configuration interface * * @author <a href="http://www.rogiel.com">Rogiel</a> */ public interface XMLTemplateServiceConfiguration extends TemplateServiceConfiguration { /** * @return the directory in which templates are stored */ @ConfigurationPropertyGetter(defaultValue = "template/") @ConfigurationXPath("templates/@root") String getTemplateDirectory(); /** * @param file * the directory in which templates are stored */ @ConfigurationPropertySetter @ConfigurationXPath("templates/@root") void setTemplateDirectory(String file); /** * @return true if service must validade template schemas before loading */ @ConfigurationPropertyGetter(defaultValue = "true") @ConfigurationXPath("schema/@validation") boolean isSchemaValidationEnabled(); /** * @param validation * true if service must validade template schemas before loadinsg */ @ConfigurationPropertySetter @ConfigurationXPath("schema/@validation") void setSchemaValidationEnabled(boolean validation); }
gpl-3.0
mihilranathunga/SEP_project
gen/cse/sep/mihil/bridgemanagementhelper/BuildConfig.java
178
/** Automatically generated file. DO NOT MODIFY */ package cse.sep.mihil.bridgemanagementhelper; public final class BuildConfig { public final static boolean DEBUG = true; }
gpl-3.0
Presage/Presage2
util/src/main/java/uk/ac/imperial/presage2/util/network/UnicastMessage.java
2618
/** * Copyright (C) 2011-2014 Sam Macbeth <sm1106 [at] imperial [dot] ac [dot] uk> * * This file is part of Presage2. * * Presage2 is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Presage2 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 Public License for more details. * * You should have received a copy of the GNU Lesser Public License * along with Presage2. If not, see <http://www.gnu.org/licenses/>. */ package uk.ac.imperial.presage2.util.network; import uk.ac.imperial.presage2.core.messaging.Performative; /** * <p> * This is a basic unicast message to be sent between agents. * </p> * * <p> * This message will only send a performative. If you want to send any * objects/data with the message you should extend this class. * </p> * * @author Sam Macbeth * */ public class UnicastMessage extends Message { /** * Intended recipient of this message. */ protected NetworkAddress to; /** * @param performative * @param from * @param timestamp * @param to */ public UnicastMessage(Performative performative, NetworkAddress from, NetworkAddress to, int timestamp) { super(performative, from, timestamp); this.to = to; } public UnicastMessage(Performative performative, NetworkAddress from, NetworkAddress to, int timestamp, Object data) { super(performative, from, timestamp, data); this.to = to; } public UnicastMessage(Performative performative, String type, int timestamp, NetworkAddress from, NetworkAddress to, Object data) { super(performative, type, timestamp, from, data); this.to = to; } public UnicastMessage(Performative performative, String type, int timestamp, NetworkAddress from, NetworkAddress to) { super(performative, type, timestamp, from); this.to = to; } /** * Gets the intended recipient of this message. * * @return UUID recipient. */ public NetworkAddress getTo() { return this.to; } /** * @see uk.ac.imperial.presage2.util.network.Message#toString() */ @Override public String toString() { return this.getClass().getSimpleName() + ": (Time: " + this.timestamp + ", from: " + this.from.toString() + ", to: " + this.to.toString() + ", perf: " + this.performative.toString() + ")"; } }
gpl-3.0
Novanoid/Tourney
Application/src/usspg31/tourney/model/PlayerScoreComperator.java
562
package usspg31.tourney.model; import java.util.Comparator; public class PlayerScoreComperator implements Comparator<PlayerScore> { @Override public int compare(PlayerScore o1, PlayerScore o2) { if (o1.getPlayer().getStartingNumber() .equals(o2.getPlayer().getStartingNumber())) { return 0; } else if (Integer.valueOf(o1.getPlayer().getStartingNumber()) > Integer .valueOf(o2.getPlayer().getStartingNumber())) { return 1; } else { return -1; } } }
gpl-3.0
malte0811/IndustrialWires
src/main/java/malte0811/industrialwires/blocks/INetGUI.java
954
/* * This file is part of Industrial Wires. * Copyright (C) 2016-2018 malte0811 * Industrial Wires 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. * Industrial Wires 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 Industrial Wires. If not, see <http://www.gnu.org/licenses/>. */ package malte0811.industrialwires.blocks; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.nbt.NBTTagCompound; public interface INetGUI { void onChange(NBTTagCompound nbt, EntityPlayer p); }
gpl-3.0
NiklasElze/ComNet
Code/src/main/java/model/Privilege.java
979
package model; import common.interfaces.JsonConvertable; import javax.json.Json; import javax.json.JsonObject; import javax.persistence.*; @Entity @Table(name = "tprivilege", schema = "", catalog = "comnetdb") public class Privilege implements JsonConvertable{ private int id; private String name; @Id @GeneratedValue(strategy= GenerationType.AUTO, generator="seq_gen_privilege") @SequenceGenerator(name="seq_gen_privilege", sequenceName="entity_seq_privilege") @Column(name = "Id") public int getId() { return id; } public void setId(int id) { this.id = id; } @Basic @Column(name = "Name") public String getName() { return name; } public void setName(String name) { this.name= name; } @Override public JsonObject toJson() { return Json.createObjectBuilder() .add("id", id) .add("name", name) .build(); } }
gpl-3.0
gitools/gitools
org.gitools.ui.app/src/main/java/org/gitools/ui/app/commands/DetectCategoriesCommand.java
2946
/* * #%L * org.gitools.ui.app * %% * Copyright (C) 2013 - 2014 Universitat Pompeu Fabra - Biomedical Genomics group * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-3.0.html>. * #L% */ package org.gitools.ui.app.commands; import org.gitools.api.analysis.IProgressMonitor; import org.gitools.api.matrix.AbstractMatrixFunction; import org.gitools.api.matrix.IMatrixIterable; import org.gitools.api.matrix.IMatrixPosition; import org.gitools.heatmap.Heatmap; import org.gitools.ui.core.commands.AbstractCommand; import org.gitools.ui.core.commands.Command; import java.util.ArrayList; import java.util.concurrent.CancellationException; import static com.google.common.collect.Lists.newArrayList; import static java.util.Collections.sort; public class DetectCategoriesCommand extends AbstractCommand { private Heatmap heatmap; private ArrayList<Double> categories; public DetectCategoriesCommand(Heatmap heatmap) { categories = new ArrayList<>(); this.heatmap = heatmap; } @Override public void execute(IProgressMonitor monitor) throws Command.CommandException { try { IMatrixPosition position = heatmap.newPosition(); IMatrixIterable it = position.iterate(heatmap.getLayers().getTopLayer(), heatmap.getRows(), heatmap.getColumns()) .monitor(monitor, "Detecting categories") .transform(new AbstractMatrixFunction<Double, Double>() { @Override public Double apply(Double v, IMatrixPosition position) { if (v != null && !categories.contains(v)) { categories.add((Double) v); if (categories.size() > 30) { throw new CancellationException("Too many categories"); } } return null; } }); ArrayList dummyList = newArrayList(it); } catch (CancellationException e) { categories.clear(); throw new CancellationException(e.getMessage()); } sort(categories); } public ArrayList<Double> getCategories() { return categories; } }
gpl-3.0
golddragon007/scrum-logfilereader
maven/src/main/java/util/Utils.java
258
package util; public class Utils { public static String removeLastCharacter(String word) { return word.substring(0, word.length() - 1); } public static String removeLastThreeCharacter(String word) { return word.substring(0, word.length() - 3); } }
gpl-3.0
transwarpio/rapidminer
rapidMiner/rapidminer-studio-core/src/main/java/com/rapidminer/studio/io/gui/internal/DataWizardEventType.java
2008
/** * Copyright (C) 2001-2016 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * 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 com.rapidminer.studio.io.gui.internal; /** * Event types that can be logged via * {@link DataImportWizardUtils#logStats(DataWizardEventType, String)} * * @since 7.0.0 * @author Nils Woehler, Marcel Michel */ public enum DataWizardEventType { /** main data source selected */ DATASOURCE_SELECTED, /** new local file data source selected */ FILE_DATASOURCE_SELECTED, /** when changing the file type in the file location step */ FILE_TYPE_CHANGED, /** entering first step */ STARTING, /** switching to next step */ NEXT_STEP, /** switching to previous step */ PREVIOUS_STEP, /** closing the wizard */ CLOSED, /** searching for data sources in the overview step */ SEARCH_TYPE, /** when clicking on the handle errors as missing values check box */ ERROR_HANDLING_CHANGED, /** when changing the date format */ DATE_FORMAT_CHANGED, /** when changing a column type */ COLUMN_TYPE_CHANGED, /** when changing the header row state in the excel sheet selection view */ EXCEL_HEADER_ROW_STATE, /** when changing the header row state in the CSV sheet selection view */ CSV_HEADER_ROW_STATE, /** when changing the column separator */ CSV_SEPARATOR_CHANGED, }
gpl-3.0
epam/Wilma
wilma-application/modules/wilma-webapp/src/test/java/com/epam/wilma/webapp/config/servlet/stub/upload/ExternalSequenceHandlerUploadServletTest.java
4784
package com.epam.wilma.webapp.config.servlet.stub.upload; /*========================================================================== Copyright since 2013, EPAM Systems This file is part of Wilma. Wilma 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. Wilma 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 Wilma. If not, see <http://www.gnu.org/licenses/>. ===========================================================================*/ import com.epam.wilma.domain.stubconfig.StubResourcePathProvider; import com.epam.wilma.webapp.config.servlet.stub.upload.helper.FileWriter; import com.epam.wilma.webapp.domain.exception.CannotUploadExternalResourceException; import org.junit.Before; import org.junit.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; import org.mockito.internal.util.reflection.Whitebox; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import static org.mockito.BDDMockito.given; import static org.mockito.BDDMockito.willThrow; import static org.mockito.Mockito.verify; /** * Unit test for {@link ExternalSequenceHandlerUploadServlet}. * * @author Adam_Csaba_Kiraly */ public class ExternalSequenceHandlerUploadServletTest { private static final String FILE_NAME = "resource file"; private static final String EXCEPTION_MESSAGE = "Could not upload external sequence handler: "; private static final String PATH = "path"; @Mock private StubResourcePathProvider stubResourcePathProvider; @Mock private HttpServletRequest request; @Mock private HttpServletResponse response; @Mock private ServletInputStream inputStream; @Mock private FileWriter fileWriter; @Mock private PrintWriter writer; @InjectMocks private ExternalSequenceHandlerUploadServlet underTest; @Before public void setUp() throws IOException { MockitoAnnotations.initMocks(this); Whitebox.setInternalState(underTest, "stubResourcePathProvider", stubResourcePathProvider); Whitebox.setInternalState(underTest, "fileWriter", fileWriter); given(request.getInputStream()).willReturn(inputStream); given(stubResourcePathProvider.getSequenceHandlerPathAsString()).willReturn(PATH); } @Test public void testDoGetShouldCallFileWriter() throws ServletException, IOException { //GIVEN given(request.getParameter("fileName")).willReturn(FILE_NAME); //WHEN underTest.doGet(request, response); //THEN verify(fileWriter).write(inputStream, PATH + "/" + FILE_NAME, EXCEPTION_MESSAGE); } @Test public void testDoGetWhenExceptionShouldWriteErrorToResponse() throws ServletException, IOException { //GIVEN given(request.getParameter("fileName")).willReturn(FILE_NAME); given(response.getWriter()).willReturn(writer); willThrow(new CannotUploadExternalResourceException(EXCEPTION_MESSAGE, new Throwable())).given(fileWriter).write(inputStream, PATH + "/" + FILE_NAME, EXCEPTION_MESSAGE); //WHEN underTest.doGet(request, response); //THEN verify(writer).write(Mockito.anyString()); } @Test public void testDoGetWhenFileNameIsNullShouldWriteErrorToResponse() throws ServletException, IOException { //GIVEN given(request.getParameter("fileName")).willReturn(null); given(response.getWriter()).willReturn(writer); //WHEN underTest.doGet(request, response); //THEN verify(writer).write("Please give a name to the sequence handler! e.g.:.../sequencehandler?fileName=ExternalSequenceHandler.class"); } @Test public void testDoPostShouldCallDoGet() throws ServletException, IOException { //GIVEN given(request.getParameter("fileName")).willReturn(FILE_NAME); //WHEN underTest.doPost(request, response); //THEN verify(fileWriter).write(inputStream, PATH + "/" + FILE_NAME, EXCEPTION_MESSAGE); } }
gpl-3.0
iterate-ch/cyberduck
core/src/main/java/ch/cyberduck/ui/comparator/BrowserComparator.java
2710
package ch.cyberduck.ui.comparator; /* * Copyright (c) 2005 David Kocher. All rights reserved. * http://cyberduck.ch/ * * 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. * * Bug fixes, suggestions and comments should be sent to: * dkocher@cyberduck.ch */ import ch.cyberduck.core.Path; import java.io.Serializable; import java.util.Comparator; import java.util.Objects; /** * The base class for comparators used to sort by column type in the browser */ public abstract class BrowserComparator implements Comparator<Path>, Serializable { private static final long serialVersionUID = -5905031111032653689L; protected final boolean ascending; private final BrowserComparator fallback; /** * @param ascending The items should be sorted in a ascending manner. * Usually this means lower numbers first or natural language sorting * for alphabetic comparators * @param fallback Second level comparator */ public BrowserComparator(final boolean ascending, final BrowserComparator fallback) { this.ascending = ascending; this.fallback = fallback; } public boolean isAscending() { return this.ascending; } @Override public boolean equals(final Object o) { if(this == o) { return true; } if(o == null || getClass() != o.getClass()) { return false; } final BrowserComparator that = (BrowserComparator) o; if(ascending != that.ascending) { return false; } if(!Objects.equals(fallback, that.fallback)) { return false; } return true; } @Override public int hashCode() { int result = (ascending ? 1 : 0); result = 31 * result + (fallback != null ? fallback.hashCode() : 0); return result; } @Override public int compare(final Path p1, final Path p2) { int result = this.compareFirst(p1, p2); if(0 == result) { if(null != fallback) { return fallback.compareFirst(p1, p2); } } return result; } protected abstract int compareFirst(final Path p1, final Path p2); }
gpl-3.0
GitHubDroid/geodroid_master_update
geodroid.app/src/eu/hydrologis/geopaparazzi/util/VerticalProgressBar.java
19723
///* // * Geopaparazzi - Digital field mapping on Android based devices // * Copyright (C) 2010 HydroloGIS (www.hydrologis.com) // * // * This program is free software: you can redistribute it and/or modify // * it under the terms of the GNU General Public License as published by // * the Free Software Foundation, either version 3 of the License, or // * (at your option) any later version. // * // * This program is distributed in the hope that it will be useful, // * but WITHOUT ANY WARRANTY; without even the implied warranty of // * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // * GNU General Public License for more details. // * // * You should have received a copy of the GNU General Public License // * along with this program. If not, see <http://www.gnu.org/licenses/>. // */ //package eu.hydrologis.geopaparazzi.util; // //import android.content.Context; //import android.content.res.TypedArray; //import android.graphics.Bitmap; //import android.graphics.Canvas; //import android.graphics.Rect; //import android.graphics.drawable.BitmapDrawable; //import android.graphics.drawable.ClipDrawable; //import android.graphics.drawable.Drawable; //import android.graphics.drawable.LayerDrawable; //import android.graphics.drawable.ShapeDrawable; //import android.graphics.drawable.StateListDrawable; //import android.graphics.drawable.shapes.RoundRectShape; //import android.graphics.drawable.shapes.Shape; //import android.os.Parcel; //import android.os.Parcelable; //import android.util.AttributeSet; //import android.view.Gravity; //import android.view.View; //import android.view.ViewDebug; //import android.view.ViewParent; //import android.widget.ProgressBar; //import android.widget.RemoteViews.RemoteView; //import eu.hydrologis.geopaparazzi.R; // ///** // * @author http://code.google.com/p/ardroid/ // */ //@RemoteView //public class VerticalProgressBar extends View { // private static final int MAX_LEVEL = 10000; // // int mMinWidth; // int mMaxWidth; // int mMinHeight; // int mMaxHeight; // // private int mProgress; // private int mSecondaryProgress; // private int mMax; // // private Drawable mProgressDrawable; // private Drawable mCurrentDrawable; // Bitmap mSampleTile; // private boolean mNoInvalidate; // private RefreshProgressRunnable mRefreshProgressRunnable; // private long mUiThreadId; // // private boolean mInDrawing; // // protected int mScrollX; // protected int mScrollY; // protected int mPaddingLeft; // protected int mPaddingRight; // protected int mPaddingTop; // protected int mPaddingBottom; // protected ViewParent mParent; // // /** // * Create a new progress bar with range 0...100 and initial progress of 0. // * // * @param context the application environment // */ // public VerticalProgressBar( Context context ) { // this(context, null); // } // // /** // * @param context the context to use. // * @param attrs attributes. // */ // public VerticalProgressBar( Context context, AttributeSet attrs ) { // this(context, attrs, android.R.attr.progressBarStyle); // } // // /** // * @param context if something goes wrong. // * @param attrs attributes. // * @param defStyle defstyle. // */ // public VerticalProgressBar( Context context, AttributeSet attrs, int defStyle ) { // super(context, attrs, defStyle); // mUiThreadId = Thread.currentThread().getId(); // initProgressBar(); // // TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.ProgressBar, defStyle, 0); // // mNoInvalidate = true; // // Drawable drawable = a.getDrawable(R.styleable.ProgressBar_android_progressDrawable); // if (drawable != null) { // drawable = tileify(drawable, false); // // Calling this method can set mMaxHeight, make sure the corresponding // // XML attribute for mMaxHeight is read after calling this method // setProgressDrawable(drawable); // } // // mMinWidth = a.getDimensionPixelSize(R.styleable.ProgressBar_android_minWidth, mMinWidth); // mMaxWidth = a.getDimensionPixelSize(R.styleable.ProgressBar_android_maxWidth, mMaxWidth); // mMinHeight = a.getDimensionPixelSize(R.styleable.ProgressBar_android_minHeight, mMinHeight); // mMaxHeight = a.getDimensionPixelSize(R.styleable.ProgressBar_android_maxHeight, mMaxHeight); // // setMax(a.getInt(R.styleable.ProgressBar_android_max, mMax)); // // setProgress(a.getInt(R.styleable.ProgressBar_android_progress, mProgress)); // // setSecondaryProgress(a.getInt(R.styleable.ProgressBar_android_secondaryProgress, mSecondaryProgress)); // // mNoInvalidate = false; // // a.recycle(); // } // // /** // * Converts a drawable to a tiled version of itself. It will recursively // * traverse layer and state list drawables. // */ // private Drawable tileify( Drawable drawable, boolean clip ) { // // if (drawable instanceof LayerDrawable) { // LayerDrawable background = (LayerDrawable) drawable; // final int N = background.getNumberOfLayers(); // Drawable[] outDrawables = new Drawable[N]; // // for( int i = 0; i < N; i++ ) { // int id = background.getId(i); // outDrawables[i] = tileify(background.getDrawable(i), // (id == android.R.id.progress || id == android.R.id.secondaryProgress)); // } // // LayerDrawable newBg = new LayerDrawable(outDrawables); // // for( int i = 0; i < N; i++ ) { // newBg.setId(i, background.getId(i)); // } // // return newBg; // // } else if (drawable instanceof StateListDrawable) { // // StateListDrawable in = (StateListDrawable) drawable; // StateListDrawable out = new StateListDrawable(); // /*int numStates = in.getStateCount(); // for (int i = 0; i < numStates; i++) { // out.addState(in.getStateSet(i), tileify(in.getStateDrawable(i), clip)); // }*/ // return out; // // } else if (drawable instanceof BitmapDrawable) { // final Bitmap tileBitmap = ((BitmapDrawable) drawable).getBitmap(); // if (mSampleTile == null) { // mSampleTile = tileBitmap; // } // // final ShapeDrawable shapeDrawable = new ShapeDrawable(getDrawableShape()); // return (clip) ? new ClipDrawable(shapeDrawable, Gravity.LEFT, ClipDrawable.HORIZONTAL) : shapeDrawable; // } // // return drawable; // } // // Shape getDrawableShape() { // final float[] roundedCorners = new float[]{5, 5, 5, 5, 5, 5, 5, 5}; // return new RoundRectShape(roundedCorners, null, null); // } // // /** // * <p> // * Initialize the progress bar's default values: // * </p> // * <ul> // * <li>progress = 0</li> // * <li>max = 100</li> // * </ul> // */ // private void initProgressBar() { // mMax = 100; // mProgress = 0; // mSecondaryProgress = 0; // mMinWidth = 24; // mMaxWidth = 48; // mMinHeight = 24; // mMaxHeight = 48; // } // // /** // * <p>Get the drawable used to draw the progress bar in // * progress mode.</p> // * // * @return a {@link android.graphics.drawable.Drawable} instance // * // * @see #setProgressDrawable(android.graphics.drawable.Drawable) // */ // public Drawable getProgressDrawable() { // return mProgressDrawable; // } // // /** // * <p>Define the drawable used to draw the progress bar in // * progress mode.</p> // * // * @param d the new drawable // * // * @see #getProgressDrawable() // */ // public void setProgressDrawable( Drawable d ) { // if (d != null) { // d.setCallback(this); // // Make sure the ProgressBar is always tall enough // int drawableHeight = d.getMinimumHeight(); // if (mMaxHeight < drawableHeight) { // mMaxHeight = drawableHeight; // requestLayout(); // } // } // mProgressDrawable = d; // mCurrentDrawable = d; // postInvalidate(); // } // // /** // * @return The drawable currently used to draw the progress bar // */ // Drawable getCurrentDrawable() { // return mCurrentDrawable; // } // // @Override // protected boolean verifyDrawable( Drawable who ) { // return who == mProgressDrawable || super.verifyDrawable(who); // } // // @Override // public void postInvalidate() { // if (!mNoInvalidate) { // super.postInvalidate(); // } // } // // private class RefreshProgressRunnable implements Runnable { // // private int mId; // private int mProgress; // private boolean mFromUser; // // RefreshProgressRunnable( int id, int progress, boolean fromUser ) { // mId = id; // mProgress = progress; // mFromUser = fromUser; // } // // public void run() { // doRefreshProgress(mId, mProgress, mFromUser); // // Put ourselves back in the cache when we are done // mRefreshProgressRunnable = this; // } // // public void setup( int id, int progress, boolean fromUser ) { // mId = id; // mProgress = progress; // mFromUser = fromUser; // } // // } // // private synchronized void doRefreshProgress( int id, int progress, boolean fromUser ) { // float scale = mMax > 0 ? (float) progress / (float) mMax : 0; // final Drawable d = mCurrentDrawable; // if (d != null) { // Drawable progressDrawable = null; // // if (d instanceof LayerDrawable) { // progressDrawable = ((LayerDrawable) d).findDrawableByLayerId(id); // } // // final int level = (int) (scale * MAX_LEVEL); // (progressDrawable != null ? progressDrawable : d).setLevel(level); // } else { // invalidate(); // } // // if (id == android.R.id.progress) { // onProgressRefresh(scale, fromUser); // } // } // // void onProgressRefresh( float scale, boolean fromUser ) { // } // // private synchronized void refreshProgress( int id, int progress, boolean fromUser ) { // if (mUiThreadId == Thread.currentThread().getId()) { // doRefreshProgress(id, progress, fromUser); // } else { // RefreshProgressRunnable r; // if (mRefreshProgressRunnable != null) { // // Use cached RefreshProgressRunnable if available // r = mRefreshProgressRunnable; // // Uncache it // mRefreshProgressRunnable = null; // r.setup(id, progress, fromUser); // } else { // // Make a new one // r = new RefreshProgressRunnable(id, progress, fromUser); // } // post(r); // } // } // // /** // * <p>Set the current progress to the specified value.</p> // * // * @param progress the new progress, between 0 and {@link #getMax()} // * // * @see #getProgress() // * @see #incrementProgressBy(int) // */ // public synchronized void setProgress( int progress ) { // setProgress(progress, false); // } // // synchronized void setProgress( int progress, boolean fromUser ) { // if (progress < 0) { // progress = 0; // } // // if (progress > mMax) { // progress = mMax; // } // // if (progress != mProgress) { // mProgress = progress; // refreshProgress(android.R.id.progress, mProgress, fromUser); // } // } // // /** // * <p> // * Set the current secondary progress to the specified value. // * </p> // * // * @param secondaryProgress the new secondary progress, between 0 and {@link #getMax()} // * @see #getSecondaryProgress() // * @see #incrementSecondaryProgressBy(int) // */ // public synchronized void setSecondaryProgress( int secondaryProgress ) { // if (secondaryProgress < 0) { // secondaryProgress = 0; // } // // if (secondaryProgress > mMax) { // secondaryProgress = mMax; // } // // if (secondaryProgress != mSecondaryProgress) { // mSecondaryProgress = secondaryProgress; // refreshProgress(android.R.id.secondaryProgress, mSecondaryProgress, false); // } // } // // /** // * <p>Get the progress bar's current level of progress.</p> // * // * @return the current progress, between 0 and {@link #getMax()} // * // * @see #setProgress(int) // * @see #setMax(int) // * @see #getMax() // */ // @ViewDebug.ExportedProperty // public synchronized int getProgress() { // return mProgress; // } // // /** // * <p>Get the progress bar's current level of secondary progress.</p> // * // * @return the current secondary progress, between 0 and {@link #getMax()} // * // * @see #setSecondaryProgress(int) // * @see #setMax(int) // * @see #getMax() // */ // @ViewDebug.ExportedProperty // public synchronized int getSecondaryProgress() { // return mSecondaryProgress; // } // // /** // * <p>Return the upper limit of this progress bar's range.</p> // * // * @return a positive integer // * // * @see #setMax(int) // * @see #getProgress() // * @see #getSecondaryProgress() // */ // @ViewDebug.ExportedProperty // public synchronized int getMax() { // return mMax; // } // // /** // * <p>Set the range of the progress bar to 0...<tt>max</tt>.</p> // * // * @param max the upper range of this progress bar // * // * @see #getMax() // * @see #setProgress(int) // * @see #setSecondaryProgress(int) // */ // public synchronized void setMax( int max ) { // if (max < 0) { // max = 0; // } // if (max != mMax) { // mMax = max; // postInvalidate(); // // if (mProgress > max) { // mProgress = max; // refreshProgress(android.R.id.progress, mProgress, false); // } // } // } // // /** // * <p>Increase the progress bar's progress by the specified amount.</p> // * // * @param diff the amount by which the progress must be increased // * // * @see #setProgress(int) // */ // public synchronized final void incrementProgressBy( int diff ) { // setProgress(mProgress + diff); // } // // /** // * <p>Increase the progress bar's secondary progress by the specified amount.</p> // * // * @param diff the amount by which the secondary progress must be increased // * // * @see #setSecondaryProgress(int) // */ // public synchronized final void incrementSecondaryProgressBy( int diff ) { // setSecondaryProgress(mSecondaryProgress + diff); // } // // @Override // public void setVisibility( int v ) { // if (getVisibility() != v) { // super.setVisibility(v); // } // } // // @Override // public void invalidateDrawable( Drawable dr ) { // if (!mInDrawing) { // if (verifyDrawable(dr)) { // final Rect dirty = dr.getBounds(); // final int scrollX = mScrollX + mPaddingLeft; // final int scrollY = mScrollY + mPaddingTop; // // invalidate(dirty.left + scrollX, dirty.top + scrollY, dirty.right + scrollX, dirty.bottom + scrollY); // } else { // super.invalidateDrawable(dr); // } // } // } // // @Override // protected void onSizeChanged( int w, int h, int oldw, int oldh ) { // // onDraw will translate the canvas so we draw starting at 0,0 // int right = w - mPaddingRight - mPaddingLeft; // int bottom = h - mPaddingBottom - mPaddingTop; // // if (mProgressDrawable != null) { // mProgressDrawable.setBounds(0, 0, right, bottom); // } // } // // @Override // protected synchronized void onDraw( Canvas canvas ) { // super.onDraw(canvas); // // Drawable d = mCurrentDrawable; // if (d != null) { // // Translate canvas so a indeterminate circular progress bar with padding // // rotates properly in its animation // canvas.save(); // canvas.translate(mPaddingLeft, mPaddingTop); // d.draw(canvas); // canvas.restore(); // } // } // // @Override // protected synchronized void onMeasure( int widthMeasureSpec, int heightMeasureSpec ) { // Drawable d = mCurrentDrawable; // // int dw = 0; // int dh = 0; // if (d != null) { // dw = Math.max(mMinWidth, Math.min(mMaxWidth, d.getIntrinsicWidth())); // dh = Math.max(mMinHeight, Math.min(mMaxHeight, d.getIntrinsicHeight())); // } // dw += mPaddingLeft + mPaddingRight; // dh += mPaddingTop + mPaddingBottom; // // setMeasuredDimension(resolveSize(dw, widthMeasureSpec), resolveSize(dh, heightMeasureSpec)); // } // // @Override // protected void drawableStateChanged() { // super.drawableStateChanged(); // // int[] state = getDrawableState(); // // if (mProgressDrawable != null && mProgressDrawable.isStateful()) { // mProgressDrawable.setState(state); // } // } // // static class SavedState extends BaseSavedState { // int progress; // int secondaryProgress; // // /** // * Constructor called from {@link ProgressBar#onSaveInstanceState()} // */ // SavedState( Parcelable superState ) { // super(superState); // } // // /** // * Constructor called from {@link #CREATOR} // */ // private SavedState( Parcel in ) { // super(in); // progress = in.readInt(); // secondaryProgress = in.readInt(); // } // // @Override // public void writeToParcel( Parcel out, int flags ) { // super.writeToParcel(out, flags); // out.writeInt(progress); // out.writeInt(secondaryProgress); // } // // public static final Parcelable.Creator<SavedState> CREATOR = new Parcelable.Creator<SavedState>(){ // public SavedState createFromParcel( Parcel in ) { // return new SavedState(in); // } // // public SavedState[] newArray( int size ) { // return new SavedState[size]; // } // }; // } // // @Override // public Parcelable onSaveInstanceState() { // // Force our ancestor class to save its state // Parcelable superState = super.onSaveInstanceState(); // SavedState ss = new SavedState(superState); // // ss.progress = mProgress; // ss.secondaryProgress = mSecondaryProgress; // // return ss; // } // // @Override // public void onRestoreInstanceState( Parcelable state ) { // SavedState ss = (SavedState) state; // super.onRestoreInstanceState(ss.getSuperState()); // // setProgress(ss.progress); // setSecondaryProgress(ss.secondaryProgress); // } // }
gpl-3.0
veresdavid/deik-tdk-2017
visualizer/src/main/java/hu/david/veres/graph/thread/ProcessThread.java
10115
package hu.david.veres.graph.thread; import exceptions.InvalidVariableException; import exceptions.TypeMismatchException; import hu.david.veres.graph.dto.ProcessDTO; import hu.david.veres.graph.form.ProblemForm; import hu.david.veres.graph.form.VariableData; import hu.david.veres.graph.generator.ResultGenerator; import hu.david.veres.graph.model.Result; import hu.david.veres.graph.service.ProcessService; import hu.david.veres.graph.service.StorageService; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import main.SolutionManager; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import java.io.File; import java.io.IOException; import java.util.*; import java.util.stream.Collectors; @Component @Scope("prototype") @Getter @Setter @NoArgsConstructor public class ProcessThread implements Runnable { @Value("${file.uploaded.search.algorithm.files.folder}") private String uploadedSearchAlgorithmFilesFolderName; private static final String ERROR_MESSAGE_SERVER_SIDE = "Server-side error! Please try again!"; private String processIdentifier; private SolutionManager solutionManager; private ProblemForm problemForm; private int algorithmIndex; private boolean custom; @Autowired private ProcessService processService; @Autowired private StorageService storageService; @Override public void run() { // SOLVE PROBLEM // Generate and get solution output file name String absoluteFileName = ""; if(custom){ try { absoluteFileName = solutionManager.doUserSolutionSearcher(getJavaFileLocations(problemForm.getCustomSearchAlgorithms().get(algorithmIndex).getFiles()), Collections.emptyList(), problemForm.getCustomSearchAlgorithms().get(algorithmIndex).isUsesHeuristic(), problemForm.getHeuristic(), convertInputToSet(problemForm.getVariablesInHeuristicFunction()), generateVariablesArray(problemForm.getCustomSearchAlgorithms().get(algorithmIndex).getVariables()), problemForm.isDoTree()); } catch (Exception e) { finishAndUpdateProcess(processIdentifier, true, ERROR_MESSAGE_SERVER_SIDE, null); e.printStackTrace(); return; } }else { switch (problemForm.getAlgorithms().get(algorithmIndex)) { case "BackTrackSimple": absoluteFileName = solutionManager.doBackTrackSimple(problemForm.isDoTree()); break; case "BackTrackCircle": absoluteFileName = solutionManager.doBackTrackCircle(problemForm.isDoTree()); break; case "BackTrackPathLengthLimitation": absoluteFileName = solutionManager.doBackTrackPathLengthLimitation(problemForm.isDoTree(), problemForm.getBackTrackPathLengthLimitationLimit()); break; case "BackTrackOptimal": absoluteFileName = solutionManager.doBackTrackOptimal(problemForm.isDoTree(), problemForm.getBackTrackOptimalLimit()); break; case "BreadthFirst": absoluteFileName = solutionManager.doBreadthFirst(problemForm.isDoTree()); break; case "DepthFirst": absoluteFileName = solutionManager.doDepthFirst(problemForm.isDoTree()); break; case "Optimal": absoluteFileName = solutionManager.doOptimal(problemForm.isDoTree()); break; case "BestFirst": try { absoluteFileName = solutionManager.doBestFirst(problemForm.getHeuristic(), convertInputToSet(problemForm.getVariablesInHeuristicFunction()), problemForm.isDoTree()); } catch (ClassNotFoundException e) { finishAndUpdateProcess(processIdentifier, true, ERROR_MESSAGE_SERVER_SIDE, null); e.printStackTrace(); return; } catch (NoSuchFieldException e) { finishAndUpdateProcess(processIdentifier, true, ERROR_MESSAGE_SERVER_SIDE, null); e.printStackTrace(); return; } catch (IllegalAccessException e) { finishAndUpdateProcess(processIdentifier, true, ERROR_MESSAGE_SERVER_SIDE, null); e.printStackTrace(); return; } catch (InstantiationException e) { finishAndUpdateProcess(processIdentifier, true, ERROR_MESSAGE_SERVER_SIDE, null); e.printStackTrace(); return; } catch (InvalidVariableException e) { finishAndUpdateProcess(processIdentifier, true, e.getMessage(), null); e.printStackTrace(); return; } catch (TypeMismatchException e) { finishAndUpdateProcess(processIdentifier, true, e.getMessage(), null); e.printStackTrace(); return; } break; case "A": try { absoluteFileName = solutionManager.doA(problemForm.getHeuristic(), convertInputToSet(problemForm.getVariablesInHeuristicFunction()), problemForm.isDoTree()); } catch (ClassNotFoundException e) { finishAndUpdateProcess(processIdentifier, true, ERROR_MESSAGE_SERVER_SIDE, null); e.printStackTrace(); return; } catch (NoSuchFieldException e) { finishAndUpdateProcess(processIdentifier, true, ERROR_MESSAGE_SERVER_SIDE, null); e.printStackTrace(); return; } catch (IllegalAccessException e) { finishAndUpdateProcess(processIdentifier, true, ERROR_MESSAGE_SERVER_SIDE, null); e.printStackTrace(); return; } catch (InstantiationException e) { finishAndUpdateProcess(processIdentifier, true, ERROR_MESSAGE_SERVER_SIDE, null); e.printStackTrace(); return; } catch (InvalidVariableException e) { finishAndUpdateProcess(processIdentifier, true, e.getMessage(), null); e.printStackTrace(); return; } catch (TypeMismatchException e) { finishAndUpdateProcess(processIdentifier, true, e.getMessage(), null); e.printStackTrace(); return; } break; } } // GENERATE JSON // Check if file exists File file = new File(absoluteFileName); if (!file.exists()) { finishAndUpdateProcess(processIdentifier, true, ERROR_MESSAGE_SERVER_SIDE, null); return; } // Generate result Result result; try { ResultGenerator resultGenerator = new ResultGenerator(); result = resultGenerator.generate(file); } catch (IOException e) { finishAndUpdateProcess(processIdentifier, true, ERROR_MESSAGE_SERVER_SIDE, null); e.printStackTrace(); return; } // Store JSON file try { storageService.storeResultInJsonFile(result, processIdentifier); } catch (IOException e) { finishAndUpdateProcess(processIdentifier, true, ERROR_MESSAGE_SERVER_SIDE, null); e.printStackTrace(); return; } // Update database String solutionFileName = file.getName().substring(0, file.getName().indexOf('.')); finishAndUpdateProcess(processIdentifier, false, null, solutionFileName); } private void finishAndUpdateProcess(String processIdentifier, boolean error, String errorMessage, String solutionFileName) { ProcessDTO processDTO = processService.getProcessByIdentifier(processIdentifier); processDTO.setDone(true); processDTO.setError(error); processDTO.setErrorMessage(errorMessage); processDTO.setSolutionFileName(solutionFileName); processService.save(processDTO); } private Set<String> convertInputToSet(String input) { if (input.isEmpty()) { return new HashSet<>(); } String[] parts = input.split(", "); return Arrays.stream(parts).collect(Collectors.toSet()); } private List<String> getJavaFileLocations(List<String> fileNames){ List<String> javaFileLocations = new ArrayList<>(); for(String fileName : fileNames){ javaFileLocations.add(uploadedSearchAlgorithmFilesFolderName + File.separator + fileName); } return javaFileLocations; } private Object[] generateVariablesArray(List<VariableData> variableDatas){ Object[] variables = new Object[variableDatas.size()]; for(int i=0; i<variableDatas.size(); i++){ switch (variableDatas.get(i).getType()){ case "int": variables[i] = Integer.parseInt(variableDatas.get(i).getValue()); break; case "double": variables[i] = Double.parseDouble(variableDatas.get(i).getValue()); break; case "string": variables[i] = variableDatas.get(i).getValue(); break; case "boolean": variables[i] = Boolean.parseBoolean(variableDatas.get(i).getValue()); break; } } return variables; } }
gpl-3.0
WestonReed/CSGameClient
src/russianroulette/Resizer.java
2919
package russianroulette; import java.awt.*; import java.awt.image.BufferedImage; /** * @author maxpat21, onContentStop */ public enum Resizer { NEAREST_NEIGHBOR { @Override public BufferedImage resize(BufferedImage source, int width, int height) { return commonResize(source, width, height, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); } }, BILINEAR { @Override public BufferedImage resize(BufferedImage source, int width, int height) { return commonResize(source, width, height, RenderingHints.VALUE_INTERPOLATION_BILINEAR); } }, BICUBIC { @Override public BufferedImage resize(BufferedImage source, int width, int height) { return commonResize(source, width, height, RenderingHints.VALUE_INTERPOLATION_BICUBIC); } }, PROGRESSIVE_BILINEAR { @Override public BufferedImage resize(BufferedImage source, int width, int height) { return progressiveResize(source, width, height, RenderingHints.VALUE_INTERPOLATION_BILINEAR); } }, PROGRESSIVE_BICUBIC { @Override public BufferedImage resize(BufferedImage source, int width, int height) { return progressiveResize(source, width, height, RenderingHints.VALUE_INTERPOLATION_BICUBIC); } }, AVERAGE { @Override public BufferedImage resize(BufferedImage source, int width, int height) { Image img2 = source.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING); BufferedImage img = new BufferedImage(width, height, source.getType()); Graphics2D g = img.createGraphics(); try { g.drawImage(img2, 0, 0, width, height, null); } finally { g.dispose(); } return img; } }; public abstract BufferedImage resize(BufferedImage source, int width, int height); private static BufferedImage progressiveResize(BufferedImage source, int width, int height, Object hint) { int w = Math.max(source.getWidth() / 2, width); int h = Math.max(source.getHeight() / 2, height); BufferedImage img = commonResize(source, w, h, hint); while (w != width || h != height) { BufferedImage prev = img; w = Math.max(w / 2, width); h = Math.max(h / 2, height); img = commonResize(prev, w, h, hint); prev.flush(); } return img; } private static BufferedImage commonResize(BufferedImage source, int width, int height, Object hint) { BufferedImage img = new BufferedImage(width, height, source.getType()); Graphics2D g = img.createGraphics(); try { g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, hint); g.drawImage(source, 0, 0, width, height, null); } finally { g.dispose(); } return img; } }
gpl-3.0
oswetto/LoboEvolution
LoboPDF/src/main/java/org/loboevolution/pdfview/font/cid/PDFCMap.java
3964
/* * Copyright 2004 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.loboevolution.pdfview.font.cid; import java.io.IOException; import java.util.HashMap; import org.loboevolution.pdfview.PDFDebugger; import org.loboevolution.pdfview.PDFObject; /** * A CMap maps from a character in a composite font to a font/glyph number * pair in a CID font. * * Author jkaplan * */ public abstract class PDFCMap { /** * A cache of known CMaps by name */ private static HashMap<String, PDFCMap> cache; /** * Creates a new instance of CMap */ protected PDFCMap() {} /** * Get a CMap, given a PDF object containing one of the following: * a string name of a known CMap * a stream containing a CMap definition * * @param map a {@link org.loboevolution.pdfview.PDFObject} object. * @return a {@link org.loboevolution.pdfview.font.cid.PDFCMap} object. * @throws java.io.IOException if any. */ public static PDFCMap getCMap(PDFObject map) throws IOException { if (map.getType() == PDFObject.NAME) { return getCMap(map.getStringValue()); } else if (map.getType() == PDFObject.STREAM) { return parseCMap(map); } else { throw new IOException("CMap type not Name or Stream!"); } } /** * Get a CMap, given a string name * * @param mapName a {@link java.lang.String} object. * @return a {@link org.loboevolution.pdfview.font.cid.PDFCMap} object. * @throws java.io.IOException if any. */ public static PDFCMap getCMap(String mapName) throws IOException { if (cache == null) { populateCache(); } if (!cache.containsKey(mapName)) { //throw new IOException("Unknown CMap: " + mapName); PDFDebugger.debug("Unknown CMap: '" + mapName + "' procced with 'Identity-H'"); return cache.get("Identity-H"); } return cache.get(mapName); } /** * Populate the cache with well-known types */ protected static void populateCache() { cache = new HashMap<>(); // add the Identity-H map cache.put("Identity-H", new PDFCMap() { @Override public char map(char src) { return src; } }); } /** * Parse a CMap from a CMap stream * * @param map a {@link org.loboevolution.pdfview.PDFObject} object. * @return a {@link org.loboevolution.pdfview.font.cid.PDFCMap} object. * @throws java.io.IOException if any. */ protected static PDFCMap parseCMap(PDFObject map) throws IOException { return new ToUnicodeMap(map); } /** * Map a given source character to a destination character * * @param src a char. * @return a char. */ public abstract char map(char src); /** * Get the font number assoicated with a given source character * * @param src a char. * @return a int. */ public int getFontID(char src) { return 0; } }
gpl-3.0
waikato-datamining/adams-base
adams-core/src/main/java/adams/flow/sink/sequenceplotter/ErrorCirclePaintlet.java
7405
/* * 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/>. */ /* * ErrorCirclePaintlet.java * Copyright (C) 2014-2017 University of Waikato, Hamilton, New Zealand */ package adams.flow.sink.sequenceplotter; import adams.data.sequence.XYSequence; import adams.data.sequence.XYSequencePoint; import adams.gui.core.GUIHelper; import adams.gui.event.PaintEvent.PaintMoment; import adams.gui.visualization.core.AxisPanel; import adams.gui.visualization.core.plot.Axis; import adams.gui.visualization.sequence.AbstractXYSequencePointHitDetector; import adams.gui.visualization.sequence.CirclePaintlet; import java.awt.Color; import java.awt.Graphics; import java.util.List; /** <!-- globalinfo-start --> * Paintlet for painting circles with diameters based on the error at the specified X-Y position. Prefers X errors over Y errors. * <br><br> <!-- globalinfo-end --> * <!-- options-start --> * <pre>-logging-level &lt;OFF|SEVERE|WARNING|INFO|CONFIG|FINE|FINER|FINEST&gt; (property: loggingLevel) * &nbsp;&nbsp;&nbsp;The logging level for outputting errors and debugging output. * &nbsp;&nbsp;&nbsp;default: WARNING * </pre> * * <pre>-stroke-thickness &lt;float&gt; (property: strokeThickness) * &nbsp;&nbsp;&nbsp;The thickness of the stroke. * &nbsp;&nbsp;&nbsp;default: 1.0 * &nbsp;&nbsp;&nbsp;minimum: 0.01 * </pre> * * <pre>-diameter &lt;int&gt; (property: diameter) * &nbsp;&nbsp;&nbsp;The diameter of the circle in pixels. * &nbsp;&nbsp;&nbsp;default: 7 * &nbsp;&nbsp;&nbsp;minimum: 1 * </pre> * * <pre>-anti-aliasing-enabled &lt;boolean&gt; (property: antiAliasingEnabled) * &nbsp;&nbsp;&nbsp;If enabled, uses anti-aliasing for drawing circles. * &nbsp;&nbsp;&nbsp;default: true * </pre> * <!-- options-end --> * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision: 8902 $ */ public class ErrorCirclePaintlet extends CirclePaintlet { /** for serialization. */ private static final long serialVersionUID = -8772546156227148237L; /** * Returns a string describing the object. * * @return a description suitable for displaying in the gui */ @Override public String globalInfo() { return "Paintlet for painting circles with diameters based on the error at " + "the specified X-Y position. Prefers X errors over Y errors."; } /** * Returns a new instance of the hit detector to use. * * @return the hit detector */ @Override public AbstractXYSequencePointHitDetector newHitDetector() { return new ErrorCircleHitDetector(this); } /** * Draws the custom data with the given color. * * @param g the graphics context * @param moment the paint moment * @param data the data to draw * @param color the color to draw in */ @Override public void drawCustomData(Graphics g, PaintMoment moment, XYSequence data, Color color) { List<XYSequencePoint> points; XYSequencePoint curr; int currX; int currY; AxisPanel axisX; AxisPanel axisY; int i; int diameter; points = data.toList(); axisX = getPanel().getPlot().getAxis(Axis.BOTTOM); axisY = getPanel().getPlot().getAxis(Axis.LEFT); // paint all points g.setColor(color); GUIHelper.configureAntiAliasing(g, m_AntiAliasingEnabled); for (i = 0; i < data.size(); i++) { curr = points.get(i); // determine coordinates currX = axisX.valueToPos(XYSequencePoint.toDouble(curr.getX())); currY = axisY.valueToPos(XYSequencePoint.toDouble(curr.getY())); diameter = getDiameter(axisX, axisY, currX, currY, curr); currX -= ((diameter - 1) / 2); currY -= ((diameter - 1) / 2); // draw circle g.drawOval(currX, currY, diameter, diameter); } } /** * Calculates the diameter for the given point (slow call). * * @param curr the current point * @return the diameter in pixel */ public int getDiameter(XYSequencePoint curr) { AxisPanel axisX; AxisPanel axisY; axisX = getPanel().getPlot().getAxis(Axis.BOTTOM); axisY = getPanel().getPlot().getAxis(Axis.LEFT); return getDiameter(axisX, axisY, curr); } /** * Calculates the diameter for the given point (medium fast call). * * @param axisX the X axis to use * @param axisY the Y axis to use * @param curr the current point * @return the diameter in pixel */ public int getDiameter(AxisPanel axisX, AxisPanel axisY, XYSequencePoint curr) { double currX; double currY; currX = axisX.valueToPos(XYSequencePoint.toDouble(curr.getX())); currY = axisY.valueToPos(XYSequencePoint.toDouble(curr.getY())); return getDiameter(axisX, axisY, currX, currY, curr); } /** * Calculates the diameter for the given point (fast call). * * @param axisX the X axis to use * @param axisY the Y axis to use * @param currX the current X value * @param currY the current Y value * @param curr the current point * @return the diameter in pixel */ public int getDiameter(AxisPanel axisX, AxisPanel axisY, double currX, double currY, XYSequencePoint curr) { int diameter; SequencePlotPoint ppoint; Double[] errors; diameter = m_Diameter; if (curr instanceof SequencePlotPoint) { ppoint = (SequencePlotPoint) curr; if (ppoint.hasErrorX()) { errors = ppoint.getErrorX(); if (errors.length == 1) diameter = Math.max(diameter, axisX.valueToPos(currX - errors[0]) - axisX.valueToPos(currX + errors[0])); else diameter = Math.max(diameter, axisX.valueToPos(errors[1]) - axisX.valueToPos(errors[0])); } else if (ppoint.hasErrorY()) { errors = ppoint.getErrorY(); if (errors.length == 1) diameter = Math.max(diameter, axisY.valueToPos(currY - errors[0]) - axisY.valueToPos(currY + errors[0])); else diameter = Math.max(diameter, axisY.valueToPos(errors[1]) - axisY.valueToPos(errors[0])); } } return diameter; } /** * The paint routine of the paintlet. * * @param g the graphics context to use for painting * @param moment what {@link PaintMoment} is currently being painted */ @Override public void performPaint(Graphics g, PaintMoment moment) { int i; XYSequence data; // paint all points synchronized(getActualContainerManager()) { for (i = 0; i < getActualContainerManager().count(); i++) { if (!getActualContainerManager().isVisible(i)) continue; if (getActualContainerManager().isFiltered() && !getActualContainerManager().isFiltered(i)) continue; data = getActualContainerManager().get(i).getData(); if (data.size() == 0) continue; synchronized(data) { drawCustomData(g, moment, data, getColor(i)); } } } } }
gpl-3.0
waikato-datamining/adams-base
adams-core/src/main/java/adams/flow/standalone/GridView.java
14406
/* * 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/>. */ /** * GridView.java * Copyright (C) 2012-2017 University of Waikato, Hamilton, New Zealand */ package adams.flow.standalone; import adams.core.QuickInfoHelper; import adams.flow.core.Actor; import adams.flow.core.DataPlotUpdaterSupporter; import adams.flow.sink.CallableSink; import adams.flow.sink.ComponentSupplier; import adams.gui.core.AdjustableGridPanel; import adams.gui.core.BasePanel; import adams.gui.print.JComponentWriter; import adams.gui.print.NullWriter; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.SwingUtilities; import java.awt.BorderLayout; import java.util.ArrayList; import java.util.List; /** <!-- globalinfo-start --> * Displays multiple graphical actors in a grid. The actors get added row-wise to the grid from top-left to bottom-right. The actors can be referenced in the flow using adams.flow.sink.CallableSink actors. * <br><br> <!-- globalinfo-end --> * <!-- flow-summary-start --> <!-- flow-summary-end --> * <!-- options-start --> * <pre>-logging-level &lt;OFF|SEVERE|WARNING|INFO|CONFIG|FINE|FINER|FINEST&gt; (property: loggingLevel) * &nbsp;&nbsp;&nbsp;The logging level for outputting errors and debugging output. * &nbsp;&nbsp;&nbsp;default: WARNING * </pre> * * <pre>-name &lt;java.lang.String&gt; (property: name) * &nbsp;&nbsp;&nbsp;The name of the actor. * &nbsp;&nbsp;&nbsp;default: GridView * </pre> * * <pre>-annotation &lt;adams.core.base.BaseAnnotation&gt; (property: annotations) * &nbsp;&nbsp;&nbsp;The annotations to attach to this actor. * &nbsp;&nbsp;&nbsp;default: * </pre> * * <pre>-skip &lt;boolean&gt; (property: skip) * &nbsp;&nbsp;&nbsp;If set to true, transformation is skipped and the input token is just forwarded * &nbsp;&nbsp;&nbsp;as it is. * &nbsp;&nbsp;&nbsp;default: false * </pre> * * <pre>-stop-flow-on-error &lt;boolean&gt; (property: stopFlowOnError) * &nbsp;&nbsp;&nbsp;If set to true, the flow execution at this level gets stopped in case this * &nbsp;&nbsp;&nbsp;actor encounters an error; the error gets propagated; useful for critical * &nbsp;&nbsp;&nbsp;actors. * &nbsp;&nbsp;&nbsp;default: false * </pre> * * <pre>-silent &lt;boolean&gt; (property: silent) * &nbsp;&nbsp;&nbsp;If enabled, then no errors are output in the console; Note: the enclosing * &nbsp;&nbsp;&nbsp;actor handler must have this enabled as well. * &nbsp;&nbsp;&nbsp;default: false * </pre> * * <pre>-short-title &lt;boolean&gt; (property: shortTitle) * &nbsp;&nbsp;&nbsp;If enabled uses just the name for the title instead of the actor's full * &nbsp;&nbsp;&nbsp;name. * &nbsp;&nbsp;&nbsp;default: false * </pre> * * <pre>-display-in-editor &lt;boolean&gt; (property: displayInEditor) * &nbsp;&nbsp;&nbsp;If enabled displays the panel in a tab in the flow editor rather than in * &nbsp;&nbsp;&nbsp;a separate frame. * &nbsp;&nbsp;&nbsp;default: false * </pre> * * <pre>-width &lt;int&gt; (property: width) * &nbsp;&nbsp;&nbsp;The width of the dialog. * &nbsp;&nbsp;&nbsp;default: 800 * &nbsp;&nbsp;&nbsp;minimum: -1 * </pre> * * <pre>-height &lt;int&gt; (property: height) * &nbsp;&nbsp;&nbsp;The height of the dialog. * &nbsp;&nbsp;&nbsp;default: 600 * &nbsp;&nbsp;&nbsp;minimum: -1 * </pre> * * <pre>-x &lt;int&gt; (property: x) * &nbsp;&nbsp;&nbsp;The X position of the dialog (&gt;=0: absolute, -1: left, -2: center, -3: right * &nbsp;&nbsp;&nbsp;). * &nbsp;&nbsp;&nbsp;default: -1 * &nbsp;&nbsp;&nbsp;minimum: -3 * </pre> * * <pre>-y &lt;int&gt; (property: y) * &nbsp;&nbsp;&nbsp;The Y position of the dialog (&gt;=0: absolute, -1: top, -2: center, -3: bottom * &nbsp;&nbsp;&nbsp;). * &nbsp;&nbsp;&nbsp;default: -1 * &nbsp;&nbsp;&nbsp;minimum: -3 * </pre> * * <pre>-actor &lt;adams.flow.core.Actor&gt; [-actor ...] (property: actors) * &nbsp;&nbsp;&nbsp;The panel-generating actors to display in the grid. * &nbsp;&nbsp;&nbsp;default: * </pre> * * <pre>-num-rows &lt;int&gt; (property: numRows) * &nbsp;&nbsp;&nbsp;The number of rows in the grid. * &nbsp;&nbsp;&nbsp;default: 1 * &nbsp;&nbsp;&nbsp;minimum: 1 * </pre> * * <pre>-num-cols &lt;int&gt; (property: numCols) * &nbsp;&nbsp;&nbsp;The number of columns in the grid. * &nbsp;&nbsp;&nbsp;default: 1 * &nbsp;&nbsp;&nbsp;minimum: 1 * </pre> * * <pre>-add-headers &lt;boolean&gt; (property: addHeaders) * &nbsp;&nbsp;&nbsp;If enabled, headers with the names of the actors as labels get added as * &nbsp;&nbsp;&nbsp;well. * &nbsp;&nbsp;&nbsp;default: false * </pre> * * <pre>-show-controls &lt;boolean&gt; (property: showControls) * &nbsp;&nbsp;&nbsp;If enabled, the controls for adjusting rows&#47;columns are visible. * &nbsp;&nbsp;&nbsp;default: false * </pre> * * <pre>-writer &lt;adams.gui.print.JComponentWriter&gt; (property: writer) * &nbsp;&nbsp;&nbsp;The writer to use for generating the graphics output. * &nbsp;&nbsp;&nbsp;default: adams.gui.print.NullWriter * </pre> * <!-- options-end --> * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class GridView extends AbstractMultiView implements ComponentSupplier, DataPlotUpdaterSupporter { /** for serialization. */ private static final long serialVersionUID = -4454052058077687116L; /** the number of rows to display. */ protected int m_NumRows; /** the number of columns to display. */ protected int m_NumCols; /** whether to add headers. */ protected boolean m_AddHeaders; /** whether to show the controls. */ protected boolean m_ShowControls; /** the panels to display. */ protected List<BasePanel> m_Panels; /** the writer to use. */ protected JComponentWriter m_Writer; /** * Returns a string describing the object. * * @return a description suitable for displaying in the gui */ @Override public String globalInfo() { return "Displays multiple graphical actors in a grid. The actors get added " + "row-wise to the grid from top-left to bottom-right. The actors " + "can be referenced in the flow using " + CallableSink.class.getName() + " actors."; } /** * Adds options to the internal list of options. */ @Override public void defineOptions() { super.defineOptions(); m_OptionManager.add( "num-rows", "numRows", 1, 1, null); m_OptionManager.add( "num-cols", "numCols", 1, 1, null); m_OptionManager.add( "add-headers", "addHeaders", false); m_OptionManager.add( "show-controls", "showControls", false); m_OptionManager.add( "writer", "writer", new NullWriter()); } /** * Initializes the members. */ @Override protected void initialize() { super.initialize(); m_Panels = null; } /** * Returns a quick info about the actor, which will be displayed in the GUI. * * @return null if no info available, otherwise short string */ @Override public String getQuickInfo() { String result; result = super.getQuickInfo(); result += QuickInfoHelper.toString(this, "numRows", m_NumRows, ", Rows: "); result += QuickInfoHelper.toString(this, "numCols", m_NumCols, ", Cols: "); return result; } /** * Sets the number of rows in the grid. * * @param value the number of rows */ public void setNumRows(int value) { m_NumRows = value; reset(); } /** * Returns the number of rows in the grid. * * @return the number of rows */ public int getNumRows() { return m_NumRows; } /** * Returns the tip text for this property. * * @return tip text for this property suitable for * displaying in the GUI or for listing the options. */ public String numRowsTipText() { return "The number of rows in the grid."; } /** * Sets the number of columns in the grid. * * @param value the number of cols */ public void setNumCols(int value) { m_NumCols = value; reset(); } /** * Returns the number of columns in the grid. * * @return the number of cols */ public int getNumCols() { return m_NumCols; } /** * Returns the tip text for this property. * * @return tip text for this property suitable for * displaying in the GUI or for listing the options. */ public String numColsTipText() { return "The number of columns in the grid."; } /** * Sets whether to add headers to the cells in the grid with the names * of the actors. * * @param value true if to add headers */ public void setAddHeaders(boolean value) { m_AddHeaders = value; reset(); } /** * Returns whether to add headers to the cells in the grid with the names * of the actors. * * @return true if to add headers */ public boolean getAddHeaders() { return m_AddHeaders; } /** * Returns the tip text for this property. * * @return tip text for this property suitable for * displaying in the GUI or for listing the options. */ public String addHeadersTipText() { return "If enabled, headers with the names of the actors as labels get added as well."; } /** * Sets whether to show the controls for adjusting rows/columns. * * @param value true if to show controls */ public void setShowControls(boolean value) { m_ShowControls = value; reset(); } /** * Returns whether to show the controls for adjusting rows/columns. * * @return true if to show controls */ public boolean getShowControls() { return m_ShowControls; } /** * Returns the tip text for this property. * * @return tip text for this property suitable for * displaying in the GUI or for listing the options. */ public String showControlsTipText() { return "If enabled, the controls for adjusting rows/columns are visible."; } /** * Sets the writer. * * @param value the writer */ public void setWriter(JComponentWriter value) { m_Writer = value; reset(); } /** * Returns the writer. * * @return the writer */ public JComponentWriter getWriter() { return m_Writer; } /** * Returns the tip text for this property. * * @return tip text for this property suitable for * displaying in the GUI or for listing the options. */ public String writerTipText() { return "The writer to use for generating the graphics output."; } /** * Returns the tip text for this property. * * @return tip text for this property suitable for * displaying in the GUI or for listing the options. */ @Override public String actorsTipText() { return "The panel-generating actors to display in the grid."; } /** * Updates the data container panel regardless, notifying the listeners. */ public void updatePlot() { int i; for (i = 0; i < m_Panels.size(); i++) { if (m_Panels.get(i) instanceof DataPlotUpdaterSupporter) ((DataPlotUpdaterSupporter) m_Panels.get(i)).updatePlot(); } } /** * Ensures that the wrapper is visible. * * @param wrapper the wrapper to make visible * @return true if successful */ @Override public boolean makeVisible(ViewWrapper wrapper) { // nothing to do return true; } /** * Creates the panel to display in the dialog. * * @return the panel */ @Override protected BasePanel newPanel() { AdjustableGridPanel result; JLabel label; BasePanel panel; int i; result = new AdjustableGridPanel(m_NumRows, m_NumCols); result.setControlsVisible(m_ShowControls); // add dummy panels m_Panels = new ArrayList<>(); for (i = 0; i < m_Actors.size(); i++) { panel = new BasePanel(new BorderLayout()); label = new JLabel(m_Actors.get(i).getName(), JLabel.CENTER); panel.add(label, BorderLayout.CENTER); result.addItem(panel); m_Panels.add(panel); } return result; } /** * Replaces the current dummy panel with the actual panel. * * @param actor the actor this panel is for * @param panel the panel to replace the dummy one */ @Override public void addPanel(Actor actor, BasePanel panel) { int index; index = indexOf(actor.getName()); m_Panels.set(index, panel); SwingUtilities.invokeLater(() -> { AdjustableGridPanel grid = (AdjustableGridPanel) m_Panel; grid.clear(); for (int i = 0; i < m_Panels.size(); i++) { if (m_AddHeaders) { BasePanel outer = new BasePanel(new BorderLayout()); JLabel label = new JLabel(m_Actors.get(i).getName(), JLabel.LEFT); outer.add(label, BorderLayout.NORTH); outer.add(m_Panels.get(i), BorderLayout.CENTER); grid.addItem(outer); } else { grid.addItem(m_Panels.get(i)); } } grid.updateLayout(); }); } /** * Returns the current component. * * @return the current component, can be null */ @Override public JComponent supplyComponent() { return m_Panel; } /** * Cleans up after the execution has finished. */ @Override public void wrapUp() { if (!(m_Writer instanceof NullWriter)) { SwingUtilities.invokeLater(() -> { try { m_Writer.setComponent(supplyComponent()); m_Writer.toOutput(); } catch (Exception e) { handleException("Failed to write graphical output", e); } }); } super.wrapUp(); } /** * Cleans up after the execution has finished. Also removes graphical * components. */ @Override public void cleanUp() { if (m_Panels != null) { m_Panels.clear(); m_Panels = null; } super.cleanUp(); } }
gpl-3.0
lpavone/DesignPatterns
src/Adapter/Turkey.java
125
package Adapter; /** * Created by leonardo on 09/04/17. */ public interface Turkey { void gobble(); void fly(); }
gpl-3.0
pkiraly/metadata-qa-marc
src/test/java/de/gwdg/metadataqa/marc/definition/tags/bltags/TagEXPTest.java
487
package de.gwdg.metadataqa.marc.definition.tags.bltags; import org.junit.Test; public class TagEXPTest extends BLTagTest { public TagEXPTest() { super(TagEXP.getInstance()); } @Test public void testValidFields() { validField("a", "X"); validField("a", "X", "d", "20070727"); } @Test public void testInvalidFields() { invalidField("3", "a", "1"); invalidField("a", "000093159."); invalidField("h", "B"); invalidField("d", "20070737"); } }
gpl-3.0
MasterEric/META
src/main/java/com/mastereric/meta/common/inventory/CompatSlotItemHandler.java
4777
package com.mastereric.meta.common.inventory; import mcjty.lib.compat.CompatSlot; import mcjty.lib.tools.ItemStackTools; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.InventoryBasic; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import net.minecraftforge.items.IItemHandler; import net.minecraftforge.items.IItemHandlerModifiable; import net.minecraftforge.items.SlotItemHandler; public class CompatSlotItemHandler extends CompatSlot { //TODO I am extending CompatSlot and copy-pasting code from SlotItemHandler, destroy this immediately! private static IInventory emptyInventory = new InventoryBasic("[Null]", true, 0); private final IItemHandler itemHandler; private final int index; public CompatSlotItemHandler(IItemHandler itemHandler, int index, int xPosition, int yPosition) { super(emptyInventory, index, xPosition, yPosition); this.itemHandler = itemHandler; this.index = index; } /** * Check if the stack is allowed to be placed in this slot, used for armor slots as well as furnace fuel. */ @Override public boolean isItemValid(ItemStack stack) { if (stack == null) return false; IItemHandler handler = this.getItemHandler(); ItemStack remainder; if (handler instanceof IItemHandlerModifiable) { IItemHandlerModifiable handlerModifiable = (IItemHandlerModifiable) handler; ItemStack currentStack = handlerModifiable.getStackInSlot(index); handlerModifiable.setStackInSlot(index, null); remainder = handlerModifiable.insertItem(index, stack, true); handlerModifiable.setStackInSlot(index, currentStack); } else { remainder = handler.insertItem(index, stack, true); } return ItemStackTools.isEmpty(remainder) || ItemStackTools.getStackSize(remainder) < ItemStackTools.getStackSize(stack); } /** * Helper fnct to get the stack in the slot. */ @Override public ItemStack getStack() { return this.getItemHandler().getStackInSlot(index); } // Override if your IItemHandler does not implement IItemHandlerModifiable /** * Helper method to put a stack in the slot. */ @Override public void putStack(ItemStack stack) { ((IItemHandlerModifiable) this.getItemHandler()).setStackInSlot(index, stack); this.onSlotChanged(); } /** * if par2 has more items than par1, onCrafting(item,countIncrease) is called */ @Override public void onSlotChange(ItemStack p_75220_1_, ItemStack p_75220_2_) { } @Override public int getItemStackLimit(ItemStack stack) { ItemStack maxAdd = stack.copy(); int maxInput = stack.getMaxStackSize(); ItemStackTools.setStackSize(maxAdd, maxInput); IItemHandler handler = this.getItemHandler(); ItemStack currentStack = handler.getStackInSlot(index); if (handler instanceof IItemHandlerModifiable) { IItemHandlerModifiable handlerModifiable = (IItemHandlerModifiable) handler; handlerModifiable.setStackInSlot(index, null); ItemStack remainder = handlerModifiable.insertItem(index, maxAdd, true); handlerModifiable.setStackInSlot(index, currentStack); return maxInput - (remainder != null ? ItemStackTools.getStackSize(remainder) : 0); } else { ItemStack remainder = handler.insertItem(index, maxAdd, true); int current = ItemStackTools.isEmpty(currentStack) ? 0 : ItemStackTools.getStackSize(currentStack); int added = maxInput - (ItemStackTools.isEmpty(remainder) ? ItemStackTools.getStackSize(remainder) : 0); return current + added; } } /** * Return whether this slot's stack can be taken from this slot. */ @Override public boolean canTakeStack(EntityPlayer playerIn) { return !ItemStackTools.isEmpty(this.getItemHandler().extractItem(index, 1, true)); } /** * Decrease the size of the stack in slot (first int arg) by the amount of the second int arg. Returns the new * stack. */ @Override public ItemStack decrStackSize(int amount) { return this.getItemHandler().extractItem(index, amount, false); } public IItemHandler getItemHandler() { return itemHandler; } @Override public boolean isSameInventory(Slot other) { return other instanceof SlotItemHandler && ((SlotItemHandler) other).getItemHandler() == this.itemHandler; } }
gpl-3.0
sch1zo/gui
gui/src/logparser/Parser.java
2716
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package logparser; import fisparser.Rule; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Scanner; import java.util.regex.Pattern; import xmlparser.Timepoint; /** * * @author sch1zo */ public class Parser { private Pattern ptab; private List<Float[]> controllerOutputs; private List<Float[]> controllerInputs; private List<String> controllerTimestamps; private final Pattern ptime; private final Pattern pinputs; public Parser(){ ptab = Pattern.compile("\\s\\t"); ptime = Pattern.compile("\\s*,\\s*"); pinputs = Pattern.compile("(:|\\s)"); controllerOutputs = new ArrayList<Float[]>(); controllerInputs = new ArrayList<Float[]>(); controllerTimestamps = new ArrayList<String>(); } public void run(String[] files) throws FileNotFoundException{ processLineByLine(new File(files[0])); } public void run(String file) throws FileNotFoundException{ processLineByLine(new File(file)); } /** Template method that calls {@link #processLine(String)}. */ public final void processLineByLine(File fFile) throws FileNotFoundException { //Note that FileReader is used, not File, since File is not Closeable Scanner scanner = new Scanner(new FileReader(fFile)); try { //first use a Scanner to get each line String line; while ( scanner.hasNextLine() ){ line = scanner.nextLine(); if(!line.isEmpty()) processLine( line ); } } finally { //ensure the underlying stream is always closed //this only has any effect if the item passed to the Scanner //constructor implements Closeable (which it does in this case). scanner.close(); } } protected void processLine(String aLine){ String[] a = ptab.split(aLine); String time= ptime.split(a[0])[1]; String[] b = pinputs.split(a[1]); Float[] inputs = new Float[4]; for (int i = 1; i < b.length; i++) { inputs[i-1] = Float.parseFloat(b[i]); } String[] c = pinputs.split(a[2]); Float[] outputs = new Float[4]; for (int i = 1; i < c.length; i++) { outputs[i-1] = Float.parseFloat(c[i]); } controllerInputs.add(inputs); controllerOutputs.add(outputs); controllerTimestamps.add(time); } public List<Float[]> getInputs(){ return controllerInputs; } public List<Float[]> getOutputs(){ return controllerOutputs; } public List<String> getTimestamps(){ return controllerTimestamps; } }
gpl-3.0
smee/elateXam
taskmodel/taskmodel-api/src/main/java/de/thorstenberger/taskmodel/complex/complextaskhandling/submitdata/TextSubmitData.java
1413
/* Copyright (C) 2006 Thorsten Berger 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 de.thorstenberger.taskmodel.complex.complextaskhandling.submitdata; import de.thorstenberger.taskmodel.complex.complextaskhandling.SubmitData; /** * @author Thorsten Berger * */ public class TextSubmitData implements SubmitData { private String answer = null; private int forVirtualSubtaskNumber; /** * @param relativeNumber */ public TextSubmitData( String answer ) { this.answer = answer; } public String getAnswer(){ return answer; } /* (non-Javadoc) * @see de.thorstenberger.taskmodel.complex.complextaskhandling.SubmitData#getForVirtualSubtaskNumber() */ public int getForVirtualSubtaskNumber() { return forVirtualSubtaskNumber; } }
gpl-3.0
ledyba/PokemonSavedataEditorForGBA
Pokemon_SaveData_Editor/src/PokemonSaveDataEditorForGBA/data/cheat/DiffArea.java
508
package PokemonSaveDataEditorForGBA.data.cheat; /** * <p>ƒ^ƒCƒgƒ‹: ƒ|ƒPƒ‚ƒ“ƒZ[ƒuƒf[ƒ^ƒGƒfƒBƒ^ for GBA</p> * * <p>à–¾: •ω»‚µ‚Ä‚¢‚éƒGƒŠƒA‚ð‹Lq‚·‚éƒNƒ‰ƒX</p> * * <p>’˜ìŒ : Copyright (c) 2005 PSI</p> * * <p>‰ïŽÐ–¼: ƒÕiƒvƒTƒCj‚Ì‹»–¡ŠÖS‹óŠÔ</p> * * @author PSI * @version 1.0 */ public class DiffArea { int Block; int StartOff=0; int EndOff=0; public DiffArea(int block,int start,int end) { this.Block = block; StartOff = start; EndOff = end; } }
gpl-3.0
CodeMason/code6
MultiplayerSpaceGame/src/com/puchisoft/multiplayerspacegame/DesktopStarter.java
1070
package com.puchisoft.multiplayerspacegame; import com.badlogic.gdx.Application; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.backends.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; import com.puchisoft.multiplayerspacegame.screen.WaoGame; public class DesktopStarter { public static void main(String[] args) { LwjglApplicationConfiguration config = new LwjglApplicationConfiguration(); config.title = "Multiplayer Space Game"; config.width = 800; config.height = 600; config.useCPUSynch = false; // Doesn't work on some graphics cards in windowed mode... but looks way better; makes two instances of game run poorly // config.useGL20 = true; // config.width = LwjglApplicationConfiguration.getDesktopDisplayMode().width; // config.height = LwjglApplicationConfiguration.getDesktopDisplayMode().height; // config.useCPUSynch = false; // config.resizable = false; // config.fullscreen = true; new LwjglApplication(new WaoGame(), config); Gdx.app.setLogLevel(Application.LOG_DEBUG); } }
gpl-3.0
applifireAlgo/OnlineShopEx
onlineshopping/src/main/java/shop/app/server/repository/LanguageRepository.java
1166
package shop.app.server.repository; import com.athena.server.repository.SearchInterface; import com.athena.annotation.Complexity; import com.athena.annotation.SourceCodeAuthorClass; import com.athena.framework.server.exception.repository.SpartanPersistenceException; import java.util.List; import com.athena.framework.server.exception.biz.SpartanConstraintViolationException; @SourceCodeAuthorClass(createdBy = "john.doe", updatedBy = "", versionNumber = "1", comments = "Repository for Language Master table Entity", complexity = Complexity.LOW) public interface LanguageRepository<T> extends SearchInterface { public List<T> findAll() throws SpartanPersistenceException; public T save(T entity) throws SpartanPersistenceException; public List<T> save(List<T> entity) throws SpartanPersistenceException; public void delete(String id) throws SpartanPersistenceException; public void update(T entity) throws SpartanConstraintViolationException, SpartanPersistenceException; public void update(List<T> entity) throws SpartanPersistenceException; public T findById(String languageId) throws Exception, SpartanPersistenceException; }
gpl-3.0
timernsberger/sepia
Sepia/src/edu/cwru/sepia/agent/Agent.java
3164
/** * Strategy Engine for Programming Intelligent Agents (SEPIA) Copyright (C) 2012 Case Western Reserve University This file is part of SEPIA. SEPIA 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. SEPIA 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 SEPIA. If not, see <http://www.gnu.org/licenses/>. */ package edu.cwru.sepia.agent; import java.io.InputStream; import java.io.OutputStream; import java.io.Serializable; import java.util.Collection; import org.apache.commons.configuration.Configuration; import edu.cwru.sepia.action.Action; import edu.cwru.sepia.model.history.History; import edu.cwru.sepia.model.state.State; /** * The base type for any agent that can interact with the Sepia environment. * @author Tim * */ public abstract class Agent implements Serializable { private static final long serialVersionUID = 1L; public static final int OBSERVER_ID = -999; protected final int playernum; protected Configuration configuration; // map: agentID -> flag, if this flag set false, then we will ignore this agent when checking terminal condition. /** * Create a new Agent to control a player. * @param playernum The player number controlled by this agent. */ public Agent(int playernum) { this.playernum = playernum; } public void setConfiguration(Configuration configuration) { this.configuration = configuration; } /** * Get the player number that this agent controls * @return */ public int getPlayerNumber() { return playernum; } /** * Responds to the first state of the episode with a mapping of unit Ids to unit actions. * @param state * @param history * @return */ public abstract Collection<Action> initialStep(State.StateView state, History.HistoryView history); /** * Responds to any state other than the first or last of the episode with a mapping of unit Ids to unit actions. * @param state * @param history * @return */ public abstract Collection<Action> middleStep(State.StateView state, History.HistoryView history); /** * Receives notification about the end of an episode. * @param state * @param history * @return */ public abstract void terminalStep(State.StateView state, History.HistoryView history); /** * Save data accumulated by the agent. * @see {@link #loadPlayerData(InputStream)} * @param os An output stream, such as to a file. */ public abstract void savePlayerData(OutputStream os); /** * Load data stored by the agent. * @see {@link #savePlayerData(OutputStream)} * @param is An input stream, such as from a file. */ public abstract void loadPlayerData(InputStream is); }
gpl-3.0
mvetsch/JWT4B
src/app/helpers/Config.java
8237
package app.helpers; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.eclipsesource.json.Json; import com.eclipsesource.json.JsonArray; import com.eclipsesource.json.JsonObject; import com.eclipsesource.json.JsonValue; import com.eclipsesource.json.WriterConfig; public class Config { public static PrintWriter stdout; public static PrintWriter stderr; public static List<String> jwtKeywords = Arrays.asList("Authorization: Bearer", "Authorization: bearer", "authorization: Bearer", "authorization: bearer"); public static List<String> tokenKeywords = Arrays.asList("id_token", "ID_TOKEN", "access_token", "token"); public static String highlightColor = "blue"; public static String interceptComment = "Contains a JWT"; public static boolean resetEditor = true; public static String configName = "config.json"; public static String configFolderName = ".JWT4B"; public static String configPath = System.getProperty("user.home") + File.separator + configFolderName + File.separator + configName; /* ssh-keygen -t rsa -b 2048 -m PEM -f jwtRS256.key # Don't add passphrase openssl rsa -in jwtRS256.key -pubout -outform PEM -out jwtRS256.key.pub cat jwtRS256.key cat jwtRS256.key.pub */ public static String cveAttackModePublicKey = "-----BEGIN PUBLIC KEY-----\n" + "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuvBC2RJqGAbPg6HoJaOl\n" + "T6L4tMwMzGUI8TptoBlStWe+TfRcuPVfxI1U6g87/7B62768kuU55H8bd3Yd7nBm\n" + "mdzuNthAdPDMXlrnIbOywG52iPtHAV1U5Vk5QGuj39aSuLjpBSC4jUJPcdJENpmE\n" + "CVX+EeNwZlOEDfbtnpOTMRr/24r1CLSMwp9gtaLnE6NJzh+ycTDgyrWK9OtNA+Uq\n" + "zwfNJ9BfE53u9JHJP/nWZopqlNQ26fgPASu8FULa8bmJ3kc0SZFCNvXyjZn7HVCw\n" + "Ino/ZEq7oN9tphmAPBwdfQhb2xmD3gYeWrXNP/M+SKisaX1CVwaPPowjCQMbsmfC\n" + "2wIDAQAB\n" + "-----END PUBLIC KEY-----"; public static String cveAttackModePrivateKey = "-----BEGIN RSA PRIVATE KEY-----\n" + "MIIEowIBAAKCAQEAuvBC2RJqGAbPg6HoJaOlT6L4tMwMzGUI8TptoBlStWe+TfRc\n" + "uPVfxI1U6g87/7B62768kuU55H8bd3Yd7nBmmdzuNthAdPDMXlrnIbOywG52iPtH\n" + "AV1U5Vk5QGuj39aSuLjpBSC4jUJPcdJENpmECVX+EeNwZlOEDfbtnpOTMRr/24r1\n" + "CLSMwp9gtaLnE6NJzh+ycTDgyrWK9OtNA+UqzwfNJ9BfE53u9JHJP/nWZopqlNQ2\n" + "6fgPASu8FULa8bmJ3kc0SZFCNvXyjZn7HVCwIno/ZEq7oN9tphmAPBwdfQhb2xmD\n" + "3gYeWrXNP/M+SKisaX1CVwaPPowjCQMbsmfC2wIDAQABAoIBAGtODOEzq8i86BMk\n" + "NfCdHgA3iVGmq1YMTPTDWDgFMS/GLDvtH+hfmShnBC4SrpsXv34x32bmw7OArtCE\n" + "8atzw8FgSzEaMu2tZ3Jl9bSnxNymy83XhyumWlwIOk/bOcb8EV6NbdyuqqETRi0M\n" + "yHEa7+q3/M5h4pwqJmwpqL5U8bHGVGXNEbiA/TneNyXjSn03uPYaKTw4R9EG951A\n" + "pCJf4Atba5VIfdZ59fx/6rxCuKjWlvZrklE3Cll/+A0dRN5vBSR+EBYgfedMPepM\n" + "6TYDOsQnsy1bFJjy+aE/kwYGgtjuHOlvCpwq90SY3WueXClDfioaJ/1S6QT3q8hf\n" + "UHodWxkCgYEA8X6+dybVvBgawxyYZEi1P/KNWC9tr2zdztnkDB4nn97UIJzxmjTh\n" + "s81EsX0Mt24DJg36HoX5x1lDHNrR2RvIEPy8vfzTdNVa6KP7E7CWUUcW39nmt/z7\n" + "ezlyZa8TVPBE/xvozdZuTAzd0rafUX3Ugqzn17MBshz07/K4Z0iy/C0CgYEAxiqm\n" + "J7ul9CmNVvCnQ19tvcO7kY8h9AYIEtrqf9ubiq9W7Ldf9mXIhlG3wr6U3dXuAVVa\n" + "4g9zkXr+N7BE4hlQcJpBn5ywtYfqzK1GRy+rfwPgC/JbWEnNDP8oYnZ8R6pkhyOC\n" + "zqDqCZPtnmD9Je/ifdmgIkkxQD25ktyCYMhPuCcCgYEAh/MQCkfEfxUay8gnSh1c\n" + "W9mSFJjuqJki7TXgmanIKMnqpUl1AZjPjsb56uk45XJ7N0sbCV/m04C+tVnCVPS8\n" + "1kNRhar054rMmLbnu5fnp23bxL0Ik39Jm38llXTP7zsrvGnbzzTt9sYvglXorpml\n" + "rsLj6ZwOUlTW1tXPVeWpTSkCgYBfAkGpWRlGx8lA/p5i+dTGn5pFPmeb9GxYheba\n" + "KDMZudkmIwD6RHBwnatJzk/XT+MNdpvdOGVDQcGyd2t/L33Wjs6ZtOkwD5suSIEi\n" + "TiOeAQChGbBb0v5hldAJ7R7GyVXrSMZFRPcQYoERZxTX5HwltHpHFepsD2vykpBb\n" + "0I4QDwKBgDRH3RjKJduH2WvHOmQmXqWwtkY7zkLwSysWTW5KvCEUI+4VHMggaQ9Z\n" + "YUXuHa8osFZ8ruJzSd0HTrDVuNTb8Q7XADOn4a5AGHu1Bhw996uNCP075dx8IOsl\n" + "B6zvMHB8rRW93GfFd08REpsgqSm+AL6iLlZHowC00FFPtLs9e7ci\n" + "-----END RSA PRIVATE KEY-----"; public static void loadConfig() { File configFile = new File(configPath); if (!configFile.getParentFile().exists()) { Output.output("Config file directory '" + configFolderName + "' does not exist - creating it"); boolean mkdir = configFile.getParentFile().mkdir(); if (!mkdir) { Output.outputError("Could not create directory '" + configFile.getParentFile().toString() + "'"); } } if (!configFile.exists()) { Output.output("Config file '" + configPath + "' does not exist - creating it"); try { boolean configFileCreated = configFile.createNewFile(); if (!configFileCreated) { throw new IOException("Create new file failed for config file"); } } catch (IOException e) { Output.outputError( "Error creating config file '" + configPath + "' - message:" + e.getMessage() + " - cause:" + e.getCause() .toString()); return; } String defaultConfigJSONRaw = generateDefaultConfigFile(); try { Files.write(Paths.get(configPath), defaultConfigJSONRaw.getBytes()); } catch (IOException e) { Output.outputError( "Error writing config file '" + configPath + "' - message:" + e.getMessage() + " - cause:" + e.getCause() .toString()); } } try { String configRaw = new String(Files.readAllBytes(Paths.get(configPath))); JsonObject configJO = Json.parse(configRaw).asObject(); JsonArray jwtKeywordsJA = configJO.get("jwtKeywords").asArray(); jwtKeywords = new ArrayList<>(); for (JsonValue jwtKeyword : jwtKeywordsJA) { jwtKeywords.add(jwtKeyword.asString()); } JsonArray tokenKeywordsJA = configJO.get("tokenKeywords").asArray(); tokenKeywords = new ArrayList<>(); for (JsonValue tokenKeyword : tokenKeywordsJA) { tokenKeywords.add(tokenKeyword.asString()); } resetEditor = configJO.getBoolean("resetEditor", true); highlightColor = configJO.get("highlightColor").asString(); // red, orange, yellow, green, cyan, blue, pink, magenta, gray,or a null String to clear any existing highlight. ArrayList<String> allowedColors = new ArrayList<>( Arrays.asList("red", "orange", "yellow", "green", "cyan", "blue", "pink", "magenta", "gray", "none")); if (!allowedColors.contains(highlightColor)) { highlightColor = "none"; Output.output( "Unknown color, only 'red, orange, yellow, green, cyan, blue, pink, magenta, gray, none' is possible - defaulting to none."); } interceptComment = configJO.get("interceptComment").asString(); cveAttackModePublicKey = configJO.get("cveAttackModePublicKey").asString(); cveAttackModePrivateKey = configJO.get("cveAttackModePrivateKey").asString(); } catch (IOException e) { Output.outputError( "Error loading config file '" + configPath + "' - message:" + e.getMessage() + " - cause:" + e.getCause() .toString()); } } private static String generateDefaultConfigFile() { JsonObject configJO = new JsonObject(); JsonArray jwtKeywordsJA = new JsonArray(); for (String jwtKeyword : jwtKeywords) { jwtKeywordsJA.add(jwtKeyword); } JsonArray tokenKeywordsJA = new JsonArray(); for (String tokenKeyword : tokenKeywords) { tokenKeywordsJA.add(tokenKeyword); } configJO.add("resetEditor", true); configJO.add("highlightColor", highlightColor); configJO.add("interceptComment", interceptComment); configJO.add("jwtKeywords", jwtKeywordsJA); configJO.add("tokenKeywords", tokenKeywordsJA); configJO.add("cveAttackModePublicKey", cveAttackModePublicKey); configJO.add("cveAttackModePrivateKey", cveAttackModePrivateKey); return configJO.toString(WriterConfig.PRETTY_PRINT); } }
gpl-3.0
AshourAziz/EchoPet-1
modules/v1_12_R1/src/com/dsh105/echopet/compat/nms/v1_12_R1/entity/type/EntityShulkerPet.java
2836
/* * This file is part of EchoPet. * * EchoPet 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. * * EchoPet 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 EchoPet. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.echopet.compat.nms.v1_12_R1.entity.type; import org.bukkit.DyeColor; import com.dsh105.echopet.compat.api.entity.*; import com.dsh105.echopet.compat.api.entity.type.nms.IEntityShulkerPet; import com.dsh105.echopet.compat.nms.v1_12_R1.entity.EntityPet; import com.google.common.base.Optional; import net.minecraft.server.v1_12_R1.*; /** * @Author Borlea * @Github https://github.com/borlea/ * @Website http://codingforcookies.com/ * @since Mar 7, 2016 */ @EntitySize(width = 1.0F, height = 1.0F) @EntityPetType(petType = PetType.SHULKER) public class EntityShulkerPet extends EntityPet implements IEntityShulkerPet{ protected static final DataWatcherObject<EnumDirection> ATTACHED_FACE = DataWatcher.a(EntityShulkerPet.class, DataWatcherRegistry.l); protected static final DataWatcherObject<Optional<BlockPosition>> ATTACHED_BLOCK_POS = DataWatcher.a(EntityShulkerPet.class, DataWatcherRegistry.k); protected static final DataWatcherObject<Byte> PEEK_TICK = DataWatcher.a(EntityShulkerPet.class, DataWatcherRegistry.a);// how many ticks its opened for protected static final DataWatcherObject<Byte> COLOR_DW = DataWatcher.a(EntityShulkerPet.class, DataWatcherRegistry.a); public EntityShulkerPet(World world){ super(world); } public EntityShulkerPet(World world, IPet pet){ super(world, pet); } protected void initDatawatcher(){ super.initDatawatcher(); this.datawatcher.register(ATTACHED_FACE, EnumDirection.DOWN); this.datawatcher.register(ATTACHED_BLOCK_POS, Optional.absent()); this.datawatcher.register(PEEK_TICK, (byte) 0); this.datawatcher.register(COLOR_DW, (byte) EnumColor.PURPLE.getColorIndex()); } @Override public SizeCategory getSizeCategory(){ return SizeCategory.REGULAR; } @Override public void setOpen(boolean open){ if(open){ datawatcher.set(PEEK_TICK, Byte.MAX_VALUE);// since we don't have the ai nothing decreases it except us. }else{ datawatcher.set(PEEK_TICK, (byte) 0); } } @Override public void setColor(DyeColor color){ datawatcher.register(COLOR_DW, (byte) EnumColor.fromColorIndex(color.ordinal()).getColorIndex());// is enumcolor stuff needed? } }
gpl-3.0
filinep/cilib
library/src/main/java/net/sourceforge/cilib/pso/dynamic/detectionstrategies/RandomSentryDetectionStrategy.java
3410
/** __ __ * _____ _/ /_/ /_ Computational Intelligence Library (CIlib) * / ___/ / / / __ \ (c) CIRG @ UP * / /__/ / / / /_/ / http://cilib.net * \___/_/_/_/_.___/ */ package net.sourceforge.cilib.pso.dynamic.detectionstrategies; import fj.P2; import net.sourceforge.cilib.algorithm.Algorithm; import net.sourceforge.cilib.algorithm.population.HasNeighbourhood; import net.sourceforge.cilib.algorithm.population.HasTopology; import net.sourceforge.cilib.pso.particle.Particle; import net.sourceforge.cilib.util.selection.Samples; import net.sourceforge.cilib.util.selection.recipes.RandomSelector; public class RandomSentryDetectionStrategy extends EnvironmentChangeDetectionStrategy { private static final long serialVersionUID = 6254159986113630555L; private int sentries; private double theta; private boolean initialised = false; fj.data.List<Integer> sentryIndexes; public RandomSentryDetectionStrategy() { sentries = 1; theta = 0.001; } public <A extends HasTopology & Algorithm> void initialise(A algorithm){ sentryIndexes = fj.data.List.iterableList(new RandomSelector<P2<Particle,Integer>>().on(algorithm.getTopology().zipIndex()).select(Samples.first(sentries))).map(P2.<Particle,Integer>__2()); this.initialised = true; } public RandomSentryDetectionStrategy(RandomSentryDetectionStrategy copy) { super(copy); this.sentries = copy.sentries; this.theta = copy.theta; } public RandomSentryDetectionStrategy getClone() { return new RandomSentryDetectionStrategy(this); } /** Check for environment change: * Pick the specified number of random particles (sentries) and evaluate their current positions. * If the difference between the old fitness and the newly generated one is significant (exceeds a predefined theta) * for one or more of the sentry particles, assume that the environment has changed. * @param algorithm PSO algorithm that operates in a dynamic environment * @return true if any changes are detected, false otherwise */ @Override public <A extends HasTopology & Algorithm & HasNeighbourhood> boolean detect(A algorithm) { if(initialised == false){ this.initialise(algorithm); } boolean envChangeOccured = false; for (Integer nextSentryIndex : sentryIndexes) { Particle nextSentry = (Particle) algorithm.getTopology().index(nextSentryIndex); double oldSentryFitness = nextSentry.getFitness().getValue(); double newSentryFitness = algorithm.getOptimisationProblem().getFitness(nextSentry.getCandidateSolution()).getValue(); if (Math.abs(oldSentryFitness - newSentryFitness) >= theta) { envChangeOccured = true; break; } } return envChangeOccured; } /** * @return the sentries */ public int getSentries() { return sentries; } /** * @param sentries the sentries to set */ public void setSentries(int sentries) { this.sentries = sentries; } /** * @return the theta */ public double getTheta() { return theta; } /** * @param theta the theta to set */ public void setTheta(double theta) { this.theta = theta; } }
gpl-3.0
csmart/jContacts
src/com/distroguy/jContacts/Database.java
3942
/** * * Database * * This is responsible for reading and writing out the program's dataset to disk * * @author Chris Smart <distroguy@gmail.com> * @since 2015-02-01 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.distroguy.jContacts; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.ArrayList; /** * Database * * Reading and writing out the dataset. * * @param Takes nothing * @return Returns nothing * */ public class Database { // Create a file object so we can test for it File organiserFile; String dataFormat; /** * Database * * Constructor for the Database object * * @param Takes a String for filename * @return Returns nothing * */ Database(String filename) { organiserFile = new File(filename); } /** * Database * * Default constructor for the Database object * * @param Takes nothing * @return Returns nothing * */ Database() { } /** * checkExists * * Checks to see if the persistent file that holds the dataset already * exists * * @param Takes nothing * @return Returns Boolean * */ public Boolean checkExists() { if (organiserFile.exists() && organiserFile.isFile() && organiserFile.canWrite() && organiserFile.canWrite()) { return true; } else { return false; } } /** * readDataset * * Reads in any data from disk and formats as an ArrayList for Organiser * class * * @param Takes nothing * @return Returns ArrayList of the dataset * */ public ArrayList<Contact> readDataset() { ArrayList<Contact> newContacts = new ArrayList<Contact>(); try { ObjectInputStream inputStream = new ObjectInputStream( new FileInputStream(organiserFile.getAbsolutePath())); newContacts = (ArrayList<Contact>) inputStream.readObject(); inputStream.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return newContacts; } /** * saveDataset * * Saves the program data to persistent storage * * @param Takes String for the file name * @param Takes ArrayList of Contact objects to write * @return Returns nothing * */ public Boolean saveDataset(ArrayList<Contact> contacts) { try { ObjectOutputStream outputStream = new ObjectOutputStream( new FileOutputStream(organiserFile.getAbsolutePath())); outputStream.writeObject(contacts); outputStream.flush(); outputStream.close(); } catch (Exception e) { return false; } return true; } /** * setFormat * * Sets the format of the persistent data * * @param Takes String for data format * @return Returns nothing * */ public void setFormat(String dataFormat) { // TO-DO } /** * setFilename * * Sets the name of the file to write data to * * @param Takes String for file name * @return Returns nothing * */ public void setFilename(String filename) { organiserFile = new File(filename); } }
gpl-3.0
sasikumar0114/sasikumar.v
beginner21.java
465
package guvibeginner; import java.util.Scanner; public class beginner21 { public static void main(String[] args) { System.out.println("Enter the number:"); Scanner s=new Scanner(System.in); int a=s.nextInt(); if(a==1){ System.out.println("1"); } if(a==2){ System.out.println("1 1"); } int b=1,c=1,d; if(a>2){ System.out.print(b+" "+c+" "); for(int i=2;i<a;i++){ d=b+c; System.out.print(d+" "); b=c; c=d; } } } }
gpl-3.0
hervegirod/j6dof-flight-sim
src/steelseries/eu/hansolo/steelseries/tools/CustomLedColor.java
3148
/* * Copyright (c) 2012, Gerrit Grunwald * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * The names of its contributors may not be used to endorse or promote * products derived from this software without specific prior written * permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package eu.hansolo.steelseries.tools; import java.awt.Color; /** * * @author Gerrit Grunwald han.solo at muenster.de */ public class CustomLedColor { public final Color COLOR; public final Color INNER_COLOR1_ON; public final Color INNER_COLOR2_ON; public final Color OUTER_COLOR_ON; public final Color CORONA_COLOR; public final Color INNER_COLOR1_OFF; public final Color INNER_COLOR2_OFF; public final Color OUTER_COLOR_OFF; public CustomLedColor(final Color COLOR) { this.COLOR = COLOR; final float HUE = Color.RGBtoHSB(COLOR.getRed(), COLOR.getGreen(), COLOR.getBlue(), null)[0]; if (COLOR.getRed() == COLOR.getGreen() && COLOR.getRed() == COLOR.getBlue()) { INNER_COLOR1_ON = Color.getHSBColor(HUE, 0.0f, 1.0f); INNER_COLOR2_ON = Color.getHSBColor(HUE, 0.0f, 1.0f); OUTER_COLOR_ON = Color.getHSBColor(HUE, 0.0f, 0.99f); CORONA_COLOR = Color.getHSBColor(HUE, 0.0f, 1.00f); INNER_COLOR1_OFF = Color.getHSBColor(HUE, 0.0f, 0.35f); INNER_COLOR2_OFF = Color.getHSBColor(HUE, 0.0f, 0.35f); OUTER_COLOR_OFF = Color.getHSBColor(HUE, 0.0f, 0.26f); } else { INNER_COLOR1_ON = Color.getHSBColor(HUE, 0.75f, 1.0f); INNER_COLOR2_ON = Color.getHSBColor(HUE, 0.75f, 1.0f); OUTER_COLOR_ON = Color.getHSBColor(HUE, 1.0f, 0.99f); CORONA_COLOR = Color.getHSBColor(HUE, 0.75f, 1.00f); INNER_COLOR1_OFF = Color.getHSBColor(HUE, 1.0f, 0.35f); INNER_COLOR2_OFF = Color.getHSBColor(HUE, 1.0f, 0.35f); OUTER_COLOR_OFF = Color.getHSBColor(HUE, 1.0f, 0.26f); } } }
gpl-3.0
0xnm/BTC-e-client-for-Android
BTCeClient/src/main/java/com/QuarkLabs/BTCeClient/ConstantHolder.java
1225
/* * WEX client * Copyright (C) 2014 QuarkDev Solutions <quarkdev.solutions@gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.QuarkLabs.BTCeClient; public final class ConstantHolder { public static final int ALARM_NOTIF_ID = 1000; public static final int ACCOUNT_INFO_NOTIF_ID = 2000; public static final int TRADE_REGISTERED_NOTIF_ID = 3000; public static final String UPDATE_TICKERS_ACTION = "UpdateTickers"; public static final String UPDATE_TICKERS_FAILED_ACTION = "UpdateTickersFailed"; private ConstantHolder() { } }
gpl-3.0
hertzigger/AgaBacbone
src/main/java/com/craftaga/agabacbone/session/SessionHandler.java
8510
package com.craftaga.agabacbone.session; import com.craftaga.agabacbone.IPlayerNameResolver; import com.craftaga.agabacbone.commands.queue.CommandQueue; import com.craftaga.agabacbone.concurrent.schedule.IPlayerScheduledTimerHandler; import com.craftaga.agabacbone.concurrent.IPluginManager; import com.craftaga.agabacbone.concurrent.IMethod; import com.craftaga.agabacbone.concurrent.IWorldManager; import com.craftaga.agabacbone.concurrent.methods.ParentMethod; import com.craftaga.agabacbone.persistence.IPersistenceManager; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.core.task.TaskExecutor; import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; /** * description * * @author Jonathan * @since 25/03/14 */ public class SessionHandler implements ISessionHandler { final private IMethod commandHandler = new ParentMethod(); final private ConcurrentHashMap<UUID, IUserSession> userSessionHashMap = new ConcurrentHashMap<>(); final private List<IPlayerScheduledTimerHandler> scheduledCommandQueueList = new ArrayList<IPlayerScheduledTimerHandler>(); private TaskExecutor taskExecutor; private ThreadPoolTaskScheduler threadPoolTaskScheduler; private IPlayerNameResolver playerNameResolver; private IPluginManager pluginManager; private IPersistenceManager persistenceManager; private IWorldManager worldManager; private ClassPathXmlApplicationContext context; public SessionHandler(TaskExecutor taskExecutor, ThreadPoolTaskScheduler threadPoolTaskScheduler) { this.taskExecutor = taskExecutor; this.threadPoolTaskScheduler = threadPoolTaskScheduler; } @Override public IPersistenceManager getPersistenceManager() { return persistenceManager; } @Override public void setPersistenceManager(IPersistenceManager persistenceManager) { this.persistenceManager = persistenceManager; } @Override public IWorldManager getWorldManager() { return worldManager; } @Override public void setContext(ClassPathXmlApplicationContext context) { this.context = context; } @Override public void setWorldManager(IWorldManager worldManager) { this.worldManager = worldManager; } @Override public IMethod getCommandHandler() { return commandHandler; } private CommandSender commandSender; @Override public CommandSender getCommandSender() { return commandSender; } @Override public void setCommandSender(CommandSender commandSender) { this.commandSender = commandSender; } @Override public void setupInstructions() { } @Override public IPlayerNameResolver getPlayerNameResolver() { return playerNameResolver; } @Override public void setPlayerNameResolver(IPlayerNameResolver playerNameResolver) { this.playerNameResolver = playerNameResolver; } @Override public boolean onCommand( final Player player, final Command command, final String label, final String[] args) { String[] allArgs = new String[args.length + 1]; allArgs[0] = command.getName(); int i = 1; for (String s : args) { allArgs[i] = s; i++; } IUserSession userSession = null; if (!userSessionHashMap.containsKey(player.getUniqueId())) { addUserSession(player); } else { userSession = userSessionHashMap.get(player.getUniqueId()); } CommandQueue cmdQueue = commandHandler.getCommandQueue(allArgs, userSession); if (cmdQueue != null) { cmdQueue.setPlugin(pluginManager); cmdQueue.setSender(player); userSession.executeQueue(cmdQueue); return true; } return false; } @Override public IPluginManager getPluginManager() { return pluginManager; } @Override public void setPluginManager(IPluginManager pluginManager) { this.pluginManager = pluginManager; } @Override public boolean checkPlayerHasSession(Player player) { return userSessionHashMap.containsKey(player.getUniqueId()); } @Override public boolean checkPlayerHasSession(String player) { return userSessionHashMap.containsKey(playerNameResolver.getUniqueId(player)); } @Override public IUserSession getUserSession(Player player) { if (userSessionHashMap.containsKey(player.getUniqueId())) { return userSessionHashMap.get(player.getUniqueId()); } else { return null; } } @Override public IUserSession getUserSession(String playerName) { UUID userUUID = playerNameResolver.getUniqueId(playerName); if (userSessionHashMap.containsKey(userUUID)) { return userSessionHashMap.get(userUUID); } else { return null; } } @Override public void scheduleTimerHandlerAtFixedRate(IPlayerScheduledTimerHandler scheduledTimerHandler) { for (Map.Entry<UUID, IUserSession> entry : userSessionHashMap.entrySet()) { if ((entry.getValue().getUser() instanceof Player)) { entry.getValue().scheduleTimerHandlerAtFixedRate(scheduledTimerHandler); } } scheduledCommandQueueList.add(scheduledTimerHandler); } @Override public void removeScheduledHandle(IPlayerScheduledTimerHandler scheduledTimerHandler) { for (Map.Entry<UUID, IUserSession> entry : userSessionHashMap.entrySet()) { IUserSession session = entry.getValue(); session.removeScheduledHandle(scheduledTimerHandler); } } @Override public void removeAllScheduledJobs() { for (Map.Entry<UUID, IUserSession> entry : userSessionHashMap.entrySet()) { IUserSession session = entry.getValue(); session.removeAllScheduledJobs(); } } @Override public void immediatelyEndAllScheduledJobs() { for (Map.Entry<UUID, IUserSession> entry : userSessionHashMap.entrySet()) { IUserSession session = entry.getValue(); session.removeAllScheduledJobs(); } } @Override public void addUserSession(Player player) { if (!userSessionHashMap.containsValue(player.getUniqueId())) { IUserSession userSession = new UserSession(); userSession.setSessionHandler(this); userSession.setContext(context); userSession.setTaskExecutor(taskExecutor); userSession.setThreadPoolTaskScheduler(threadPoolTaskScheduler); userSession.setUser(player); userSession.setPersistenceManager(persistenceManager); userSession.startSession(); userSession.createSnapshot(); userSessionHashMap.put(player.getUniqueId(), userSession); for (IPlayerScheduledTimerHandler scheduledTimerHandler : scheduledCommandQueueList) { userSession.scheduleTimerHandlerAtFixedRate(scheduledTimerHandler); } } } @Override public void removeUserSession(Player player) { if (userSessionHashMap.containsKey(player.getUniqueId())) { IUserSession session = userSessionHashMap.get(player.getUniqueId()); session.removeAllScheduledJobs(); session.close(); userSessionHashMap.remove(player.getUniqueId()); getPluginManager().getPlugin().getLogger().info("[" + session.getUser().getDisplayName() + "][" + session.getUser().getName() + "] Session unloaded"); } } /** * Gets a copy of the players in the session to avoid modification of the userSession * * @return list of players */ @Override public List<Player> getPlayers() { ArrayList<Player> players = new ArrayList<Player>(); for(IUserSession userSession : userSessionHashMap.values()) { players.add(userSession.getUser()); } return players; } }
gpl-3.0
bsumath/MathToolkit
mathtools/src/main/java/edu/emporia/mathtools/Literal.java
189
package edu.emporia.mathtools; /** * Created by Ben on 12/19/2015. */ class Literal extends Expr { double v; Literal (double _v) { v = _v; } public double value () { return v; } }
gpl-3.0
nagyistoce/Wilma
wilma-application/modules/wilma-stub-configuration-parser/src/main/java/com/epam/wilma/stubconfig/initializer/support/ExternalClassInitializer.java
5690
package com.epam.wilma.stubconfig.initializer.support; /*========================================================================== Copyright 2013-2015 EPAM Systems This file is part of Wilma. Wilma 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. Wilma 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 Wilma. If not, see <http://www.gnu.org/licenses/>. ===========================================================================*/ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeansException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.epam.wilma.stubconfig.dom.parser.node.helper.ClassNameMapper; import com.epam.wilma.stubconfig.domain.exception.DescriptorValidationFailedException; import com.epam.wilma.stubconfig.initializer.condition.helper.ClassFactory; import com.epam.wilma.stubconfig.initializer.condition.helper.ClassPathExtender; import com.epam.wilma.stubconfig.initializer.support.helper.BeanRegistryService; import com.epam.wilma.stubconfig.initializer.support.helper.ClassInstantiator; import com.epam.wilma.stubconfig.initializer.support.helper.ClassValidator; /** * Class for initializing external classes and adding them to class path. * @author Tamas_Bihari, Tamas Kohegyi * */ @Component public class ExternalClassInitializer { private static final Logger LOGGER = LoggerFactory.getLogger(ExternalClassInitializer.class); @Autowired private ClassPathExtender classPathExtender; @Autowired private ClassFactory classFactory; @Autowired private BeanRegistryService beanRegistryService; @Autowired private ClassNameMapper classNameMapper; @Autowired private ClassValidator externalClassValidator; @Autowired private ClassInstantiator classInstantiator; /** * Generic function, which imports external class from the file system and adds it to the class path. * @param <T> is the type of the return object * @param externalClassName is fully qualified name * @param classPath is the resource path * @param interfaceToCast class of the desirable interface * @return with the new instance of the class * @throws DescriptorValidationFailedException if the class does not exist or not valid. */ public <T> T loadExternalClass(final String externalClassName, final String classPath, final Class<T> interfaceToCast) { String simpleName = getSimpleName(externalClassName); T result; try { result = findBean(interfaceToCast, simpleName); } catch (BeansException ex) { LOGGER.debug(String.format("Finding class with name '%s' of type '%s' as a bean failed", simpleName, interfaceToCast), ex); String fullClassName = classNameMapper.get(externalClassName); result = initializeBean(fullClassName, classPath, interfaceToCast, simpleName); } return result; } private <T> T initializeBean(final String externalClassName, final String classPath, final Class<T> interfaceToCast, final String className) { LOGGER.info("Initializing class {} of type {}, using classpath {}.", externalClassName + "/" + className, interfaceToCast, classPath); T result = instantiateExternalClass(externalClassName, classPath, interfaceToCast); beanRegistryService.register(className, result); return result; } private <T> T instantiateExternalClass(final String externalClassName, final String classPath, final Class<T> interfaceToCast) { T result; classPathExtender.addFile(classPath); try { Class<T> classToLoad = null; classToLoad = classFactory.getClassToLoad(externalClassName); result = classInstantiator.createClassInstanceOf(classToLoad); externalClassValidator.validateInterface(result, interfaceToCast, classPath); } catch (SecurityException | IllegalArgumentException | ReflectiveOperationException e) { throw new DescriptorValidationFailedException("Validation of stub descriptor failed - External class '" + classPath + "/" + externalClassName + "' not found.", e); } catch (NoClassDefFoundError e) { throw new DescriptorValidationFailedException("Validation of stub descriptor failed - External class '" + classPath + "/" + externalClassName + "' cannot be loaded, probably cannot find the package.", e); } catch (ClassFormatError e) { throw new DescriptorValidationFailedException("Validation of stub descriptor failed - External class '" + classPath + "/" + externalClassName + "' has invalid class format.", e); } return result; } private <T> T findBean(final Class<T> interfaceToCast, final String className) { LOGGER.debug("Searching for class with name {} of type {}", className, interfaceToCast); return beanRegistryService.getBean(className, interfaceToCast); } private String getSimpleName(final String externalClassName) { String[] split = externalClassName.split("\\."); return split[split.length - 1]; } }
gpl-3.0
xedushx/erpxprime
erpxprime/src/java/ec/com/erpxprime/framework/componentes/SeleccionArbol.java
2491
/* * Copyright (c) 2012, xedushx . All rights reserved. */ package ec.com.erpxprime.framework.componentes; import org.primefaces.model.TreeNode; /** * * @author xedushx */ public class SeleccionArbol extends Dialogo { private String ruta = "mbe_index.clase"; private Arbol arb_seleccion = new Arbol(); private Grid gri_cuerpo = new Grid(); private boolean aux_arbol = false; public SeleccionArbol() { this.setWidth("35%"); this.setHeight("60%"); this.setResizable(false); this.setHeader("Seleccionar"); gri_cuerpo.setTransient(true); gri_cuerpo.getChildren().add(arb_seleccion); this.setDialogo(gri_cuerpo); } public void setSeleccionArbol(String tabla, String campoPrimaria, String campoNombre, String campoPadre) { arb_seleccion.setId(this.getId() + "_arb_seleccion"); arb_seleccion.setDynamic(false); arb_seleccion.setRuta(ruta + "." + this.getId()); arb_seleccion.setTipoSeleccion(true); arb_seleccion.setArbol(tabla, campoPrimaria, campoNombre, campoPadre); } public void setTituloArbol(String titulo) { arb_seleccion.setTitulo(titulo); } @Override public void dibujar() { if (aux_arbol == false) { arb_seleccion.dibujar(); aux_arbol = true; } gri_cuerpo.setStyle("width:" + (getAnchoPanel() - 5) + "px;height:" + getAltoPanel() + "px;overflow: auto;display: block;"); arb_seleccion.setStyle("width:" + (getAnchoPanel() - 15) + "px;height:" + (getAltoPanel() - 10) + "px;overflow: hidden;display: block;"); super.dibujar(); } @Override public Grid getGri_cuerpo() { return gri_cuerpo; } @Override public void setGri_cuerpo(Grid gri_cuerpo) { this.gri_cuerpo = gri_cuerpo; } public String getSeleccionados() { return arb_seleccion.getFilasSeleccionadas(); } public TreeNode[] getNodosSeleccionados() { return arb_seleccion.getSeleccionados(); } public String getRuta() { return ruta; } public void setRuta(String ruta) { this.ruta = ruta; } public Arbol getArb_seleccion() { return arb_seleccion; } public void setArb_seleccion(Arbol arb_seleccion) { this.arb_seleccion = arb_seleccion; } @Override public void cerrar() { arb_seleccion.setSeleccionados(null); super.cerrar(); } }
gpl-3.0
CCAFS/MARLO
marlo-data/src/main/java/org/cgiar/ccafs/marlo/data/dao/ProjectedBenefitsWeightDescriptionDAO.java
1280
/***************************************************************** * This file is part of Managing Agricultural Research for Learning & * Outcomes Platform (MARLO). * MARLO 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. * MARLO 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 MARLO. If not, see <http://www.gnu.org/licenses/>. *****************************************************************/ /************** * @author Diego Perez - CIAT/CCAFS **************/ package org.cgiar.ccafs.marlo.data.dao; import org.cgiar.ccafs.marlo.data.model.ProjectedBenefitsWeightDescription; import java.util.List; public interface ProjectedBenefitsWeightDescriptionDAO { public ProjectedBenefitsWeightDescription find(long id); public List<ProjectedBenefitsWeightDescription> findAll(); }
gpl-3.0
robworth/patientview
patientview-parent/radar/src/main/java/org/patientview/radar/web/components/JFreeChartImage.java
2474
/* * PatientView * * Copyright (c) Worth Solutions Limited 2004-2013 * * This file is part of PatientView. * * PatientView 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. * PatientView 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 PatientView in a file * titled COPYING. If not, see <http://www.gnu.org/licenses/>. * * @package PatientView * @link http://www.patientview.org * @author PatientView <info@patientview.org> * @copyright Copyright (c) 2004-2013, Worth Solutions Limited * @license http://www.gnu.org/licenses/gpl-3.0.html The GNU General Public License V3.0 */ package org.patientview.radar.web.components; import org.apache.wicket.markup.html.image.Image; import org.apache.wicket.model.Model; import org.apache.wicket.request.http.WebResponse; import org.apache.wicket.request.resource.DynamicImageResource; import org.apache.wicket.request.resource.IResource; import org.apache.wicket.util.time.Duration; import org.jfree.chart.JFreeChart; public class JFreeChartImage extends Image { private int width; private int height; public JFreeChartImage(String id, JFreeChart chart, int width, int height) { super(id, new Model(chart)); this.width = width; this.height = height; } @Override protected IResource getImageResource() { DynamicImageResource resource = new DynamicImageResource() { @Override protected byte[] getImageData(final Attributes attributes) { JFreeChart chart = (JFreeChart) getDefaultModelObject(); return toImageData(chart.createBufferedImage(width, height)); } @Override protected void configureResponse(final ResourceResponse response, final Attributes attributes) { super.configureResponse(response, attributes); response.setCacheDuration(Duration.NONE); response.setCacheScope(WebResponse.CacheScope.PRIVATE); } }; return resource; } }
gpl-3.0
moxaj/mobsoft-lab3
app/src/main/java/mobsoftlab/repository/SugarOrmRepository.java
1047
package mobsoftlab.repository; import android.content.Context; import com.orm.SugarContext; import com.orm.SugarRecord; import java.util.List; import mobsoftlab.model.ChatMessage; import mobsoftlab.model.ChatRoom; public class SugarOrmRepository implements Repository { @Override public void open(Context context) { SugarContext.init(context); } @Override public void close() { SugarContext.terminate(); } @Override public List<ChatRoom> getChatRooms() { return SugarRecord.listAll(ChatRoom.class); } @Override public void addChatRoom(ChatRoom chatRoom) { SugarRecord.saveInTx(chatRoom); } @Override public List<ChatMessage> getChatMessages(ChatRoom chatRoom) { return SugarRecord.find(ChatMessage.class, "chatRoom = ?", chatRoom.getId().toString()); } @Override public void addChatMessage(ChatRoom chatRoom, ChatMessage chatMessage) { chatMessage.setChatRoom(chatRoom); SugarRecord.saveInTx(chatMessage); } }
gpl-3.0
nicolaskruchten/OpenMyEWB
WEB-INF/src/ca/myewb/frame/StickyMessage.java
1215
/* This file is part of OpenMyEWB. OpenMyEWB 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. OpenMyEWB 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 OpenMyEWB. If not, see <http://www.gnu.org/licenses/>. OpenMyEWB is Copyright 2005-2009 Nicolas Kruchten (nicolas@kruchten.com), Francis Kung, Engineers Without Borders Canada, Michael Trauttmansdorff, Jon Fishbein, David Kadish */ package ca.myewb.frame; public class StickyMessage extends Message { private boolean groupMsg; public boolean isGroupMsg() { return groupMsg; } public void setGroupMsg(boolean groupMsg) { this.groupMsg = groupMsg; } public StickyMessage(String m, boolean groupMsg) { super(m); sticky = true; this.groupMsg = groupMsg; } }
gpl-3.0
gergob/reactNativeSamples
rnNavigator/android/app/src/main/java/com/rnnavigator/MainActivity.java
367
package com.rnnavigator; import com.facebook.react.ReactActivity; public class MainActivity extends ReactActivity { /** * Returns the name of the main component registered from JavaScript. * This is used to schedule rendering of the component. */ @Override protected String getMainComponentName() { return "rnNavigator"; } }
gpl-3.0
tpfinal-pp1/tp-final
src/main/java/com/TpFinal/data/dao/DAOCitaImpl.java
302
package com.TpFinal.data.dao; import com.TpFinal.data.dao.interfaces.DAOCita; import com.TpFinal.data.dao.interfaces.DAOContratoDuracion; import com.TpFinal.dto.cita.Cita; public class DAOCitaImpl extends DAOImpl<Cita> implements DAOCita{ public DAOCitaImpl() { super(Cita.class); } }
gpl-3.0
McNetic/peris
app/src/main/java/de/enlightened/peris/CategoriesFragment.java
35710
/* * Copyright (C) 2014 - 2015 Initial Author * Copyright (C) 2017 Nicolai Ehemann * * This file is part of Peris. * * Peris 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. * * Peris 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 Peris. If not, see <http://www.gnu.org/licenses/>. * */ package de.enlightened.peris; import android.annotation.SuppressLint; import android.content.Intent; import android.content.SharedPreferences; import android.os.AsyncTask; import android.os.AsyncTask.Status; import android.os.Bundle; import android.support.v4.app.FragmentActivity; import android.support.v4.app.ListFragment; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AbsListView; import android.widget.AbsListView.OnScrollListener; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.Toast; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import java.util.List; import de.enlightened.peris.api.ApiResult; import de.enlightened.peris.site.Category; import de.enlightened.peris.site.Config; import de.enlightened.peris.site.Topic; import de.enlightened.peris.site.TopicItem; import de.enlightened.peris.support.CacheService; import de.enlightened.peris.support.Net; @SuppressLint("NewApi") public class CategoriesFragment extends ListFragment { private static final String TAG = CategoriesFragment.class.getName(); private static final int CATEGORIES_PER_PAGE = 20; private String serverAddress; private String subforumId = null; private String background; private String userid; private TopicItem clickedTopicItem; private String storagePrefix = ""; private DownloadCategoriesTask categoriesDownloader; private PerisApp application; private String searchQuery = ""; private String passedSubforum = ""; private String screenTitle; private String screenSubtitle; private int startingPos = 0; private int endingPos = CATEGORIES_PER_PAGE; private boolean canScrollMoreThreads = true; private boolean isExtraScrolling = false; private boolean isLoading = false; private boolean initialLoadComplete = false; private String[] subforumParts; private URL shareURL = null; private FragmentActivity activity; private String totalHash; private List<TopicItem> categoryList; private boolean initialParseDone = false; private TopicItemSelectedListener categorySelected = null; private OnScrollListener listScrolled = new OnScrollListener() { @Override public void onScroll(final AbsListView arg0, final int arg1, final int arg2, final int arg3) { //do nothing } @Override @SuppressWarnings("checkstyle:requirethis") public void onScrollStateChanged(final AbsListView arg0, final int arg1) { if (canScrollMoreThreads && !isLoading && categoryList != null && categoryList.size() >= CATEGORIES_PER_PAGE && initialLoadComplete && arg1 == SCROLL_STATE_IDLE && arg0.getLastVisiblePosition() >= categoryList.size() - 5) { isExtraScrolling = true; startingPos = endingPos + 1; endingPos = startingPos + CATEGORIES_PER_PAGE; categoriesDownloader = new DownloadCategoriesTask(); categoriesDownloader.execute(); } } }; @Override public final void onCreate(final Bundle bundle) { super.onCreate(bundle); this.activity = (FragmentActivity) getActivity(); this.application = (PerisApp) this.activity.getApplication(); if (this.activity != null) { if (this.activity.getActionBar() != null) { if (this.activity.getActionBar().getSubtitle() != null) { this.screenSubtitle = this.activity.getActionBar().getSubtitle().toString(); } } } setHasOptionsMenu(true); } @Override public final View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { return super.onCreateView(inflater, container, savedInstanceState); } @Override public final void onStart() { super.onStart(); if (!(this.application.getSession().getServer().serverBackground.contentEquals(this.application.getSession().getServer().serverBoxColor) && this.application.getSession().getServer().serverBoxBorder.contentEquals("0"))) { getListView().setDivider(null); } final Bundle bundle = getArguments(); this.subforumId = bundle.getString("subforum_id"); this.background = bundle.getString("background"); this.screenTitle = bundle.getString("subforum_name"); this.passedSubforum = this.subforumId; if (bundle.containsKey("query")) { this.searchQuery = bundle.getString("query"); } //Log.i(TAG, "**** New CategoriesFragment Instance ****"); //Log.d(TAG, "Passed subforum " + this.subforumId); this.totalHash = this.subforumId; if (this.subforumId.contains("###")) { this.subforumParts = this.subforumId.split("###"); Log.d(TAG, "Subforum has " + this.subforumParts.length + " parts."); this.subforumId = this.subforumParts[0]; //hashId = subforumParts[1]; } else { this.subforumParts = new String[1]; this.subforumParts[0] = this.subforumId; } Log.d(TAG, "Entering subforum " + this.subforumId); this.serverAddress = this.application.getSession().getServer().serverAddress; if (getString(R.string.server_location).contentEquals("0")) { this.storagePrefix = this.serverAddress + "_"; } this.userid = this.application.getSession().getServer().serverUserId; final String shareId = this.subforumId; if (shareId.contentEquals("0")) { this.shareURL = this.application.getSession().getServer().getURL(); } else { if (this.application.getSession().getApi().getConfig().getForumSystem() == Config.ForumSystem.PHPBB) { this.shareURL = this.application.getSession().getServer().getURL("viewforum.php?f=" + shareId); } } getListView().setOnScrollListener(this.listScrolled); } @Override public final void onPause() { if (!this.subforumId.contentEquals("unread") && !this.subforumId.contentEquals("participated") && !this.subforumId.contentEquals("userrecent") && !this.subforumId.contentEquals("favs") && !this.subforumId.contentEquals("search") && !this.subforumId.contentEquals("forum_favs")) { final String scrollY = Integer.toString(getListView().getFirstVisiblePosition()); final SharedPreferences appPreferences = this.activity.getSharedPreferences("prefs", 0); final SharedPreferences.Editor editor = appPreferences.edit(); editor.putString(this.storagePrefix + "forumScrollPosition" + this.passedSubforum, scrollY); editor.commit(); } this.endCurrentlyRunning(); super.onPause(); } @Override public final void onResume() { //Log.d(TAG,"CF OnResume Began"); this.activity.getActionBar().setTitle(this.screenTitle); this.activity.getActionBar().setSubtitle(this.screenSubtitle); //activity.getActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); final ResultObject forumObject = (ResultObject) CacheService.readObject(CategoriesFragment.this.getContext(), "forums/" + this.storagePrefix + "forum" + this.subforumId); if (forumObject != null) { try { this.parseCachedForums(forumObject); Log.d(TAG, "Forum cache available, using it"); } catch (Exception ex) { if (ex.getMessage() != null) { Log.e(TAG, ex.getMessage()); } } } this.loadCategories(); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) { this.activity.invalidateOptionsMenu(); } Log.d(TAG, "CF OnResume Completed"); super.onResume(); } private void endCurrentlyRunning() { //Stop any running tasks if (this.categoriesDownloader != null) { if (this.categoriesDownloader.getStatus() == Status.RUNNING) { this.categoriesDownloader.cancel(true); Log.i(TAG, "Killed Currently Running"); } } } @Override public final void onStop() { super.onStop(); this.endCurrentlyRunning(); } private void loadCategories() { Log.d(TAG, "CF Starting loadCategories"); this.endCurrentlyRunning(); this.categoriesDownloader = new DownloadCategoriesTask(); if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) { this.categoriesDownloader.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR); } else { this.categoriesDownloader.execute(); } } /* private void setChatThread() { application.getSession().getServer().chatThread = clickedTopicItem.id; application.getSession().getServer().chatForum = clickedTopicItem.subforumId; application.getSession().getServer().chatName = clickedTopicItem.name; application.getSession().updateServer(); chatChanged.onChatChanged(application.getSession().getServer().chatThread); } */ @SuppressWarnings("rawtypes") private void parseCachedForums(final ResultObject result) { Log.d(TAG, "parseCachedForums()"); if (this.categoryList == null || !this.isExtraScrolling) { this.categoryList = new ArrayList<>(); } int retainedPosition = getListView().getFirstVisiblePosition(); if (!this.initialParseDone) { final SharedPreferences appPreferences = this.activity.getSharedPreferences("prefs", 0); final String savedForumPosition = appPreferences.getString(this.storagePrefix + "forumScrollPosition" + this.passedSubforum, "0"); retainedPosition = Integer.parseInt(savedForumPosition); } //Announcement Topics if (result.announcementTopics != null) { //this.categoryList.add(result.announcementTopics); this.categoryList.addAll(result.announcementTopics.getTopics()); } //Sticky Topics if (result.stickyTopics != null) { this.categoryList.addAll(result.stickyTopics.getTopics()); } Log.d(TAG, "Starting category parse! " + this.subforumId); //Forums if (result.categories != null) { this.categoryList.addAll(result.categories.get(this.subforumId).getChildren()); } /* if (result.categories != null) { ArrayList<CategoryOld> forumz = CategoryParser.parseCategories(result.categories, this.subforumId, this.background); Log.d(TAG, "Forums parsed!"); String currentHash = this.subforumParts[0]; Log.d(TAG, "Hash Size: " + this.subforumParts.length); if (this.subforumParts.length == 1) { for (CategoryOld c : forumz) { this.categoryList.add(c); } } else { for (int i = 1; i < this.subforumParts.length; i++) { currentHash = currentHash + "###" + this.subforumParts[i]; Log.d(TAG, "Checking hash: " + currentHash + " (total hash is " + this.totalHash + ")"); ArrayList<CategoryOld> tempForums = null; for (CategoryOld c : forumz) { if (c.children != null && c.id.contentEquals(currentHash)) { tempForums = c.children; } } if (tempForums != null) { forumz = tempForums; if (currentHash.contentEquals(this.totalHash)) { for (CategoryOld c : forumz) { this.categoryList.add(c); } } } } } }*/ Log.d(TAG, "Finished category parse!"); //Non-Sticky Topics if (result.defaultTopics == null) { this.canScrollMoreThreads = false; } else { this.categoryList.addAll(result.defaultTopics.getTopics()); } if (result.favoriteTopics != null) { Log.i(TAG, "We have some favs!"); this.categoryList.addAll(result.favoriteTopics); } setListAdapter(new CategoryAdapter(this.categoryList, this.activity, this.application)); registerForContextMenu(getListView()); getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override @SuppressWarnings("checkstyle:requirethis") public void onItemClick(final AdapterView<?> parent, final View view, final int position, final long id) { final TopicItem topicItem = (TopicItem) parent.getItemAtPosition(position); if (topicItem != null && categorySelected != null) { categorySelected.onTopicItemSelected(topicItem); } } }); getListView().setSelection(retainedPosition); this.initialParseDone = true; } /*private CategoryOld createCategoryFromTopics(final Map topicMap, final boolean subforum, final boolean sticky) { final CategoryOld ca = new CategoryOld(); ca.name = new String((byte[]) topicMap.get("topic_title")); if (subforum && topicMap.get("forum_id") != null) { ca.subforumId = (String) topicMap.get("forum_id"); } else { ca.subforumId = this.subforumId; //if(!hashId.contentEquals("0")) { // ca.subforumId = hashId; //} } ca.id = (String) topicMap.get("topic_id"); ca.lastUpdate = (Date) topicMap.get("last_reply_time"); if (!subforum || topicMap.get("topic_author_name") != null) { ca.lastThread = new String((byte[]) topicMap.get("topic_author_name")); } else { ca.lastThread = new String((byte[]) topicMap.get("forum_name")); } if (sticky) { ca.topicSticky = "Y"; } ca.type = "C"; ca.color = this.background; if (topicMap.get("reply_number") != null) { ca.threadCount = topicMap.get("reply_number").toString().replace(".0", ""); } if (topicMap.get("view_number") != null) { ca.viewCount = topicMap.get("view_number").toString().replace(".0", ""); } if (topicMap.get("new_post") != null) { ca.hasNewTopic = (Boolean) topicMap.get("new_post"); } if (topicMap.get("is_closed") != null) { ca.isLocked = (Boolean) topicMap.get("is_closed"); } if (topicMap.containsKey("icon_url")) { if (topicMap.get("icon_url") != null) { ca.icon = (String) topicMap.get("icon_url"); } } if (topicMap.get("can_stick") != null) { ca.canSticky = (Boolean) topicMap.get("can_stick"); } if (topicMap.get("can_delete") != null) { ca.canDelete = (Boolean) topicMap.get("can_delete"); } if (topicMap.get("can_close") != null) { ca.canLock = (Boolean) topicMap.get("can_close"); } return ca; }*/ public final void onCreateContextMenu(final ContextMenu menu, final View v, final ContextMenuInfo menuInfo) { final String serverUserId = this.application.getSession().getServer().serverUserId; final AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; this.clickedTopicItem = (TopicItem) CategoriesFragment.this.getListView().getItemAtPosition(info.position); if (serverUserId == null) { return; } super.onCreateContextMenu(menu, v, menuInfo); menu.setHeaderTitle(this.clickedTopicItem.getHeading()); final MenuInflater inflater = this.activity.getMenuInflater(); inflater.inflate(R.menu.categories_context, menu); final MenuItem ubsubItem = menu.findItem(R.id.categories_unsubscribe); final MenuItem subItem = menu.findItem(R.id.categories_subscribe); final MenuItem stickyItem = menu.findItem(R.id.categories_context_sticky); final MenuItem lockItem = menu.findItem(R.id.categories_context_lock); final MenuItem deleteItem = menu.findItem(R.id.categories_context_delete); final MenuItem subscribeItem = menu.findItem(R.id.categories_add_favorite); final MenuItem unsubscribeItem = menu.findItem(R.id.categories_remove_favorite); if (this.clickedTopicItem instanceof Category) { final Category category = (Category) this.clickedTopicItem; ubsubItem.setVisible(false); subItem.setVisible(false); stickyItem.setVisible(false); lockItem.setVisible(false); deleteItem.setVisible(false); if (category.isCanSubscribe()) { subscribeItem.setVisible(true); } else { subscribeItem.setVisible(false); } if (category.isSubscribed()) { unsubscribeItem.setVisible(true); subscribeItem.setVisible(false); } else { unsubscribeItem.setVisible(false); } } else { final Topic topic = (Topic) this.clickedTopicItem; unsubscribeItem.setVisible(false); subscribeItem.setVisible(false); if (topic.isCanStick()) { stickyItem.setVisible(true); if (Topic.Type.Sticky == topic.getType()) { stickyItem.setTitle("Unstick Topic"); } else { stickyItem.setTitle("Stick Topic"); } } else { stickyItem.setVisible(false); } if (topic.isCanDelete()) { deleteItem.setVisible(true); } else { deleteItem.setVisible(false); } if (topic.isCanClose()) { lockItem.setVisible(true); if (topic.isClosed()) { lockItem.setTitle("Unlock Topic"); } else { lockItem.setTitle("Lock Topic"); } } else { lockItem.setVisible(false); } if (this.subforumId.contentEquals("favs")) { ubsubItem.setVisible(true); subItem.setVisible(false); } else { ubsubItem.setVisible(false); subItem.setVisible(true); } } } public final boolean onContextItemSelected(final MenuItem item) { switch (item.getItemId()) { case R.id.categories_unsubscribe: new UnsubscribeTopicTask().execute(this.clickedTopicItem.getId()); break; case R.id.categories_subscribe: new SubscribeTopicTask().execute(this.clickedTopicItem.getId()); break; case R.id.categories_context_sticky: if (this.clickedTopicItem instanceof Topic) { if (Topic.Type.Sticky == ((Topic) this.clickedTopicItem).getType()) { new StickyTopicTask().execute(this.clickedTopicItem.getId(), "2"); } else { new StickyTopicTask().execute(this.clickedTopicItem.getId(), "1"); } } break; case R.id.categories_context_lock: if (this.clickedTopicItem instanceof Topic) { final Topic topic = (Topic) this.clickedTopicItem; if (((Topic) this.clickedTopicItem).isClosed()) { new LockTopicTask().execute(this.clickedTopicItem.getId(), "1"); } else { new LockTopicTask().execute(this.clickedTopicItem.getId(), "2"); } } break; case R.id.categories_context_delete_yes: new DeleteTopicTask().execute(this.clickedTopicItem.getId()); break; case R.id.categories_add_favorite: new AddToFavoritesTask().execute(this.clickedTopicItem.getId()); break; case R.id.categories_remove_favorite: new RemoveFromFavoritesTask().execute(this.clickedTopicItem.getId()); break; default: return super.onContextItemSelected(item); } return true; } @SuppressLint("NewApi") @Override public final void onCreateOptionsMenu(final Menu menu, final MenuInflater inflater) { if (this.userid != null) { inflater.inflate(R.menu.categories_menu, menu); } super.onCreateOptionsMenu(menu, inflater); } @Override public final void onPrepareOptionsMenu(final Menu menu) { super.onPrepareOptionsMenu(menu); if ((this.userid != null) && (menu != null)) { if (this.subforumId == null || this.subforumId.contentEquals("participated") || this.subforumId.contentEquals("favs") || this.subforumId.contentEquals("search")) { final MenuItem item = menu.findItem(R.id.cat_mark_read); if (item != null) { item.setVisible(false); } } else { final MenuItem item = menu.findItem(R.id.cat_mark_read); if (item != null) { if (ThemeSetter.getForegroundDark(this.background)) { item.setIcon(R.drawable.ic_action_read_dark); } } } if (this.subforumId == null || this.subforumId.contentEquals("participated") || this.subforumId.contentEquals("favs") || this.subforumId.contentEquals("userrecent") || this.subforumId.contentEquals("search")) { final MenuItem item2 = menu.findItem(R.id.cat_new_thread); if (item2 != null) { item2.setVisible(false); } } else { final MenuItem item2 = menu.findItem(R.id.cat_new_thread); if (item2 != null) { if (ThemeSetter.getForegroundDark(this.background)) { item2.setIcon(R.drawable.ic_action_new_dark); } } } final MenuItem browserItem = menu.findItem(R.id.cat_open_browser); if (this.shareURL == null) { browserItem.setVisible(false); } else { browserItem.setVisible(true); } } } @Override public final boolean onOptionsItemSelected(final MenuItem item) { switch (item.getItemId()) { case R.id.cat_new_thread: this.startPost(); break; case R.id.cat_mark_read: this.markAsRead(); break; case R.id.cat_open_browser: final Intent browserIntent = new Intent(Intent.ACTION_VIEW, Net.uriFromURL(this.shareURL)); this.startActivity(browserIntent); break; default: return super.onOptionsItemSelected(item); } return true; } private void startPost() { if (this.subforumId == null || this.userid == null) { final Toast toast = Toast.makeText(this.activity, "You are not allowed to post here!", Toast.LENGTH_LONG); toast.show(); return; } final Intent myIntent = new Intent(this.activity, NewPost.class); final Bundle bundle = new Bundle(); bundle.putString("postid", (String) "0"); bundle.putString("parent", (String) "0"); bundle.putString("category", (String) this.subforumId); bundle.putString("subforum_id", (String) this.subforumId); bundle.putString("original_text", (String) ""); bundle.putString("boxTitle", (String) "New Thread"); bundle.putString("picture", (String) "0"); bundle.putString("subject", (String) ""); bundle.putString("post_type", NewPost.Type.NewThread.name()); bundle.putString("color", (String) this.background); myIntent.putExtras(bundle); startActivity(myIntent); } public final void setOnCategorySelectedListener(final TopicItemSelectedListener l) { this.categorySelected = l; } private void markAsRead() { new ReadMarkerTask().execute(this.subforumId); } //Category Selected Interface public interface TopicItemSelectedListener { void onTopicItemSelected(TopicItem category); } private class DownloadCategoriesTask extends AsyncTask<String, Void, ResultObject> { @Override protected void onPreExecute() { super.onPreExecute(); } @SuppressLint("UseValueOf") @SuppressWarnings({"unchecked", "rawtypes", "checkstyle:requirethis"}) @Override protected ResultObject doInBackground(final String... params) { Log.i(TAG, "DownloadCategoriesTask doInBackground subforumId " + subforumId); if (activity == null) { Log.e(TAG, "Category activity is null!"); return null; } isLoading = true; final ResultObject result = new ResultObject(); if (subforumId.contentEquals("favs")) { //Handle subscription category result.defaultTopics = application.getSession().getApi().getSubscribedTopics(subforumId, startingPos, endingPos); } else if (subforumId.contentEquals("forum_favs")) { //Handle favorites category result.favoriteTopics = application.getSession().getApi().getSubscribedCategories(); } else if (subforumId.contentEquals("participated")) { //Handle participated topics category result.defaultTopics = application.getSession().getApi().getParticipatedTopics(subforumId, startingPos, endingPos); } else if (subforumId.contentEquals("search")) { //Handle topic listing for the Search function result.defaultTopics = application.getSession().getApi().searchTopic(subforumId, searchQuery, startingPos, endingPos); } else if (subforumId.contentEquals("timeline")) { //Handle timeline result.defaultTopics = application.getSession().getApi().getLatestTopics(subforumId, startingPos, endingPos); } else if (subforumId.contentEquals("unread")) { //Handle topic listing for the Unread category if (!isExtraScrolling) { //TODO: paging? result.defaultTopics = application.getSession().getApi().getUnreadTopics(subforumId); } } else if (!subforumId.contentEquals("userrecent")) { //Do not get a forum listing if we are inside one of the special sections if (!isExtraScrolling) { final String topicId; if (subforumId != null && !Category.ROOT_ID.equals(subforumId)) { result.categories = CategoriesFragment.this.application.getSession().getApi().getCategory(subforumId); topicId = subforumId; } else { result.categories = CategoriesFragment.this.application.getSession().getApi().getCategories(); topicId = "-1"; } //First grab any announcement topics result.announcementTopics = CategoriesFragment.this.application.getSession().getApi().getTopics(topicId, 0, CATEGORIES_PER_PAGE, Topic.Type.Announcement); //Then grab any sticky topics result.stickyTopics = CategoriesFragment.this.application.getSession().getApi().getTopics(topicId, 0, CATEGORIES_PER_PAGE, Topic.Type.Sticky); } //Grab the non-sticky topics Log.d(TAG, "Getting topics " + startingPos + " through " + endingPos); result.defaultTopics = CategoriesFragment.this.application.getSession().getApi().getTopics(subforumId, startingPos, endingPos); } return result; } @SuppressWarnings("checkstyle:requirethis") protected void onPostExecute(final ResultObject result) { Log.i(TAG, "DownloadCategoriesTask onPostExecute"); if (activity != null) { if (result == null) { final Toast toast = Toast.makeText(activity, "Error pulling data from the server, ecCFDL", Toast.LENGTH_SHORT); toast.show(); } else { Log.i(TAG, "Received category data!"); initialLoadComplete = true; isLoading = false; final ResultObject cachedForum = (ResultObject) CacheService.readObject(CategoriesFragment.this.getContext(), "forums/" + storagePrefix + "forum" + subforumId); if (!result.equals(cachedForum)) { if (!isExtraScrolling) { try { CacheService.writeObject(CategoriesFragment.this.getContext(), "forums/" + storagePrefix + "forum" + subforumId, result); } catch (IOException e) { Log.e(TAG, "Error writing forum cache (" + e.getMessage() + ")\n" + e); } } parseCachedForums(result); Log.i(TAG, "Found " + CategoriesFragment.this.categoryList.size() + " categories"); } /* final String objectString = GsonHelper.CUSTOM_GSON.toJson(result); final SharedPreferences appPreferences = activity.getSharedPreferences("prefs", 0); final String cachedForum = appPreferences.getString(storagePrefix + "forum" + subforumId, "n/a"); if (!objectString.contentEquals(cachedForum)) { if (!isExtraScrolling) { final SharedPreferences.Editor editor = appPreferences.edit(); editor.putString(storagePrefix + "forum" + subforumId, objectString); editor.commit(); } final Object[][] forumObject = GsonHelper.CUSTOM_GSON.fromJson(objectString, Object[][].class); parseCachedForums(result); } */ } } } } private class ReadMarkerTask extends AsyncTask<String, Void, ApiResult> { @SuppressWarnings({"unchecked", "rawtypes"}) @Override protected ApiResult doInBackground(final String... params) { final ApiResult result; if (CategoriesFragment.this.activity != null) { if (!"0".equals(params[0]) && !"unread".equals(params[0])) { result = CategoriesFragment.this.application.getSession().getApi().markForumTopicsRead(params[0]); } else { result = CategoriesFragment.this.application.getSession().getApi().markAllTopicsRead(); } } else { result = null; } return result; } protected void onPostExecute(final ApiResult result) { if (CategoriesFragment.this.activity != null) { if (CategoriesFragment.this.subforumId.equals("unread")) { CategoriesFragment.this.activity.finish(); } else { CategoriesFragment.this.loadCategories(); final Toast toast = Toast.makeText(CategoriesFragment.this.activity, "Posts marked read!", Toast.LENGTH_LONG); toast.show(); } } } } private class SubscribeTopicTask extends AsyncTask<String, Void, ApiResult> { @SuppressWarnings({"unchecked", "rawtypes"}) @Override protected ApiResult doInBackground(final String... params) { final ApiResult result; if (CategoriesFragment.this.activity != null) { result = CategoriesFragment.this.application.getSession().getApi().subscribeTopic(params[0]); } else { result = null; } return result; } protected void onPostExecute(final ApiResult result) { if (CategoriesFragment.this.activity != null) { final Toast toast = Toast.makeText(CategoriesFragment.this.activity, "Subscribed!", Toast.LENGTH_SHORT); toast.show(); } } } private class UnsubscribeTopicTask extends AsyncTask<String, Void, ApiResult> { @SuppressWarnings({"unchecked", "rawtypes"}) @Override protected ApiResult doInBackground(final String... params) { final ApiResult result; if (CategoriesFragment.this.activity != null) { result = CategoriesFragment.this.application.getSession().getApi().unsubscribeTopic(params[0]); } else { result = null; } return result; } protected void onPostExecute(final ApiResult result) { if (CategoriesFragment.this.activity != null) { CategoriesFragment.this.loadCategories(); } } } private class StickyTopicTask extends AsyncTask<String, Void, ApiResult> { // parm[0] - (string)topic_id // parm[1] - (int)mode (1 - stick; 2 - unstick) @SuppressWarnings({"unchecked", "rawtypes"}) @Override protected ApiResult doInBackground(final String... params) { final ApiResult result; if (CategoriesFragment.this.activity != null) { if ("1".equals(params[1])) { result = CategoriesFragment.this.application.getSession().getApi().setTopicSticky(params[0], true); } else { result = CategoriesFragment.this.application.getSession().getApi().setTopicSticky(params[0], false); } } else { result = null; } return result; } protected void onPostExecute(final ApiResult result) { if (CategoriesFragment.this.activity != null) { CategoriesFragment.this.loadCategories(); } } } private class LockTopicTask extends AsyncTask<String, Void, ApiResult> { // parm[0] - (string)topic_id // parm[1] - (int)mode (1 - unlock; 2 - lock) @SuppressWarnings({"unchecked", "rawtypes"}) @Override protected ApiResult doInBackground(final String... params) { final ApiResult result; if (CategoriesFragment.this.activity != null) { if ("1".equals(params[1])) { result = CategoriesFragment.this.application.getSession().getApi().setTopicLocked(params[0], false); } else { result = CategoriesFragment.this.application.getSession().getApi().setTopicLocked(params[0], true); } } else { result = null; } return result; } protected void onPostExecute(final ApiResult result) { if (CategoriesFragment.this.activity != null) { CategoriesFragment.this.loadCategories(); } } } private class DeleteTopicTask extends AsyncTask<String, Void, ApiResult> { // parm[0] - (string)topic_id @SuppressLint("UseValueOf") @SuppressWarnings({"unchecked", "rawtypes"}) @Override protected ApiResult doInBackground(final String... params) { final ApiResult result; if (CategoriesFragment.this.activity != null) { result = CategoriesFragment.this.application.getSession().getApi().deleteTopic(params[0]); } else { result = null; } return result; } protected void onPostExecute(final ApiResult result) { if (CategoriesFragment.this.activity != null && result.isSuccess()) { CategoriesFragment.this.loadCategories(); } } } private class AddToFavoritesTask extends AsyncTask<String, Void, ApiResult> { @SuppressLint("UseValueOf") @SuppressWarnings({"unchecked", "rawtypes"}) @Override protected ApiResult doInBackground(final String... params) { final ApiResult result; if (CategoriesFragment.this.activity != null) { result = CategoriesFragment.this.application.getSession().getApi().subscribeCategory(params[0]); } else { result = null; } return result; } protected void onPostExecute(final ApiResult result) { if (CategoriesFragment.this.activity != null && result.isSuccess()) { final Toast toast = Toast.makeText(CategoriesFragment.this.activity, "Category added to favorites!", Toast.LENGTH_SHORT); toast.show(); CategoriesFragment.this.loadCategories(); } } } private class RemoveFromFavoritesTask extends AsyncTask<String, Void, ApiResult> { @SuppressLint("UseValueOf") @SuppressWarnings({"unchecked", "rawtypes"}) @Override protected ApiResult doInBackground(final String... params) { final ApiResult result; if (CategoriesFragment.this.activity != null) { result = CategoriesFragment.this.application.getSession().getApi().unsubscribeCategory(params[0]); } else { result = null; } return result; } protected void onPostExecute(final ApiResult result) { if (CategoriesFragment.this.activity != null && result.isSuccess()) { final Toast toast = Toast.makeText(CategoriesFragment.this.activity, "Category removed to favorites!", Toast.LENGTH_SHORT); toast.show(); CategoriesFragment.this.loadCategories(); } } } }
gpl-3.0
sangjw/99work
src/main/java/com/sjw/dwetl/controller/FileUpload.java
3283
package com.sjw.dwetl.controller; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Enumeration; import java.util.Iterator; import java.util.UUID; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.shiro.SecurityUtils; import org.apache.shiro.authc.UsernamePasswordToken; import org.apache.shiro.authz.annotation.RequiresAuthentication; import org.apache.shiro.authz.annotation.RequiresPermissions; import org.apache.shiro.authz.annotation.RequiresUser; import org.apache.shiro.subject.Subject; import org.springframework.stereotype.Controller; import org.springframework.util.StringUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest; import org.springframework.web.servlet.ModelAndView; import com.sjw.dwetl.po.Result; import net.sf.json.JSONObject; @RequiresUser @RequiresAuthentication @Controller @RequestMapping("/upload") public class FileUpload extends BaseController{ private static final Log logger = LogFactory.getLog(FileUpload.class); //用户登录 @RequiresPermissions("/upload/file") @RequestMapping(value="/file",method=RequestMethod.PUT) @ResponseBody public JSONObject updateItems(HttpServletRequest request, HttpServletResponse response) throws IOException { Enumeration<String> e = request.getHeaderNames(); while(e.hasMoreElements()){ String headerName = e.nextElement();//透明j称 Enumeration<String> headerValues = request.getHeaders(headerName); while(headerValues.hasMoreElements()){ System.out.println(headerName+":"+headerValues.nextElement()); } } String filename=new String(request.getHeader("filename").getBytes("iso-8859-1"),"gbk"); int pos=filename.lastIndexOf("\\"); pos=pos<0?0:pos+1; FileOutputStream outputStream = new FileOutputStream("c:\\tmp\\"+filename.substring(pos)); byte[] bytes = new byte[4096]; int bytesWritten = 0; int byteCount = 0; while ((byteCount = request.getInputStream().read(bytes)) != -1) { outputStream.write(bytes, 0, byteCount); bytesWritten += byteCount; } outputStream.close(); int ret=0; Result result=new Result(); if(ret==0) { result.setRet(0); result.setMsg("success"); } else{ result.setRet(1); result.setMsg("fail"); } return JSONObject.fromObject(result); } }
gpl-3.0
elfrasco/dependency-injection
dependency-injection-javaee/src/main/java/com/epidata/talks/dependencyinjection/javaee/dao/ProjectDAOImpl.java
682
package com.epidata.talks.dependencyinjection.javaee.dao; import javax.inject.Singleton; import com.epidata.talks.dependencyinjection.base.dao.ProjectDAO; import com.epidata.talks.dependencyinjection.model.Project; import com.epidata.talks.dependencyinjection.model.repository.JSONProjectRepository; import com.epidata.talks.dependencyinjection.model.repository.ProjectRepository; @Singleton public class ProjectDAOImpl implements ProjectDAO { private ProjectRepository projectRepository; public ProjectDAOImpl() { projectRepository = new JSONProjectRepository(); } @Override public Project findByName(String name) { return projectRepository.findByName(name); } }
gpl-3.0
agkphysics/ChatBot
JavaBot/src/main/java/jcolibri/method/retrieve/NNretrieval/similarity/local/MaxString.java
2192
package jcolibri.method.retrieve.NNretrieval.similarity.local; import jcolibri.method.retrieve.NNretrieval.similarity.LocalSimilarityFunction; /** * This function returns a similarity value depending of the biggest substring * that belong to both strings. */ public class MaxString implements LocalSimilarityFunction { /** * Applies the similarity function. * * @param s * String. * @param t * String. * @return result of apply the similarity funciton. */ @Override public double compute(Object s, Object t) throws jcolibri.exception.NoApplicableSimilarityFunctionException { if ((s == null) || (t == null)) return 0; if (!(s instanceof java.lang.String)) throw new jcolibri.exception.NoApplicableSimilarityFunctionException(this.getClass(), s.getClass()); if (!(t instanceof java.lang.String)) throw new jcolibri.exception.NoApplicableSimilarityFunctionException(this.getClass(), s.getClass()); String news = (String)s; String newt = (String)t; if (news.equals(newt)) return 1.0; else return ((double)MaxSubString(news, newt) / (double)Math.max(news.length(), newt.length())); } /** Applicable to String */ @Override public boolean isApplicable(Object o1, Object o2) { if ((o1 == null) && (o2 == null)) return true; else if (o1 == null) return o2 instanceof String; else if (o2 == null) return o1 instanceof String; else return (o1 instanceof String) && (o2 instanceof String); } /** * Returns the length of the biggest substring that belong to both strings. * * @param s * @param t * @return */ private int MaxSubString(String s, String t) { String shorter = (s.length() > t.length()) ? t : s; String longer = (shorter.equals(s)) ? t : s; int best = 0; for (int i = 0; i < shorter.length(); i++) { for (int j = shorter.length(); j > i; j--) { if (longer.indexOf(shorter.substring(i, j)) != -1) best = Math.max(best, j - i); } } return best; } }
gpl-3.0
saltisgood/open-android
OpenAndroid/src/main/java/com/nickstephen/openandroid/components/SubClassListFrag.java
14182
package com.nickstephen.openandroid.components; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.Toast; import com.nickstephen.lib.Twig; import com.nickstephen.lib.gui.ExpandableListFragment; import com.nickstephen.lib.gui.Fragment; import com.nickstephen.lib.misc.StatMethods; import com.nickstephen.openandroid.OpenAndroid; import com.nickstephen.openandroid.R; import com.nickstephen.openandroid.misc.TypeHelpers; import com.nickstephen.openandroid.misc.Types; import com.nickstephen.openandroid.util.BaseExpandableListAdapter; import com.nickstephen.openandroid.util.Constants; import org.holoeverywhere.LayoutInflater; import org.holoeverywhere.widget.ExpandableListView; import org.holoeverywhere.widget.TextView; import java.lang.annotation.Annotation; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; /** * Child fragment class that is used to navigate the inside of a class */ public class SubClassListFrag extends ExpandableListFragment { public static final String FRAG_TAG = "com.nickstephen.openandroid.components.SubClassListFrag"; private static final String TYPE_KEY = "type_key"; private Class<?> mClass; private String mClassName; private Class<?>[] mInterfaces; private Annotation[] mAnnotations; private Class<?>[] mInnerClasses; private Constructor<?>[] mConstructors; private Field[] mFields; private Method[] mMethods; private Class<?> mSuperClass; private Types mClassType; private ClassBrowserFrag mParentFrag; private LayoutInflater mInflater; public SubClassListFrag() {} @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mParentFrag = (ClassBrowserFrag) this.getParentFragment(); Bundle args = this.getArguments(); if (args != null) { mClassName = args.getString(Constants.CLASS_KEY); } if (mClassName == null) { this.popFragment(); Twig.debug(FRAG_TAG, "mMemberName null"); return; } try { //noinspection ConstantConditions mClass = ((OpenAndroid) this.getSupportApplication()).getPackageContext().getClassLoader().loadClass(mClassName); } catch (ClassNotFoundException e) { e.printStackTrace(); this.popFragment(); return; } if (mClass.isInterface()) { mClassType = Types.INTERFACE; } else if (mClass.isEnum()) { mClassType = Types.ENUM; } else if (mClass.isAnnotation()) { mClassType = Types.ANNOTATION; } else { mClassType = Types.CLASS; } try { mSuperClass = mClass.getSuperclass(); mInterfaces = mClass.getInterfaces(); mAnnotations = mClass.getDeclaredAnnotations(); mInnerClasses = mClass.getDeclaredClasses(); mConstructors = mClass.getDeclaredConstructors(); mMethods = mClass.getDeclaredMethods(); mFields = mClass.getDeclaredFields(); } catch (SecurityException e) { e.printStackTrace(); this.popFragment(); return; } catch (Exception e) { Twig.printStackTrace(e); } if (mParentFrag.shouldIgnoreSynthetics() && mMethods != null) { List<Method> methods = new ArrayList<Method>(); for (Method m : mMethods) { if (!m.isSynthetic()) { methods.add(m); } } mMethods = methods.toArray(new Method[methods.size()]); } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { mInflater = inflater; mParentFrag.setType(mClassType); mParentFrag.setHeaderText(TypeHelpers.printClass(mClass)); View rootView = inflater.inflate(R.layout.subclass_browser_listfrag); this.setListAdapter(new ClassBrowserAdapter(), rootView); if (mClassType == Types.INTERFACE || mClassType == Types.ENUM || mSuperClass == null) { View v = rootView.findViewById(R.id.subclass_header_scrollview); v.setVisibility(View.GONE); v = rootView.findViewById(R.id.subclass_header_divider); v.setVisibility(View.GONE); } else { TextView superText = (TextView) rootView.findViewById(R.id.superclass_text); superText.setText("extends " + mSuperClass.getName()); superText.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { SubClassListFrag frag = new SubClassListFrag(); Bundle args = new Bundle(); args.putString(Constants.CLASS_KEY, mSuperClass.getName()); frag.setArguments(args); SubClassListFrag.this.getFragmentManager().beginTransaction() .setCustomAnimations(R.anim.push_left_in, R.anim.push_left_out, R.anim.push_right_in, R.anim.push_right_out) .replace(R.id.package_browser_frag_container, frag, SubClassListFrag.FRAG_TAG) .addToBackStack(SubClassListFrag.FRAG_TAG).commit(); } }); } this.getListView().setOnChildClickListener(mListChildClickListener); this.getListView().setOnChildLongClickListener(mChildLongClickL); return rootView; } private void methodClick(int methodNo) { if (mMethods == null || mMethods.length == 0) { StatMethods.hotBread(this.getActivity(), "No methods found", Toast.LENGTH_SHORT); return; } if (methodNo >= mMethods.length || methodNo < 0) { Twig.info(FRAG_TAG, "methodClick: Parameter error - " + methodNo); return; } if (!Modifier.isStatic(mMethods[methodNo].getModifiers())) { StatMethods.hotBread(this.getActivity(), "Non-static methods not supported yet", Toast.LENGTH_SHORT); return; } } /** * Groups: Interfaces, Annotations, Inner Classes, Fields, Constructors, Methods */ private class ClassBrowserAdapter extends BaseExpandableListAdapter<String, Object> { public ClassBrowserAdapter() { } @Override public int getGroupCount() { return 6; } @Override public int getChildrenCount(int groupPosition) { switch (groupPosition) { case 0: return mInterfaces != null ? mInterfaces.length : 0; case 1: return mAnnotations != null ? mAnnotations.length : 0; case 2: return mInnerClasses != null ? mInnerClasses.length : 0; case 3: return mFields != null ? mFields.length : 0; case 4: return mConstructors != null ? mConstructors.length : 0; case 5: return mMethods != null ? mMethods.length : 0; } return 0; } @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { View view = mInflater.inflate(R.layout.group_expandable_list); TextView txt = (TextView) view.findViewById(R.id.text_item); int childCount = getChildrenCount(groupPosition); switch (groupPosition) { case 0: if (mClassType == Types.INTERFACE) { txt.setText("Interfaces Extended (" + childCount + ")"); } else { txt.setText("Implemented Interfaces (" + childCount + ")"); } break; case 1: txt.setText("Annotations (" + childCount + ")"); break; case 2: txt.setText("Inner Classes (" + childCount + ")"); break; case 3: if (mClassType == Types.INTERFACE) { txt.setText("Constants (" + childCount + ")"); } else { txt.setText("Fields (" + childCount + ")"); } break; case 4: txt.setText("Constructors (" + childCount + ")"); break; case 5: default: txt.setText("Methods (" + childCount + ")"); break; } return view; } @Override public Object getChild(int groupPosition, int childPosition) { switch (groupPosition) { case 0: return mInterfaces[childPosition]; case 1: return mAnnotations[childPosition]; case 2: return mInnerClasses[childPosition]; case 3: return mFields[childPosition]; case 4: return mConstructors[childPosition]; case 5: return mMethods[childPosition]; default: return null; } } @Override public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { View view = mInflater.inflate(R.layout.child_expandable_list); TextView txt = (TextView) view.findViewById(R.id.text_item); switch (groupPosition) { case 0: case 2: txt.setText(TypeHelpers.printClass((Class<?>) getChild(groupPosition, childPosition))); break; case 3: txt.setText(TypeHelpers.printField((Field) getChild(groupPosition, childPosition))); break; case 4: txt.setText(TypeHelpers.printConstructor((Constructor<?>) getChild(groupPosition, childPosition))); break; case 5: txt.setText(TypeHelpers.printMethod((Method) getChild(groupPosition, childPosition))); break; default: //noinspection ConstantConditions txt.setText(getChild(groupPosition, childPosition).toString()); break; } return view; } } private final ExpandableListView.OnChildClickListener mListChildClickListener = new ExpandableListView.OnChildClickListener() { @Override public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { if (groupPosition >= 0 && groupPosition <= 2) { Fragment frag = new SubClassListFrag(); Bundle args = new Bundle(); String val = null; int num = 0; switch (groupPosition) { case 0: // Interfaces val = mInterfaces[childPosition].getName(); num = Types.CLASS.ordinal(); break; case 1: // Annotations val = mAnnotations[childPosition].annotationType().getName(); num = Types.ANNOTATION.ordinal(); break; case 2: // Inner Classes val = mInnerClasses[childPosition].getName(); num = Types.CLASS.ordinal(); break; } args.putString(Constants.CLASS_KEY, val); args.putInt(TYPE_KEY, num); frag.setArguments(args); SubClassListFrag.this.getFragmentManager().beginTransaction() .setCustomAnimations(R.anim.push_left_in, R.anim.push_left_out, R.anim.push_right_in, R.anim.push_right_out) .replace(R.id.package_browser_frag_container, frag, SubClassListFrag.FRAG_TAG) .addToBackStack(SubClassListFrag.FRAG_TAG).commit(); return true; } else if (groupPosition >= 3 && groupPosition <= 5) { switch (groupPosition) { case 3: mParentFrag.setNextMember(mFields[childPosition]); break; case 4: mParentFrag.setNextMember(mConstructors[childPosition]); break; case 5: mParentFrag.setNextMember(mMethods[childPosition]); break; } SubClassListFrag.this.getFragmentManager().beginTransaction() .setCustomAnimations(R.anim.push_left_in, R.anim.push_left_out, R.anim.push_right_in, R.anim.push_right_out) .replace(R.id.package_browser_frag_container, new MemberListFrag(), MemberListFrag.FRAG_TAG) .addToBackStack(MemberListFrag.FRAG_TAG) .commit(); return true; } return false; } }; private final ExpandableListView.OnChildLongClickListener mChildLongClickL = new ExpandableListView.OnChildLongClickListener() { @Override public boolean onChildLongClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) { switch (groupPosition) { case 5: methodClick(childPosition); break; } return true; } }; }
gpl-3.0
icgc-dcc/dcc-portal
dcc-portal-server/src/main/java/org/icgc/dcc/portal/server/model/Mutation.java
10443
/* * Copyright 2013(c) The Ontario Institute for Cancer Research. All rights reserved. * * This program and the accompanying materials are made available under the terms of the GNU Public * License v3.0. You should have received a copy of the GNU General Public License along with this * program. If not, see <http://www.gnu.org/licenses/>. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY * WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.icgc.dcc.portal.server.model; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Sets.newHashSet; import static org.icgc.dcc.common.core.util.stream.Collectors.toImmutableList; import static org.icgc.dcc.common.core.util.stream.Collectors.toImmutableSet; import static org.icgc.dcc.portal.server.model.IndexModel.FIELDS_MAPPING; import static org.icgc.dcc.portal.server.util.ElasticsearchResponseUtils.getLong; import static org.icgc.dcc.portal.server.util.ElasticsearchResponseUtils.getString; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Objects; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonInclude; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import lombok.Value; import lombok.val; import org.icgc.dcc.common.core.util.stream.Collectors; @Value @JsonInclude(JsonInclude.Include.NON_NULL) @ApiModel(value = "Mutation") public class Mutation { private static final int DEFAULT_SSM_OCCURRENCE_FIELDS_NUM = 3; @ApiModelProperty(value = "Mutation ID", required = true) String id; @ApiModelProperty(value = "Type", required = true) String type; @ApiModelProperty(value = "Chromosome", required = true) String chromosome; @ApiModelProperty(value = "Start Position", required = true) Long start; @ApiModelProperty(value = "End Position", required = true) Long end; @ApiModelProperty(value = "Mutation", required = true) String mutation; @ApiModelProperty(value = "Assembly Version", required = true) String assemblyVersion; @ApiModelProperty(value = "Reference Genome Allele", required = true) String referenceGenomeAllele; @ApiModelProperty(value = "Tested Donor Count", required = true) Long testedDonorCount; @ApiModelProperty(value = "Total number of Donors affected by Mutation", required = true) Long affectedDonorCountTotal; @ApiModelProperty(value = "Filtered number of Donors affected by Mutation", required = true) Long affectedDonorCountFiltered; @ApiModelProperty(value = "Number of Cancer Projects with a Donor affected by Mutation", required = true) Long affectedProjectCount; @ApiModelProperty(value = "List of Cancer Projects with a Donor affected by Mutation", required = true) List<String> affectedProjectIds; @ApiModelProperty(value = "Platform", required = true) Collection<String> platform; @ApiModelProperty(value = "Consequence Type", required = true) List<String> consequenceType; @ApiModelProperty(value = "Verification Status", required = true) Collection<String> verificationStatus; @ApiModelProperty(value = "Occurrences") List<EmbOccurrence> occurrences; @ApiModelProperty(value = "Transcripts") List<Transcript> transcripts; @ApiModelProperty(value = "Consequences") List<Consequence> consequences; @ApiModelProperty(value = "Functional Impact Prediction Summary") List<String> functionalImpact; @ApiModelProperty(value = "Study") List<String> study; @ApiModelProperty(value = "External DB IDS") Map<String, Object> external_db_ids; @ApiModelProperty(value = "Description") String description; @ApiModelProperty(value = "Clinical Significance") Map<String, Object> clinical_significance; @ApiModelProperty(value = "Clinical Evidence") Map<String, Object> clinical_evidence; @SuppressWarnings("unchecked") @JsonCreator public Mutation(Map<String, Object> fieldMap) { ImmutableMap<String, String> fields = FIELDS_MAPPING.get(EntityType.MUTATION); id = getString(fieldMap.get(fields.get("id"))); type = getString(fieldMap.get(fields.get("type"))); chromosome = getString(fieldMap.get(fields.get("chromosome"))); start = getLong(fieldMap.get(fields.get("start"))); end = getLong(fieldMap.get(fields.get("end"))); mutation = getString(fieldMap.get(fields.get("mutation"))); assemblyVersion = getString(fieldMap.get(fields.get("assemblyVersion"))); referenceGenomeAllele = getString(fieldMap.get(fields.get("referenceGenomeAllele"))); testedDonorCount = getLong(fieldMap.get(fields.get("testedDonorCount"))); affectedDonorCountTotal = getLong(fieldMap.get(fields.get("affectedDonorCountTotal"))); affectedDonorCountFiltered = getLong(fieldMap.get(fields.get("affectedDonorCountFiltered"))); affectedProjectCount = getLong(fieldMap.get(fields.get("affectedProjectCount"))); affectedProjectIds = (List<String>) fieldMap.get(fields.get("affectedProjectIds")); platform = unique((List<String>) fieldMap.get(fields.get("platform"))); consequenceType = (List<String>) fieldMap.get(fields.get("consequenceType")); verificationStatus = unique((List<String>) fieldMap.get(fields.get("verificationStatus"))); occurrences = buildOccurrences((List<Map<String, Object>>) fieldMap.get("ssm_occurrence")); transcripts = buildTranscripts((List<Map<String, Object>>) fieldMap.get("transcript")); consequences = buildConsequences((List<Map<String, Object>>) fieldMap.get("consequences")); functionalImpact = collectFunctionalImpacts((List<Map<String, Object>>) fieldMap.get("transcript")); study = collectStudies((List<Map<String, Object>>) fieldMap.get("ssm_occurrence")); // Start annotation data fields external_db_ids = (Map<String, Object>) fieldMap.get("external_db_ids"); description = getString(fieldMap.get(fields.get("description"))); clinical_significance = (Map<String, Object>) fieldMap.get("clinical_significance"); clinical_evidence = (Map<String, Object>) fieldMap.get("clinical_evidence"); // End annotation data fields } private List<EmbOccurrence> buildOccurrences(List<Map<String, Object>> occurrences) { if (!hasOccurrences(occurrences)) return null; val lst = Lists.<EmbOccurrence> newArrayList(); for (val item : occurrences) { lst.add(new EmbOccurrence(item)); } return lst; } /** * Checks if <code>occurrences</code> object enclosed in a List is a comprehensive one or a projection of couple * fields only. */ private static boolean hasOccurrences(List<Map<String, Object>> occurrences) { if (occurrences == null) return false; val occurrenceObject = occurrences.get(0); if (occurrenceObject == null) return false; // If request was made with ssm_occurrences included fields number will be significantly greater return occurrenceObject.keySet().size() >= DEFAULT_SSM_OCCURRENCE_FIELDS_NUM; } private List<Transcript> buildTranscripts(List<Map<String, Object>> transcripts) { if (transcripts == null) return null; val lst = Lists.<Transcript> newArrayList(); for (val item : transcripts) { lst.add(new Transcript(item)); } return lst; } @SuppressWarnings("unchecked") private List<Consequence> buildConsequences(List<Map<String, Object>> transcripts) { if (transcripts == null) return null; val lst = Lists.<Consequence> newArrayList(); val consequencesMap = Maps.<String, Consequence> newHashMap(); for (val item : transcripts) { val gene = (Map<String, Object>) item.get("gene"); val consequence = new Consequence((Map<String, Object>) item.get("consequence")); val functionalImpact = (String) item.get("functional_impact_prediction_summary"); // Key uses params needed to make it unique String key = consequence.getGeneAffectedId() + consequence.getAaMutation() + consequence.getType(); if (consequencesMap.containsKey(key)) { Consequence c = consequencesMap.get(key); c.addTranscript(item); c.addFunctionalImpact(functionalImpact); } else { consequence.addTranscript(item); // Need symbol for UI, raw field get - no translation. consequence.setGeneAffectedSymbol((String) gene.get("symbol")); consequence.setGeneStrand(getLong(gene.get("strand"))); consequence.addFunctionalImpact(functionalImpact); consequencesMap.put(key, consequence); } } // Just need the consequences we made. for (val c : consequencesMap.values()) { lst.add(c); } return lst; } private static List<String> collectFunctionalImpacts(List<Map<String, Object>> transcripts) { return transcripts == null ? null : transcripts.stream() .map(t -> t.get("functional_impact_prediction_summary").toString()) .collect(toImmutableList()); } private static Collection<String> unique(List<String> list) { if (list == null) { return null; } return newHashSet(list); } private static List<String> collectStudies(List<Map<String, Object>> occurrences) { if (occurrences == null) { return newArrayList(); } val obs = occurrences.stream() .flatMap(occ -> ((List<Map<String, Object>>) occ.get("observation")).stream()) .filter(Objects::nonNull) .collect(toImmutableList()); val study = obs.stream() .filter(o -> o.containsKey("_study")) .map(o -> (String) o.get("_study")) .filter(Objects::nonNull) .collect(toImmutableSet()).asList(); return study; } }
gpl-3.0
idega/com.idega.core
src/java/com/idega/util/DateFormatException.java
332
package com.idega.util; /** * This exception is thrown when a date couldn´t be parsed * @author <a href="mailto:joakim@idega.is">Joakim Johnson</a> * @version 1.0 */ public class DateFormatException extends Exception { public DateFormatException() { super(); } public DateFormatException(String s) { super(s); } }
gpl-3.0
dcatteeu/JSearch
src/main/java/drc/jsearch/BreadthFirstSearch.java
824
/* Copyright 2013 David Catteeuw This file is part of JSearch. JSearch 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. JSearch 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 JSearch. If not, see <http://www.gnu.org/licenses/>. */ package drc.jsearch; public class BreadthFirstSearch extends GenericSearchAlgorithm { public BreadthFirstSearch () { super(new FifoOpenList()); } }
gpl-3.0
rozkminiacz/fcm-proxy
old/src/main/java/com/rozkmin/database/MongoConnector.java
3178
package com.rozkmin.database; import com.mongodb.BasicDBObject; import com.mongodb.DB; import com.mongodb.DBObject; import com.mongodb.MongoClient; import com.rozkmin.notifications.FcmNotification; import com.rozkmin.util.JsonHelper; import rx.Observable; import java.net.UnknownHostException; import java.util.List; import java.util.Map; /** * Created by michalik on 04.04.17 * All rights reserved */ public class MongoConnector { private static final String DATABASE_NAME = "NOTIFICATIONS"; private static final String COLLECITON = "NOTIFICATIONS_COLLECTION"; private static MongoConnector instance; private DB db; public static MongoConnector getInstance() { return instance == null ? new MongoConnector() : instance; } private MongoConnector() { instance = this; MongoClient mongoClient = null; try { mongoClient = new MongoClient("localhost", 27017); } catch (UnknownHostException e) { e.printStackTrace(); } if (mongoClient != null) { db = mongoClient.getDB(DATABASE_NAME); } DBObject options = new BasicDBObject(); if (db.getCollection(COLLECITON) == null) { db.createCollection(COLLECITON, options); } System.out.println("DB initialized " + db.getName()); System.out.println(db.getCollectionNames()); } public FcmNotification saveNotification(FcmNotification notification) { DBObject dbObject = JsonHelper.toDbObject(notification); db.getCollection(COLLECITON).save(dbObject); return ((FcmNotification) db.getCollection(COLLECITON).find(dbObject).curr()); } @SuppressWarnings("unused") public Observable<List<FcmNotification>> getAllNotifications() { return Observable.from(db.getCollection(COLLECITON).find().toArray()) .map(dbObject -> JsonHelper.fromDbObject(dbObject, FcmNotification.class)) .map(o -> ((FcmNotification) o)) .toList(); } public Observable<FcmNotification> getNotificationsObservable() { return Observable.from(db.getCollection(COLLECITON).find().toArray()) .map(dbObject -> JsonHelper.fromDbObject(dbObject, FcmNotification.class)) .map(o -> ((FcmNotification) o)); } @SuppressWarnings("unused") public Observable<Map<String, String>> getNotificationsObservable(int limit) { return Observable.from(db.getCollection(COLLECITON).find().toArray()) .map(dbObject -> JsonHelper.fromDbObject(dbObject, FcmNotification.class)) .map(o -> ((FcmNotification) o)) .map(FcmNotification::getData); } @SuppressWarnings("unused") public Observable<FcmNotification> getNotificationsObservable(String topic) { return Observable.from(db.getCollection(COLLECITON).find().toArray()) .map(dbObject -> JsonHelper.fromDbObject(dbObject, FcmNotification.class)) .map(o -> ((FcmNotification) o)) .filter(fcmNotification -> fcmNotification.getTo().contentEquals("/topics/" + topic)); } }
gpl-3.0
bovard/battlecode-client-2015
src/main/battlecode/client/viewer/render/ExplosionAnim.java
1096
package battlecode.client.viewer.render; import battlecode.common.*; import battlecode.client.util.*; import java.awt.*; import java.awt.geom.*; class ExplosionAnim extends FramedAnimation { public static enum ExplosionToggle { EXPLOSIONS, } protected ExplosionToggle toggle = ExplosionToggle.EXPLOSIONS; public ExplosionAnim() { this(null, 1); } public ExplosionAnim(MapLocation loc) { this(loc, 1); } public ExplosionAnim(MapLocation loc, double width) { super(loc, width, 4); } protected boolean loops() { return false; } int offset() { return 1; } public String fileFormatString() { return "art/explode/explode64_f%02d.png"; } public void setExplosionToggle(ExplosionToggle t) { toggle = t; } protected boolean shouldDraw() { switch(toggle) { case EXPLOSIONS: return RenderConfiguration.showExplosions(); default: return false; } } public Object clone() { ExplosionAnim clone = new ExplosionAnim(loc, width); clone.curFrame = curFrame; clone.toggle = toggle; return clone; } }
gpl-3.0
trackplus/Genji
src/main/java/com/trackplus/dao/ProjectRepositoryDAO.java
1205
/** * Genji Scrum Tool and Issue Tracker * Copyright (C) 2015 Steinbeis GmbH & Co. KG Task Management Solutions * <a href="http://www.trackplus.com">Genji Scrum Tool</a> * * 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/>. */ /* $Id:$ */ package com.trackplus.dao; import java.util.List; import com.trackplus.model.Tprojectreportrepository; /** * Migrate the previous project specific TQLs Used only for backward * compatibility * * @author Tamas Ruff */ public interface ProjectRepositoryDAO { /** * Load all project TQLs * * @return */ List<Tprojectreportrepository> loadAll(); }
gpl-3.0
dgf/dm4-mail
src/main/java/de/deepamehta/plugins/mail/ImageCidEmbedment.java
1784
package de.deepamehta.plugins.mail; import java.io.IOException; import java.net.URL; import java.util.logging.Logger; import org.apache.commons.mail.EmailException; import org.apache.commons.mail.HtmlEmail; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import de.deepamehta.plugins.files.service.FilesService; class ImageCidEmbedment { private static Logger log = Logger.getLogger(MailPlugin.class.getName()); private final FilesService fileService; public ImageCidEmbedment(FilesService fileService) { this.fileService = fileService; } /** * Embed all images of body. * * @return Document with CID replaced image source attributes. */ public Document embedImages(HtmlEmail email, String body) throws EmailException, IOException { int count = 0; Document document = Jsoup.parse(body); for (Element image : document.getElementsByTag("img")) { URL url = new URL(image.attr("src")); image.attr("src", "cid:" + embedImage(email, url, ++count + url.getPath())); } return document; } /** * Embed any image type (external URL, file repository and plugin resource). * * @return CID of embedded image. * @throws EmailException */ public String embedImage(HtmlEmail email, URL url, String name) throws EmailException { String path = fileService.getRepositoryPath(url); if (path != null) { // repository link log.fine("embed repository image " + path); return email.embed(fileService.getFile(path)); } else { // external URL log.fine("embed external image " + url); return email.embed(url, name); } } }
gpl-3.0
Escapecraft/FalseBook
src/main/java/com/bukkit/gemo/FalseBook/IC/ICs/standard/MC1017.java
1406
package com.bukkit.gemo.FalseBook.IC.ICs.standard; import com.bukkit.gemo.FalseBook.IC.ICs.BaseChip; import com.bukkit.gemo.FalseBook.IC.ICs.BaseIC; import com.bukkit.gemo.FalseBook.IC.ICs.ICGroup; import com.bukkit.gemo.FalseBook.IC.ICs.InputState; import com.bukkit.gemo.FalseBook.IC.ICs.Lever; import com.bukkit.gemo.utils.ICUtils; import org.bukkit.block.Sign; import org.bukkit.event.block.SignChangeEvent; public class MC1017 extends BaseIC { public MC1017() { this.ICName = "RISING TOGGLE"; this.ICNumber = "[MC1017]"; this.setICGroup(ICGroup.STANDARD); this.chipState = new BaseChip(true, false, false, "Clock", "", ""); this.chipState.setOutputs("Output", "", ""); this.ICDescription = "The MC1017 is a toggle flip flop that toggles its output state between low and high whenever the input (the \"clock\") changes from low to high."; } public void checkCreation(SignChangeEvent event) { event.setLine(2, ""); event.setLine(3, ""); } public void Execute(Sign signBlock, InputState currentInputs, InputState previousInputs) { if(currentInputs.isInputOneHigh() && previousInputs.isInputOneLow()) { if(ICUtils.isLeverActive(signBlock)) { this.switchLever(Lever.BACK, signBlock, false); } else { this.switchLever(Lever.BACK, signBlock, true); } } } }
gpl-3.0
whwnsdlr1/HWRRC
client/src/com/remotecontrol/CR.java
26712
package com.remotecontrol; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Enumeration; import java.util.LinkedList; import java.util.StringTokenizer; import java.util.Vector; import android.os.Environment; public class CR { public final static int NUMBER_OF_LETTER = 37; private final int PART_MIN_X = 150; private final int PART_MIN_Y = 120; private final int PART_MAX_X = 1050; private final int PART_MAX_Y = 520; private final int diff_letter_tolerance = 15; // 나중에 상수 말고 변수로 글씨 크기에 따라 조정하는 방법도 생각 private LinkedList<file_read_help_class>[] database; private Vector< LinkedList<coord>> v_stroke; private Vector< LinkedList<coord>> v_stroke_part[]; private Vector< LinkedList<info_dir>> v_stroke_dir; private Vector< LinkedList<info_dir>> v_stroke_dir_part[]; private int[] training_data_count; private static String[] letter = new String[ NUMBER_OF_LETTER]; private int partition_mode; private int blob_count; private LinkedList<Integer> blob_endpoint; public CR() { v_stroke_dir = new Vector< LinkedList<info_dir>>( 10, 30); database = new LinkedList[ NUMBER_OF_LETTER]; for( int n = 0 ; n < NUMBER_OF_LETTER ; n++) database[n] = new LinkedList<file_read_help_class>(); v_stroke_part = new Vector[5]; for( int i = 0 ; i < 5 ; i++) v_stroke_part[i] = new Vector< LinkedList<coord>>(); v_stroke_dir_part = new Vector[5]; for( int i = 0 ; i < 5 ; i++) v_stroke_dir_part[i] = new Vector< LinkedList<info_dir>>(); init(); } private void init() { training_data_count = new int[ NUMBER_OF_LETTER]; for( int n = 0 ; n < NUMBER_OF_LETTER ; n++) training_data_count[ n] = 0; loadData(); } private void loadData() { String sdPath; String externalState = Environment.getExternalStorageState(); if( externalState.equals( Environment.MEDIA_MOUNTED)) sdPath = Environment.getExternalStorageDirectory().getAbsolutePath(); else sdPath = Environment.MEDIA_UNMOUNTED; File directory = new File( sdPath + "/train_data"); if( directory.isDirectory() == false) { //error 체크 } else { try { File[] sub_file = directory.listFiles(); for( File f : sub_file) { if( f.isFile() == true) { if( f.getName().startsWith( "CR_")) { BufferedReader inFile = new BufferedReader(new FileReader( f)); String sLine = null; boolean unconditional; sLine = inFile.readLine(); training_data_count[ find_letter_index( f.getName().substring( 3))] = Integer.parseInt( sLine.substring( 1)); while( (sLine = inFile.readLine()) != null ) { if( sLine.length() < 2) break; unconditional = false; if( sLine.charAt( 0) == '=') { unconditional = true; sLine = sLine.substring( 1); } file_read_help_class frhc = new file_read_help_class(); frhc.dir_length = new LinkedList<Integer>(); StringTokenizer st = new StringTokenizer( sLine, "/"); int phase = 0; int sum = 0; int n = 0; while( st.hasMoreElements()) { /////////////////////////// dis 일때 길이일때 카운트일때 다 따로 String str_token = st.nextToken(); StringTokenizer st2 = new StringTokenizer( str_token, " "); while( st2.hasMoreElements()) { String str_token2 = st2.nextToken(); if( phase == 0) frhc.dirs = str_token2; else if( phase == 1) { int i = Integer.parseInt( str_token2); sum += i; n++; frhc.dir_length.add( i); } else frhc.count = Integer.parseInt( str_token2); } if( phase == 1) { for( int nn = 0 ; nn < n ; nn++) { frhc.dir_length.add( nn, (( frhc.dir_length.get( nn) * 100) / sum)); frhc.dir_length.remove( nn + 1); } } phase++; } int index = find_letter_index( f.getName().substring( 3)); if( frhc.count / (float)training_data_count[ index] > 0.12) database[index].add( frhc); else if( unconditional == true) database[index].add( frhc); } inFile.close(); } } } } catch (IOException e) { } //_notificationField.setText("[" + Integer.toString( count) + "]개의 글자정보 로딩완료"); } } public void clearVector() { Enumeration< LinkedList<info_dir>> my_enum2 = v_stroke_dir.elements(); while( my_enum2.hasMoreElements()){ LinkedList<info_dir> temp = my_enum2.nextElement(); temp.clear(); } v_stroke_dir.clear(); for( int i = 0 ; i < 5 ; i++) { my_enum2 = v_stroke_dir_part[ i].elements(); while( my_enum2.hasMoreElements()){ LinkedList<info_dir> temp = my_enum2.nextElement(); temp.clear(); } v_stroke_dir_part[ i].clear(); } Enumeration< LinkedList<coord>> my_enum3; for( int i = 0 ; i < 5 ; i++) { my_enum3 = v_stroke_part[ i].elements(); while( my_enum3.hasMoreElements()){ LinkedList< coord> temp = my_enum3.nextElement(); temp.clear(); } v_stroke_part[ i].clear(); } } public int find_letter_index( String str2) { String str1; for( int n = 0 ; n < NUMBER_OF_LETTER ; n++) { str1 = ( letter[n] + ""); if( str1.equals( str2)) return n; } return NUMBER_OF_LETTER - 1; } public String find_CR( Vector< LinkedList<coord>> VC) { String result_str = ""; LinkedList<info_dir> l_dirs; v_stroke = VC; if( v_stroke.isEmpty() == true) return "입력 없음"; partition_mode = 0; Create_v_dir(); blob_count = 0; blob_endpoint = new LinkedList<Integer>(); if( partition_mode == 0) { blob_labeling( v_stroke); for( int process_blob = 0 ; process_blob < blob_count ; process_blob++) { l_dirs = Get_l_dirs_from_blob( process_blob, v_stroke_dir); /*result_str += Find( l_dirs); l_dirs.clear();*/ int index; if( process_blob == 0) index = 0; else index = blob_endpoint.get( process_blob - 1).intValue() + 1; String t_t_str = Find( l_dirs); t_t_str = exception_letter_process( t_t_str, v_stroke.get(index)); result_str += t_t_str; l_dirs.clear(); } blob_endpoint.clear(); result_str = analyze_letter( result_str); } else if( partition_mode == 1 || partition_mode == 2) { result_str = "p2"; for( int n1 = 1 ; n1 < 3 ; n1++) { blob_labeling( v_stroke_part[ n1]); String t_str = ","; for( int process_blob = 0 ; process_blob < blob_count ; process_blob++) { l_dirs = Get_l_dirs_from_blob( process_blob, v_stroke_dir_part[ n1]); /*t_str += Find( l_dirs); l_dirs.clear();*/ int index; if( process_blob == 0) index = 0; else index = blob_endpoint.get( process_blob - 1).intValue() + 1; String t_t_str = Find( l_dirs); t_t_str = exception_letter_process( t_t_str, v_stroke_part[ n1].get( index)); t_str += t_t_str; l_dirs.clear(); } result_str += t_str; blob_endpoint.clear(); } } else { result_str = "p4"; Vector<LinkedList<coord>> temp_v_stroke; Vector<LinkedList<info_dir>> temp_v_stroke_dir; temp_v_stroke = v_stroke_part[2]; temp_v_stroke_dir = v_stroke_dir_part[2]; v_stroke_part[2] = v_stroke_part[3]; v_stroke_dir_part[2] = v_stroke_dir_part[3]; v_stroke_part[3] = temp_v_stroke; v_stroke_dir_part[3] = temp_v_stroke_dir; for( int n1 = 1 ; n1 < 5 ; n1++) { blob_labeling( v_stroke_part[ n1]); String t_str = ","; for( int process_blob = 0 ; process_blob < blob_count ; process_blob++) { l_dirs = Get_l_dirs_from_blob( process_blob, v_stroke_dir_part[ n1]); /*t_str += Find( l_dirs); l_dirs.clear();*/ int index; if( process_blob == 0) index = 0; else index = blob_endpoint.get( process_blob - 1).intValue() + 1; String t_t_str = Find( l_dirs); t_t_str = exception_letter_process( t_t_str, v_stroke_part[ n1].get(index)); t_str += t_t_str; l_dirs.clear(); } result_str += t_str; blob_endpoint.clear(); } } return result_str; } private String exception_letter_process( String ch, LinkedList<coord> in_l_coord) { if( ch.equals("0") || ch.equals( "ㅇ")) { if( Get_length( in_l_coord.getFirst(), in_l_coord.getLast()) > diff_letter_tolerance * 4) return "6"; } else if( ch.equals("6")) { if( Get_length( in_l_coord.getFirst(), in_l_coord.getLast()) < diff_letter_tolerance * 4) return "0"; else { Direction dir = Get_direction( in_l_coord.getFirst(), in_l_coord.getLast()); if( dir == Direction.DIR3 || dir == Direction.DIR2) return "V"; } } else if( ch.equals("V")) { Direction dir = Get_direction( in_l_coord.getFirst(), in_l_coord.getLast()); if( dir != Direction.DIR3 && dir != Direction.DIR2 && dir != Direction.DIR4) return "6"; else if( Get_length( in_l_coord.getFirst(), in_l_coord.getLast()) < diff_letter_tolerance * 4) return "0"; } else if( ch.equals("2")) { Direction dir = Get_direction( in_l_coord.get( Math.max( in_l_coord.size() -2, 0)), in_l_coord.getLast()); if( dir != Direction.DIR3 && dir != Direction.DIR2 && dir != Direction.DIR4) return "3"; return ch; } else if( ch.equals("3")) { if( Get_length( in_l_coord.getFirst(), in_l_coord.getLast()) < diff_letter_tolerance * 4) return "8"; return ch; } return ch; } private String analyze_letter( String in_str) // 여기서 부터 수정 시작 { String str = in_str.charAt( 0) + ""; int letter_index; if( str.equals( "0")) { if( in_str.length() > 1) in_str = in_str.replace( '0', 'ㅇ'); } else if( str.equals("o")) { if( in_str.length() == 1) in_str = "0"; } else if( str.equals("V")) { if( in_str.length() == 1) in_str = "down"; else in_str.replace( 'ㅇ', '0'); } else if( str.equals("ㄴ")) { if( in_str.length() == 1) in_str = "nextskip"; } else if( str.startsWith( "up")) { if( in_str.length() != 1) in_str = "ㅅ" + in_str.substring( 1); } if( in_str.contains( "1ㅂ")) { in_str = in_str.replace("1ㅂ", "ㅂ"); } if( in_str.contains( "1ㅋ")) { in_str = in_str.replace("1ㅋ", "ㅂ"); } str = in_str.charAt( 0) + ""; letter_index = find_letter_index( str); if( is_Korean_letter( letter_index)) { str = "find,"; in_str = in_str.replace( '0', 'ㅇ'); str += in_str; } else if( is_Num_letter( letter_index)) { str = "channel,"; in_str = in_str.replace( 'ㅇ', '0'); in_str = in_str.replace( 'V', '6'); str += in_str; } else if( letter_index == 10) // 볼륨 { str = "volume,"; str += in_str.substring( 1); } else str = in_str; return str; } private String Find( LinkedList<info_dir> l_dirs) { String l_name = "NULL"; int probability = 0, t_probability, t_probability2; if( l_dirs.size() == 0) return l_name; int sum = 0; // 모션에 길이들을 백분율로 표시해줌 ------------------------------------------------ for( int n1 = 0 ; n1 < l_dirs.size() ; n1++) sum += l_dirs.get( n1).length; for( int n1 = 0 ; n1 < l_dirs.size() ; n1++) l_dirs.get(n1).length = ( l_dirs.get(n1).length * 100) / sum; // -------------------------------------------------------------------------------------- for( int n1 = 0 ; n1 < database.length ; n1++) { for( int n2 = 0 ; n2 < database[ n1].size() ; n2++) { t_probability = t_probability2 = 0; String dirs = database[ n1].get( n2).dirs; // ----------------------------------------------------------- 비교 1 --- int n3 = 0, n4 = 0; while( n3 < dirs.length() && n4 < l_dirs.size()) { Direction dir = Convert_sign_to_dir( dirs.charAt( n3)); if( dir.toString().charAt( 0) == 'T') { if( l_dirs.get( n4).direction != dir) { if( l_dirs.get( n4).direction.toString().charAt( 0) == 'T') break; n4++; } else { n3++; n4++; } } else { if( dir == l_dirs.get( n4).direction) { // t_probability += ( _motion.get( n4).length * database[ n1].get( n2).dir_length.get( n3)); int temp_sum = l_dirs.get( n4).length - database[ n1].get( n2).dir_length.get( n3); temp_sum = ( temp_sum * temp_sum) /2 ; t_probability += Math.sqrt( temp_sum); n3++; n4++; } else if( ( n3 + 1) < dirs.length()) { Direction dir2 = Convert_sign_to_dir( dirs.charAt( n3 + 1)); if( dir2 == l_dirs.get( n4).direction || l_dirs.get( n4).direction.toString().charAt( 0) == 'T') { int temp_sum = database[ n1].get( n2).dir_length.get( n3); temp_sum = ( temp_sum * temp_sum) / 2; t_probability += Math.sqrt( temp_sum); n3++; } else n4++; } else { if( l_dirs.get( n4).direction.toString().charAt( 0) == 'T') break; else n4++; } } } for( ; n3 < dirs.length() ; n3++) { int temp_sum = database[ n1].get( n2).dir_length.get( n3); if( temp_sum == 0) temp_sum = 30; temp_sum = ( temp_sum * temp_sum) / 2; t_probability += Math.sqrt( temp_sum); }// ----------------------------------------------------------- 비교 1 --- // ----------------------------------------------------------- 비교 2 --- n3 = n4 = 0; while( n3 < dirs.length() && n4 < l_dirs.size()) { Direction dir = Convert_sign_to_dir( dirs.charAt( n3)); if( l_dirs.get( n4).direction.toString().charAt( 0) == 'T') { if( l_dirs.get( n4).direction != dir) { if( dir.toString().charAt( 0) == 'T') break; int temp_sum = database[ n1].get( n2).dir_length.get( n3); temp_sum = ( temp_sum * temp_sum) / 2; t_probability2 += Math.sqrt( temp_sum); n3++; } else { n3++; n4++; } } else { if( dir == l_dirs.get( n4).direction) { // t_probability += ( _motion.get( n4).length * database[ n1].get( n2).dir_length.get( n3)); int temp_sum = l_dirs.get( n4).length - database[ n1].get( n2).dir_length.get( n3); temp_sum = ( temp_sum * temp_sum) /2 ; t_probability2 += Math.sqrt( temp_sum); n3++; n4++; } else if( ( n4 + 1) < l_dirs.size()) { if( dir == l_dirs.get( n4 + 1).direction || dir.toString().charAt( 0) == 'T') n4++; else { int temp_sum = database[ n1].get( n2).dir_length.get( n3); temp_sum = ( temp_sum * temp_sum) / 2; t_probability2 += Math.sqrt( temp_sum); n3++; } } else { if( dir.toString().charAt( 0) == 'T') break; int temp_sum = database[ n1].get( n2).dir_length.get( n3); temp_sum = ( temp_sum * temp_sum) / 2; t_probability2 += Math.sqrt( temp_sum); n3++; } } } for( ; n3 < dirs.length() ; n3++) { int temp_sum = database[ n1].get( n2).dir_length.get( n3); if( temp_sum == 0) temp_sum = 30; temp_sum = ( temp_sum * temp_sum) / 2; t_probability2 += Math.sqrt( temp_sum); } // ----------------------------------------------------------- 비교 2 --- if( t_probability > t_probability2) t_probability = t_probability2; t_probability = 100 - t_probability; if( t_probability > probability) { probability = t_probability; l_name = letter[ n1]; } } } // 바뀐 알고리즘 교체 하는곳 end end end end end end000000000000000000000000000000000000000000000000000 if( probability < 50) l_name = "none"; return l_name; } private void blob_labeling( Vector<LinkedList< coord>> local_v_coord) { int max_x_1 = 0, min_x_1 = 2000; blob_count = 0; if( local_v_coord.size() != 0) { blob_count = 1; if( local_v_coord.size() >= 2) { for( int n1 = 1 ; n1 < local_v_coord.size() ; n1++) { int max_x = 0, min_x = 2000; for( int n2 = 0 ; n2 < local_v_coord.get( n1 - 1).size() ; n2++) { if( max_x_1 < local_v_coord.get( n1 - 1).get( n2).x) max_x_1 = local_v_coord.get( n1 - 1).get( n2).x; if( min_x_1 > local_v_coord.get( n1 - 1).get( n2).x) min_x_1 = local_v_coord.get( n1 - 1).get( n2).x; } for( int n2 = 0 ; n2 < local_v_coord.get( n1).size() ; n2++) { if( max_x < local_v_coord.get( n1).get( n2).x) max_x = local_v_coord.get( n1).get( n2).x; if( min_x > local_v_coord.get( n1).get( n2).x) min_x = local_v_coord.get( n1).get( n2).x; } if( min_x_1 < max_x && max_x_1 > max_x) { } else if( min_x_1 < min_x && max_x_1 > min_x) { } else if( min_x < max_x_1 && max_x > max_x_1) { } else if( min_x < min_x_1 && max_x > min_x_1) { } else if( Math.abs( min_x - max_x_1) < diff_letter_tolerance) { } else if( Math.abs( min_x_1 - max_x) < diff_letter_tolerance) { } else { max_x_1 = 0; min_x_1 = 2000; blob_count++; blob_endpoint.add( n1 - 1); } } } blob_endpoint.add( local_v_coord.size() - 1); } } private LinkedList<info_dir> Get_l_dirs_from_blob( int process_blob, Vector<LinkedList<info_dir>> in_v_dir) { int n1; LinkedList<info_dir> l_dirs = new LinkedList<info_dir>(); if( process_blob == 0) n1 = 0; else n1 = blob_endpoint.get( process_blob - 1).intValue() + 1; for( ; n1 < blob_endpoint.get( process_blob).intValue() + 1 ; n1++) { if( n1 < 0 || n1 >= in_v_dir.size()) // 추가 예외처리 return l_dirs; LinkedList<info_dir> t_l_dirs = in_v_dir.get( n1); for( int n2 = 0 ; n2 < t_l_dirs.size() ; n2++) l_dirs.add( t_l_dirs.get( n2)); } if( l_dirs.isEmpty() == false) { if( process_blob != 0 || l_dirs.getFirst().toString().charAt( 0) == 'T') l_dirs.remove( 0); } return l_dirs; } private void Create_v_dir() { int start_index = 0; int pre_stroke = 0; int divide_x = 0, divide_y = 0, pre_part = 0, now_part = 0; boolean is_started = false; coord pre_coord = new coord(); coord now_coord = new coord(); for( int n1 = 0 ; n1 < v_stroke.size() ; n1++) { LinkedList<coord> l_coord = v_stroke.get( n1); if( n1 == 0) { if( l_coord.getFirst().x < PART_MIN_X && l_coord.getLast().x > PART_MAX_X) { start_index = 1; partition_mode = 1; divide_y = ( l_coord.getFirst().y + l_coord.getLast().y) / 2; continue; } else if( l_coord.getFirst().y < PART_MIN_Y && l_coord.getLast().y > PART_MAX_Y) { start_index = 1; partition_mode = 2; divide_x = ( l_coord.getFirst().x + l_coord.getLast().x) / 2; continue; } } else if( n1 == 1) { if( l_coord.getFirst().x < PART_MIN_X && l_coord.getLast().x > PART_MAX_X) { if( partition_mode == 2) { start_index = 2; partition_mode = 3; divide_y = ( l_coord.getFirst().y + l_coord.getLast().y) / 2; continue; } } else if( l_coord.getFirst().y < PART_MIN_Y && l_coord.getLast().y > PART_MAX_Y) { if( partition_mode == 1) { start_index = 2; partition_mode = 3; divide_x = ( l_coord.getFirst().x + l_coord.getLast().x) / 2; continue; } } if( partition_mode != 0) pre_part = Get_part( l_coord.getFirst(), divide_x, divide_y); } else if( n1 == 2) { if( partition_mode == 3) pre_part = Get_part( l_coord.getFirst(), divide_x, divide_y); } if( partition_mode != 0) { now_part = Get_part( l_coord.getFirst(), divide_x, divide_y); if( now_part != pre_part) { is_started = false; if( v_stroke_dir_part[ pre_part].size() != 0) v_stroke_dir_part[ pre_part].clear(); v_stroke_dir_part[ pre_part] = v_stroke_dir; v_stroke_dir = new Vector< LinkedList<info_dir>>( 10, 30); for( int index = start_index ; index < n1; index++) v_stroke_part[ pre_part].add( v_stroke.get( index)); start_index = n1; pre_part = now_part; } } //if( l_coord.size() < 2) // 나중에 블랍라벨릴ㅇ한후 이 부분에 걸리면 서로 잘리니 확인할것 // continue; LinkedList<info_dir> l_dir = new LinkedList<info_dir>(); pre_coord.x = l_coord.get( 0).x; pre_coord.y = l_coord.get( 0).y; if( is_started == true) { Direction dir = Convert_dir_to_T( Get_direction( v_stroke.get( pre_stroke).getLast(), pre_coord)); info_dir dir_info = new info_dir(); dir_info.direction = dir; dir_info.length = 0; l_dir.add( dir_info); } is_started = true; pre_stroke = n1; v_stroke_dir.add( l_dir); for( int n2 = 1 ; n2 < l_coord.size() ; n2++) { now_coord.x = l_coord.get( n2).x; now_coord.y = l_coord.get( n2).y; Direction dir = Get_direction( pre_coord, now_coord); int length = Get_length( pre_coord, now_coord); if( l_dir.isEmpty() == false && l_dir.getLast().direction == dir) l_dir.getLast().length += length; else { info_dir dir_info = new info_dir(); dir_info.direction = dir; dir_info.length = length; l_dir.add( dir_info); } pre_coord.x = now_coord.x; pre_coord.y = now_coord.y; } } if( partition_mode != 0) { for( int index = start_index ; index < v_stroke.size() ; index++) v_stroke_part[ now_part].add( v_stroke.get( index)); v_stroke_dir_part[ now_part] = v_stroke_dir; } } private int Get_part( coord conm, int divide_x, int divide_y) { int now_part = 0; if( partition_mode == 1) { if( conm.y < divide_y) now_part = 1; else now_part = 2; } else if( partition_mode == 2) { if( conm.x < divide_x) now_part = 1; else now_part = 2; } else if( partition_mode == 3) { if( conm.x < divide_x) { if( conm.y < divide_y) now_part = 1; else now_part = 2; } else { if( conm.y < divide_y) now_part = 3; else now_part = 4; } } return now_part; } private int Get_length( coord pre, coord cur) { int dx = cur.x - pre.x; int dy = cur.y - pre.y; return (int)Math.sqrt( dx * dx + dy * dy); } private Direction Convert_sign_to_dir( int ch) { if( ch == '1') return Direction.DIR1; else if( ch == '2') return Direction.DIR2; else if( ch == '3') return Direction.DIR3; else if( ch == '4') return Direction.DIR4; else if( ch == '5') return Direction.DIR5; else if( ch == '6') return Direction.DIR6; else if( ch == '7') return Direction.DIR7; else if( ch == '8') return Direction.DIR8; else if( ch == 'a') return Direction.T_DIR1; else if( ch == 'b') return Direction.T_DIR2; else if( ch == 'c') return Direction.T_DIR3; else if( ch == 'd') return Direction.T_DIR4; else if( ch == 'e') return Direction.T_DIR5; else if( ch == 'f') return Direction.T_DIR6; else if( ch == 'g') return Direction.T_DIR7; else return Direction.T_DIR8; } private Direction Get_direction( coord pre, coord cur) { int dx, dy, coord_tangent;; Direction result_dir; dx = cur.x - pre.x; dy = pre.y - cur.y; if( dx == 0) { if( dy > 0) result_dir = Direction.DIR1; else result_dir = Direction.DIR5; } else if( dy == 0) { if( dx > 0) result_dir = Direction.DIR3; else result_dir = Direction.DIR7; } else { coord_tangent = dy * 100 / dx; if( -41 <= coord_tangent && coord_tangent <= 41) { if( dx > 0) result_dir = Direction.DIR3; else result_dir = Direction.DIR7; } else if( 41 < coord_tangent && coord_tangent < 241) { if( dy > 0) result_dir = Direction.DIR2; else result_dir = Direction.DIR6; } else if( -241 < coord_tangent && coord_tangent < -41) { if( dy > 0) result_dir = Direction.DIR8; else result_dir = Direction.DIR4; } else { if( dy > 0) result_dir = Direction.DIR1; else result_dir = Direction.DIR5; } } return result_dir; } private Direction Convert_dir_to_T( Direction dir1) { if( dir1 == Direction.DIR1) return Direction.T_DIR1; else if( dir1 == Direction.DIR2) return Direction.T_DIR2; else if( dir1 == Direction.DIR3) return Direction.T_DIR3; else if( dir1 == Direction.DIR4) return Direction.T_DIR4; else if( dir1 == Direction.DIR5) return Direction.T_DIR5; else if( dir1 == Direction.DIR6) return Direction.T_DIR6; else if( dir1 == Direction.DIR7) return Direction.T_DIR7; else return Direction.T_DIR8; } private boolean is_Korean_letter( int letter_num) { if( letter_num >= 11 && letter_num <= 29) return true; else return false; } private boolean is_Num_letter( int letter_num) { if( letter_num >= 0 && letter_num <= 9) return true; else return false; } static{ letter[0] = "0"; letter[1] = "1"; letter[2] = "2"; letter[3] = "3"; letter[4] = "4"; letter[5] = "5"; letter[6] = "6"; letter[7] = "7"; letter[8] = "8"; letter[9] = "9"; letter[10] = "V"; letter[11] = "ㄱ"; letter[12] = "ㄴ"; letter[13] = "ㄷ"; letter[14] = "ㄹ"; letter[15] = "ㅁ"; letter[16] = "ㅂ"; letter[17] = "ㅅ"; letter[18] = "ㅇ"; letter[19] = "ㅈ"; letter[20] = "ㅊ"; letter[21] = "ㅋ"; letter[22] = "ㅌ"; letter[23] = "ㅍ"; letter[24] = "ㅎ"; letter[25] = "ㄲ"; letter[26] = "ㄸ"; letter[27] = "ㅃ"; letter[28] = "ㅆ"; letter[29] = "ㅉ"; letter[30] = "up"; letter[31] = "unknowncmd"; letter[32] = "pre"; letter[33] = "next"; letter[34] = "startnstop"; letter[35] = "preskip"; letter[36] = "nextskip"; } } class file_read_help_class{ String dirs; LinkedList<Integer> dir_length; int count; } class coord{ int x; int y; } enum Direction{ DIR1, DIR2, DIR3, DIR4, DIR5, DIR6, DIR7, DIR8, T_DIR1, T_DIR2, T_DIR3, T_DIR4, T_DIR5, T_DIR6, T_DIR7, T_DIR8, Z_CIRCLE} class info_dir{ Direction direction; int length; }
gpl-3.0
abmindiarepomanager/ABMOpenMainet
Mainet1.0/MainetServiceParent/MainetServiceWater/src/main/java/com/abm/mainet/water/dto/WaterBillPrintingDTO.java
13087
/** * */ package com.abm.mainet.water.dto; import java.io.Serializable; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import com.abm.mainet.common.integration.dto.TbBillDet; /** * @author Rahul.Yadav * */ public class WaterBillPrintingDTO implements Serializable { private static final long serialVersionUID = -5577526454551084817L; @NotNull private long bmIdno; // ---------------------------------------------------------------------- // ENTITY DATA FIELDS // ---------------------------------------------------------------------- @NotNull private Long csIdn; @NotNull private Long bmYear; private Date bmBilldt; @NotNull private Date bmFromdt; @NotNull private Date bmTodt; private Date bmDuedate; private double bmTotalAmount; private double bmTotalBalAmount; private double bmIntValue; private double bmTotalArrears; private double bmTotalOutstanding; private double bmTotalArrearsWithoutInt; private double bmTotalCumIntArrears; private double bmToatlInt; private double bmLastRcptamt; private Date bmLastRcptdt; private double bmToatlRebate; @Size(max = 1) private String bmPaidFlag; private double bmFyTotalArrears; private double bmFyTotalInt; @Size(max = 1) private String flagJvPost; private Date distDate; @Size(max = 100) private String bmRemarks; private Date bmPrintdate; @Size(max = 1) private String arrearsBill; private double bmTotpayamtAftdue; private double bmIntamtAftdue; @Size(max = 15) private String bmIntType; private BigDecimal bmTrdPremis; private BigDecimal bmCcnSize; @Size(max = 500) private String bmCcnOwner; @Size(max = 1) private String bmEntryFlag; @Size(max = 1) private String bmIntChargedFlag; private Long amendForBillId; @Size(max = 1) private String bmMeteredccn; private Date bmDuedate2; @Size(max = 1) private String chShdIntChargedFlag; private double bmSecDepAmt; @Size(max = 20) private String bmLastSecDepRcptno; private Date bmLastSecDepRcptdt; @NotNull private Long orgid; @NotNull private Long userId; @NotNull private int langId; @NotNull private Date lmoddate; private Date intFrom; private Date intTo; private BigDecimal fyiIntArrears; private BigDecimal fyiIntPerc; private List<TbBillDet> tbWtBillDet = new ArrayList<TbBillDet>( 0); private TbCsmrInfoDTO waterMas = new TbCsmrInfoDTO(); private TbMeterMas meterMas = new TbMeterMas(); private MeterReadingDTO meterRead = new MeterReadingDTO(); private String connectionCategory; private String tarriffCategory; private String conSize; private double grandTotal; private double arrearsTotal; private double taxtotal; private String amountInwords; private String pmPropno; private Long rmRcptid; private String bmNo; private double excessAmount; private double rebateAmount; private double balanceExcessAmount; public double getBalanceExcessAmount() { return balanceExcessAmount; } public void setBalanceExcessAmount(double balanceExcessAmount) { this.balanceExcessAmount = balanceExcessAmount; } public long getBmIdno() { return bmIdno; } public void setBmIdno(long bmIdno) { this.bmIdno = bmIdno; } public Long getCsIdn() { return csIdn; } public void setCsIdn(Long csIdn) { this.csIdn = csIdn; } public Long getBmYear() { return bmYear; } public void setBmYear(Long bmYear) { this.bmYear = bmYear; } public Date getBmBilldt() { return bmBilldt; } public void setBmBilldt(Date bmBilldt) { this.bmBilldt = bmBilldt; } public Date getBmFromdt() { return bmFromdt; } public void setBmFromdt(Date bmFromdt) { this.bmFromdt = bmFromdt; } public Date getBmTodt() { return bmTodt; } public void setBmTodt(Date bmTodt) { this.bmTodt = bmTodt; } public Date getBmDuedate() { return bmDuedate; } public void setBmDuedate(Date bmDuedate) { this.bmDuedate = bmDuedate; } public double getBmTotalAmount() { return bmTotalAmount; } public void setBmTotalAmount(double bmTotalAmount) { this.bmTotalAmount = bmTotalAmount; } public double getBmTotalBalAmount() { return bmTotalBalAmount; } public void setBmTotalBalAmount(double bmTotalBalAmount) { this.bmTotalBalAmount = bmTotalBalAmount; } public double getBmIntValue() { return bmIntValue; } public void setBmIntValue(double bmIntValue) { this.bmIntValue = bmIntValue; } public double getBmTotalArrears() { return bmTotalArrears; } public void setBmTotalArrears(double bmTotalArrears) { this.bmTotalArrears = bmTotalArrears; } public double getBmTotalOutstanding() { return bmTotalOutstanding; } public void setBmTotalOutstanding(double bmTotalOutstanding) { this.bmTotalOutstanding = bmTotalOutstanding; } public double getBmTotalArrearsWithoutInt() { return bmTotalArrearsWithoutInt; } public void setBmTotalArrearsWithoutInt(double bmTotalArrearsWithoutInt) { this.bmTotalArrearsWithoutInt = bmTotalArrearsWithoutInt; } public double getBmTotalCumIntArrears() { return bmTotalCumIntArrears; } public void setBmTotalCumIntArrears(double bmTotalCumIntArrears) { this.bmTotalCumIntArrears = bmTotalCumIntArrears; } public double getBmToatlInt() { return bmToatlInt; } public void setBmToatlInt(double bmToatlInt) { this.bmToatlInt = bmToatlInt; } public double getBmLastRcptamt() { return bmLastRcptamt; } public void setBmLastRcptamt(double bmLastRcptamt) { this.bmLastRcptamt = bmLastRcptamt; } public Date getBmLastRcptdt() { return bmLastRcptdt; } public void setBmLastRcptdt(Date bmLastRcptdt) { this.bmLastRcptdt = bmLastRcptdt; } public double getBmToatlRebate() { return bmToatlRebate; } public void setBmToatlRebate(double bmToatlRebate) { this.bmToatlRebate = bmToatlRebate; } public String getBmPaidFlag() { return bmPaidFlag; } public void setBmPaidFlag(String bmPaidFlag) { this.bmPaidFlag = bmPaidFlag; } public double getBmFyTotalArrears() { return bmFyTotalArrears; } public void setBmFyTotalArrears(double bmFyTotalArrears) { this.bmFyTotalArrears = bmFyTotalArrears; } public double getBmFyTotalInt() { return bmFyTotalInt; } public void setBmFyTotalInt(double bmFyTotalInt) { this.bmFyTotalInt = bmFyTotalInt; } public String getFlagJvPost() { return flagJvPost; } public void setFlagJvPost(String flagJvPost) { this.flagJvPost = flagJvPost; } public Date getDistDate() { return distDate; } public void setDistDate(Date distDate) { this.distDate = distDate; } public String getBmRemarks() { return bmRemarks; } public void setBmRemarks(String bmRemarks) { this.bmRemarks = bmRemarks; } public Date getBmPrintdate() { return bmPrintdate; } public void setBmPrintdate(Date bmPrintdate) { this.bmPrintdate = bmPrintdate; } public String getArrearsBill() { return arrearsBill; } public void setArrearsBill(String arrearsBill) { this.arrearsBill = arrearsBill; } public double getBmTotpayamtAftdue() { return bmTotpayamtAftdue; } public void setBmTotpayamtAftdue(double bmTotpayamtAftdue) { this.bmTotpayamtAftdue = bmTotpayamtAftdue; } public double getBmIntamtAftdue() { return bmIntamtAftdue; } public void setBmIntamtAftdue(double bmIntamtAftdue) { this.bmIntamtAftdue = bmIntamtAftdue; } public String getBmIntType() { return bmIntType; } public void setBmIntType(String bmIntType) { this.bmIntType = bmIntType; } public BigDecimal getBmTrdPremis() { return bmTrdPremis; } public void setBmTrdPremis(BigDecimal bmTrdPremis) { this.bmTrdPremis = bmTrdPremis; } public BigDecimal getBmCcnSize() { return bmCcnSize; } public void setBmCcnSize(BigDecimal bmCcnSize) { this.bmCcnSize = bmCcnSize; } public String getBmCcnOwner() { return bmCcnOwner; } public void setBmCcnOwner(String bmCcnOwner) { this.bmCcnOwner = bmCcnOwner; } public String getBmEntryFlag() { return bmEntryFlag; } public void setBmEntryFlag(String bmEntryFlag) { this.bmEntryFlag = bmEntryFlag; } public String getBmIntChargedFlag() { return bmIntChargedFlag; } public void setBmIntChargedFlag(String bmIntChargedFlag) { this.bmIntChargedFlag = bmIntChargedFlag; } public Long getAmendForBillId() { return amendForBillId; } public void setAmendForBillId(Long amendForBillId) { this.amendForBillId = amendForBillId; } public String getBmMeteredccn() { return bmMeteredccn; } public void setBmMeteredccn(String bmMeteredccn) { this.bmMeteredccn = bmMeteredccn; } public Date getBmDuedate2() { return bmDuedate2; } public void setBmDuedate2(Date bmDuedate2) { this.bmDuedate2 = bmDuedate2; } public String getChShdIntChargedFlag() { return chShdIntChargedFlag; } public void setChShdIntChargedFlag(String chShdIntChargedFlag) { this.chShdIntChargedFlag = chShdIntChargedFlag; } public double getBmSecDepAmt() { return bmSecDepAmt; } public void setBmSecDepAmt(double bmSecDepAmt) { this.bmSecDepAmt = bmSecDepAmt; } public String getBmLastSecDepRcptno() { return bmLastSecDepRcptno; } public void setBmLastSecDepRcptno(String bmLastSecDepRcptno) { this.bmLastSecDepRcptno = bmLastSecDepRcptno; } public Date getBmLastSecDepRcptdt() { return bmLastSecDepRcptdt; } public void setBmLastSecDepRcptdt(Date bmLastSecDepRcptdt) { this.bmLastSecDepRcptdt = bmLastSecDepRcptdt; } public Long getOrgid() { return orgid; } public void setOrgid(Long orgid) { this.orgid = orgid; } public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public int getLangId() { return langId; } public void setLangId(int langId) { this.langId = langId; } public Date getLmoddate() { return lmoddate; } public void setLmoddate(Date lmoddate) { this.lmoddate = lmoddate; } public Date getIntFrom() { return intFrom; } public void setIntFrom(Date intFrom) { this.intFrom = intFrom; } public Date getIntTo() { return intTo; } public void setIntTo(Date intTo) { this.intTo = intTo; } public BigDecimal getFyiIntArrears() { return fyiIntArrears; } public void setFyiIntArrears(BigDecimal fyiIntArrears) { this.fyiIntArrears = fyiIntArrears; } public BigDecimal getFyiIntPerc() { return fyiIntPerc; } public void setFyiIntPerc(BigDecimal fyiIntPerc) { this.fyiIntPerc = fyiIntPerc; } public List<TbBillDet> getTbWtBillDet() { return tbWtBillDet; } public void setTbWtBillDet(List<TbBillDet> tbWtBillDet) { this.tbWtBillDet = tbWtBillDet; } public TbCsmrInfoDTO getWaterMas() { return waterMas; } public void setWaterMas(TbCsmrInfoDTO waterMas) { this.waterMas = waterMas; } public TbMeterMas getMeterMas() { return meterMas; } public void setMeterMas(TbMeterMas meterMas) { this.meterMas = meterMas; } public MeterReadingDTO getMeterRead() { return meterRead; } public void setMeterRead(MeterReadingDTO meterRead) { this.meterRead = meterRead; } public String getConnectionCategory() { return connectionCategory; } public void setConnectionCategory(String connectionCategory) { this.connectionCategory = connectionCategory; } public String getTarriffCategory() { return tarriffCategory; } public void setTarriffCategory(String tarriffCategory) { this.tarriffCategory = tarriffCategory; } public String getConSize() { return conSize; } public void setConSize(String conSize) { this.conSize = conSize; } public double getGrandTotal() { return grandTotal; } public void setGrandTotal(double grandTotal) { this.grandTotal = grandTotal; } public double getArrearsTotal() { return arrearsTotal; } public void setArrearsTotal(double arrearsTotal) { this.arrearsTotal = arrearsTotal; } public double getTaxtotal() { return taxtotal; } public void setTaxtotal(double taxtotal) { this.taxtotal = taxtotal; } public String getAmountInwords() { return amountInwords; } public void setAmountInwords(String amountInwords) { this.amountInwords = amountInwords; } public String getPmPropno() { return pmPropno; } public void setPmPropno(String pmPropno) { this.pmPropno = pmPropno; } public Long getRmRcptid() { return rmRcptid; } public void setRmRcptid(Long rmRcptid) { this.rmRcptid = rmRcptid; } public String getBmNo() { return bmNo; } public void setBmNo(String bmNo) { this.bmNo = bmNo; } public double getExcessAmount() { return excessAmount; } public void setExcessAmount(double excessAmount) { this.excessAmount = excessAmount; } public double getRebateAmount() { return rebateAmount; } public void setRebateAmount(double rebateAmount) { this.rebateAmount = rebateAmount; } }
gpl-3.0
alexeq/datacrown
datacrow-client/_source/net/datacrow/console/components/DcFontRenderingComboBox.java
2690
/****************************************************************************** * __ * * <-----/@@\-----> * * <-< < \\// > >-> * * <-<-\ __ /->-> * * Data / \ Crow * * ^ ^ * * info@datacrow.net * * * * This file is part of Data Crow. * * Data Crow 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 any later version. * * * * Data Crow is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public * * License along with this program. If not, see http://www.gnu.org/licenses * * * ******************************************************************************/ package net.datacrow.console.components; import net.datacrow.core.resources.DcResources; public class DcFontRenderingComboBox extends DcComboBox { public DcFontRenderingComboBox() { super(); addItem(DcResources.getText("lblDefault")); addItem("LCD HRGB"); addItem("LCD HBGR"); addItem("LCD VRGB"); addItem("LCD VBGR"); } @Override public void setValue(Object value) { if (value instanceof Long) setSelectedIndex(((Long) value).intValue()); else setSelectedItem(value); } @Override public Object getValue() { int index = getSelectedIndex(); index = index == -1 ? 0 : index; return Long.valueOf(index); } }
gpl-3.0
pressgang-ccms/PressGangCCMSQuery
src/main/java/org/jboss/pressgang/ccms/filter/base/BaseFilterQueryBuilderWithProperties.java
4829
/* Copyright 2011-2014 Red Hat, Inc This file is part of PressGang CCMS. PressGang CCMS is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. PressGang CCMS 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 PressGang CCMS. If not, see <http://www.gnu.org/licenses/>. */ package org.jboss.pressgang.ccms.filter.base; import javax.persistence.EntityManager; import javax.persistence.criteria.Subquery; import java.util.Map; import org.jboss.pressgang.ccms.filter.structures.FilterFieldBooleanMapData; import org.jboss.pressgang.ccms.filter.structures.FilterFieldDataBase; import org.jboss.pressgang.ccms.filter.structures.FilterFieldStringMapData; import org.jboss.pressgang.ccms.model.base.ToPropertyTag; import org.jboss.pressgang.ccms.utils.constants.CommonFilterConstants; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Provides the query elements required by Filter.buildQuery() to get a list of Entities that have extended properties. * * @param <T> The Type of entity that should be returned by the query builder. * @param <U> The Type of the entity to PropertyTag mapping. */ public abstract class BaseFilterQueryBuilderWithProperties<T, U extends ToPropertyTag<U>> extends BaseFilterQueryBuilder<T> { private static final Logger LOG = LoggerFactory.getLogger(BaseFilterQueryBuilderWithProperties.class); protected BaseFilterQueryBuilderWithProperties(final Class<T> clazz, final BaseFieldFilter fieldFilter, final EntityManager entityManager) { super(clazz, fieldFilter, entityManager); } @Override public void processField(final FilterFieldDataBase<?> field) { final String fieldName = field.getBaseName(); if (fieldName.equals(CommonFilterConstants.PROPERTY_TAG_EXISTS)) { final FilterFieldBooleanMapData mapField = (FilterFieldBooleanMapData) field; for (final Map.Entry<Integer, Boolean> entry : mapField.getData().entrySet()) { final Integer propertyTagId = entry.getKey(); final Boolean fieldValueBoolean = entry.getValue(); if (propertyTagId != null && fieldValueBoolean) { addExistsCondition(getPropertyTagExistsSubquery(propertyTagId)); } } } else if (fieldName.startsWith(CommonFilterConstants.PROPERTY_TAG_NOT_EXISTS)) { final FilterFieldBooleanMapData mapField = (FilterFieldBooleanMapData) field; for (final Map.Entry<Integer, Boolean> entry : mapField.getData().entrySet()) { final Integer propertyTagId = entry.getKey(); final Boolean fieldValueBoolean = entry.getValue(); if (propertyTagId != null && fieldValueBoolean) { addNotExistsCondition(getPropertyTagExistsSubquery(propertyTagId)); } } } else if (fieldName.startsWith(CommonFilterConstants.PROPERTY_TAG)) { final FilterFieldStringMapData mapField = (FilterFieldStringMapData) field; for (final Map.Entry<Integer, String> entry : mapField.getData().entrySet()) { final Integer propertyTagId = entry.getKey(); final String fieldValue = entry.getValue(); if (propertyTagId != null && fieldValue != null) { addExistsCondition(getPropertyTagSubquery(propertyTagId, fieldValue)); } } } else { super.processField(field); } } /** * Create a Subquery to check if a topic has a property tag with a specific value. * * @param propertyTagId The ID of the property tag to be checked. * @param propertyTagValue The Value that the property tag should have. * @return A subquery that can be used in an exists statement to see if a topic has a property tag with the specified value. */ protected abstract Subquery<U> getPropertyTagSubquery(final Integer propertyTagId, final String propertyTagValue); /** * Create a Subquery to check if a entity has a property tag exists. * * @param propertyTagId The ID of the property tag to be checked. * @return A subquery that can be used in an exists statement to see if a topic has a property tag. */ protected abstract Subquery<U> getPropertyTagExistsSubquery(final Integer propertyTagId); }
gpl-3.0
mmoMinecraftDev/mmoInfoOnline
src/main/java/mmo/Info/mmoInfoOnline.java
2711
/* * This file is part of mmoInfoOnline <http://github.com/mmoMinecraftDev/mmoInfoOnline>. * * mmoInfoOnline is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package mmo.Info; import java.util.HashMap; import mmo.Core.InfoAPI.MMOInfoEvent; import mmo.Core.MMOPlugin; import mmo.Core.MMOPlugin.Support; import mmo.Core.util.EnumBitSet; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.player.PlayerMoveEvent; import org.bukkit.plugin.PluginManager; import org.getspout.spoutapi.gui.GenericLabel; import org.getspout.spoutapi.gui.Label; import org.getspout.spoutapi.gui.Screen; import org.getspout.spoutapi.player.SpoutPlayer; public class mmoInfoOnline extends MMOPlugin implements Listener { private HashMap<Player, CustomLabel> widgets = new HashMap(); public EnumBitSet mmoSupport(EnumBitSet support) { support.set(MMOPlugin.Support.MMO_NO_CONFIG); support.set(MMOPlugin.Support.MMO_AUTO_EXTRACT); return support; } public void onEnable() { super.onEnable(); this.pm.registerEvents(this, this); } @EventHandler public void onPlayerMove(PlayerMoveEvent event) { CustomLabel label = (CustomLabel)this.widgets.get(event.getPlayer()); if (label != null) label.change(); } @EventHandler public void onMMOInfo(MMOInfoEvent event) { if (event.isToken("online")) { SpoutPlayer player = event.getPlayer(); if (player.hasPermission("mmo.info.online")) { CustomLabel label = (CustomLabel)new CustomLabel().setResize(true).setFixed(true); label.setText("100/100"); this.widgets.put(player, label); event.setWidget(this.plugin, label); event.setIcon("player.png"); } else { event.setCancelled(true); } } } public class CustomLabel extends GenericLabel { private boolean check = true; public CustomLabel() { } public void change() { this.check = true; } private transient int tick = 0; public void onTick() { if (tick++ % 100 == 0) { setText(String.format(" " + getServer().getOnlinePlayers().length + "/" + getServer().getMaxPlayers())); } } } }
gpl-3.0
pantelis60/L2Scripts_Underground
dist/gameserver/data/scripts/ai/Kama63Minion.java
2867
package ai; import java.util.concurrent.ScheduledFuture; import l2s.commons.threading.RunnableImpl; import l2s.commons.util.Rnd; import l2s.gameserver.ThreadPoolManager; import l2s.gameserver.ai.CtrlEvent; import l2s.gameserver.ai.Fighter; import l2s.gameserver.model.Creature; import l2s.gameserver.model.World; import l2s.gameserver.model.instances.NpcInstance; import l2s.gameserver.scripts.Functions; /** * АИ для камалоки 63 уровня. * Каждые 30 секунд босс призывает миньона, который через 25 секунд совершает суицид и восстанавливает здоровье * боса. * @author SYS */ public class Kama63Minion extends Fighter { private static final int BOSS_ID = 18571; private static final int MINION_DIE_TIME = 25000; private long _wait_timeout = 0; private NpcInstance _boss; private boolean _spawned = false; ScheduledFuture<?> _dieTask = null; public Kama63Minion(NpcInstance actor) { super(actor); } @Override protected void onEvtSpawn() { _boss = findBoss(BOSS_ID); super.onEvtSpawn(); } @Override protected boolean thinkActive() { if(_boss == null) _boss = findBoss(BOSS_ID); else if(!_spawned) { _spawned = true; Functions.npcSayCustomMessage(_boss, "Kama63Boss"); NpcInstance minion = getActor(); minion.getAI().notifyEvent(CtrlEvent.EVT_AGGRESSION, _boss.getAggroList().getRandomHated(getMaxPursueRange()), Rnd.get(1, 100)); _dieTask = ThreadPoolManager.getInstance().schedule(new DieScheduleTimerTask(minion, _boss), MINION_DIE_TIME); } return super.thinkActive(); } private NpcInstance findBoss(int npcId) { // Ищем боса не чаще, чем раз в 15 секунд, если по каким-то причинам его нету if(System.currentTimeMillis() < _wait_timeout) return null; _wait_timeout = System.currentTimeMillis() + 15000; NpcInstance minion = getActor(); if(minion == null) return null; for(NpcInstance npc : World.getAroundNpc(minion)) if(npc.getNpcId() == npcId) return npc; return null; } @Override protected void onEvtDead(Creature killer) { _spawned = false; if(_dieTask != null) { _dieTask.cancel(false); _dieTask = null; } super.onEvtDead(killer); } public class DieScheduleTimerTask extends RunnableImpl { NpcInstance _minion = null; NpcInstance _master = null; public DieScheduleTimerTask(NpcInstance minion, NpcInstance master) { _minion = minion; _master = master; } @Override public void runImpl() { if(_master != null && _minion != null && !_master.isDead() && !_minion.isDead()) _master.setCurrentHp(_master.getCurrentHp() + _minion.getCurrentHp() * 5, false); Functions.npcSayCustomMessage(_minion, "Kama63Minion"); _minion.doDie(_minion); } } }
gpl-3.0
ENGYS/HELYX-OS
src/eu/engys/vtk/actions/ExtractSelection.java
14224
/******************************************************************************* * | o | * | o o | HELYX-OS: The Open Source GUI for OpenFOAM | * | o O o | Copyright (C) 2012-2016 ENGYS | * | o o | http://www.engys.com | * | o | | * |---------------------------------------------------------------------------| * | License | * | This file is part of HELYX-OS. | * | | * | HELYX-OS 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. | * | | * | HELYX-OS 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 HELYX-OS; if not, write to the Free Software Foundation, | * | Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA | *******************************************************************************/ package eu.engys.vtk.actions; import java.util.HashSet; import java.util.Set; import javax.vecmath.Vector3d; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import eu.engys.gui.view3D.PickInfo; import eu.engys.gui.view3D.Selection; import eu.engys.gui.view3D.Selection.SelectionMode; import vtk.vtkCellData; import vtk.vtkDataArray; import vtk.vtkDataSet; import vtk.vtkExtractPolyDataGeometry; import vtk.vtkExtractSelection; import vtk.vtkFloatArray; import vtk.vtkGeometryFilter; import vtk.vtkIdFilter; import vtk.vtkIdList; import vtk.vtkIdTypeArray; import vtk.vtkPolyData; import vtk.vtkPolyDataNormals; import vtk.vtkSelection; import vtk.vtkSelectionNode; public class ExtractSelection { private static final Logger logger = LoggerFactory.getLogger(ExtractSelection.class); private Selection selection; private vtkPolyData selectionData; private vtkPolyData inverseSelectionData; private vtkIdTypeArray list; public void setSelection(Selection selection) { this.selection = selection; } public void execute(PickInfo pi) { String name = (pi.actor != null ? pi.actor.getName() : null); logger.debug("------------- PICK --------------"); logger.debug(" ACTOR : " + name); logger.debug(" CELL : " + pi.cellId); logger.debug(" FRUSTUM : " + (pi.frustum != null ? pi.frustum.GetClassName() : "null")); if (selection.getDataSet() != null) { logger.debug(" DATASET 1 "); logger.debug(" hashcode : " + selection.getDataSet().hashCode()); logger.debug(" cells : " + selection.getDataSet().GetNumberOfCells()); logger.debug(" point : " + selection.getDataSet().GetNumberOfPoints()); } else { logger.debug(" DATASET 1 : " + "null"); } if (pi.dataSet != null) { logger.debug(" DATASET 2 "); logger.debug(" hashcode : " + pi.dataSet.hashCode()); logger.debug(" cells : " + pi.dataSet.GetNumberOfCells()); logger.debug(" points : " + pi.dataSet.GetNumberOfPoints()); } else { logger.debug(" DATASET 2 : " + "null"); } boolean keepSelection = selection.isKeepSelection() || pi.control; // if (selection.getDataSet() != pi.dataSet) { // return; // } if (keepSelection) { logger.debug("SELECTION: KEEP"); this.list = selection.getIdList() != null ? selection.getIdList() : new vtkIdTypeArray(); } else { logger.debug("SELECTION: DISCARD"); this.list = new vtkIdTypeArray(); } switch (selection.getType()) { case CELL: logger.debug("PICK BY: CELL"); pickByCell(pi); break; case AREA: logger.debug("PICK BY: AREA"); pickByArea(pi); break; case FEATURE: logger.debug("PICK BY: FEATURE"); pickByFeature(pi); break; default: break; } applySelection(selection.getDataSet()); selection.setSelectionData(selectionData); selection.setInverseSelectionData(inverseSelectionData); selection.setIdList(list); logger.debug("SELECTION cells: "+selectionData.GetNumberOfCells()); logger.debug("SELECTION points: "+selectionData.GetNumberOfPoints()); logger.debug("---------------------------"); } private void pickByCell(PickInfo pi) { int cellId = pi.cellId; if (cellId < 0) return; performSelection(cellId); } private void pickByArea(PickInfo pi) { if (pi.frustum != null && pi.dataSet != null) { vtkDataSet input = selection.getDataSet();//pi.dataSet; vtkIdFilter idFilter = new vtkIdFilter(); idFilter.CellIdsOn(); // idFilter.PointIdsOff(); // idFilter.FieldDataOff(); idFilter.SetIdsArrayName("originalCellIds"); idFilter.SetInputData(input); idFilter.Update(); vtkExtractPolyDataGeometry extractor = new vtkExtractPolyDataGeometry(); extractor.SetInputData(idFilter.GetOutput()); extractor.ExtractInsideOn(); extractor.ExtractBoundaryCellsOff(); extractor.SetImplicitFunction(pi.frustum); extractor.Update(); vtkDataSet output = extractor.GetOutput(); vtkIdTypeArray ids = (vtkIdTypeArray) output.GetCellData().GetArray("originalCellIds"); if (ids != null) { for (int i = 0; i < ids.GetNumberOfTuples(); i++) { int id = ids.GetValue(i); performSelection(id); } } // vtkExtractSelectedFrustum extractor = new vtkExtractSelectedFrustum(); // extractor.SetInput(pi.dataSet); // extractor.ShowBoundsOff(); // extractor.PreserveTopologyOff(); // extractor.SetFrustum(pi.frustum); // extractor.Update(); // vtkDataSet output = (vtkDataSet) extractor.GetOutput(); // // vtkIdTypeArray ids = (vtkIdTypeArray) output.GetCellData().GetArray("vtkOriginalCellIds"); // if (ids != null) { // for (int i = 0; i < ids.GetNumberOfTuples(); i++) { // performSelection(ids.GetValue(i)); // } // } } } private void pickByFeature(PickInfo pi) { double[] normal = pi.normal; vtkDataSet input = selection.getDataSet();//pi.dataSet; if (input == null) return; int cellId = pi.cellId; if (cellId < 0) return; vtkPolyData output = getNormalsDataSet(normal, input); Set<Integer> cells = new HashSet<>(); if (output.GetNumberOfCells() > 0 ) { analyseNeighbours(cellId, output, cells); performSelection(cellId); for (Integer id : cells) { performSelection(id); } } output.Delete(); } private vtkPolyData getNormalsDataSet(double[] normal, vtkDataSet dataSet) { vtkPolyDataNormals normalsFilter = new vtkPolyDataNormals(); normalsFilter.SetInputData(dataSet); normalsFilter.SplittingOff(); normalsFilter.SetFeatureAngle(60); normalsFilter.ComputeCellNormalsOn(); normalsFilter.FlipNormalsOff(); normalsFilter.AutoOrientNormalsOff(); normalsFilter.ConsistencyOff(); normalsFilter.Update(); vtkPolyData output = normalsFilter.GetOutput(); vtkCellData outputData = output.GetCellData(); vtkDataArray normals = outputData.GetVectors("Normals"); vtkFloatArray angles = new vtkFloatArray(); angles.SetName("Angles"); if (normals != null) { for (int i = 0; i < normals.GetNumberOfTuples(); i++) { double[] t = normals.GetTuple3(i); double a = computeAngle(t, normal); angles.InsertNextValue(a); } } outputData.AddArray(angles); normalsFilter.Delete(); angles.Delete(); normals.Delete(); return output; } private void analyseNeighbours(int cellId, vtkPolyData output, Set<Integer> cells) { vtkCellData outputData = output.GetCellData(); vtkDataArray angles = outputData.GetVectors("Angles"); vtkIdList cellPointIds = new vtkIdList(); output.GetCellPoints(cellId, cellPointIds); // neighbor cells may be listed multiple times // use set instead of list to get a unique list of neighbors Set<Integer> neighbors = new HashSet<>(); /* * For each vertice of the cell, we calculate which cells uses that * point. So if we make this, for each vertice, we have all the * neighbors. In the case we use ''cellPointIds'' as a parameter of * ''GeteCellNeighbors'', we will obtain an empty set. Because the only * cell that is using that set of points is the current one. That is why * we have to make each vertice at time. */ for (int i = 0; i < cellPointIds.GetNumberOfIds(); i++) { vtkIdList idList = new vtkIdList(); idList.InsertNextId(cellPointIds.GetId(i)); // get the neighbors of the cell vtkIdList neighborCellIds = new vtkIdList(); output.GetCellNeighbors(cellId, idList, neighborCellIds); for (int j = 0; j < neighborCellIds.GetNumberOfIds(); j++) { int id = neighborCellIds.GetId(j); double angle = angles.GetComponent(id, 0)%180; if (angle < selection.getFeatureAngle()) { neighbors.add(id); } } } Set<Integer> newCells = new HashSet<>(); for (Integer id : neighbors) { if (!cells.contains(id)) { newCells.add(id); cells.add(id); } } if (!newCells.isEmpty()) { for (Integer newCell : newCells) { analyseNeighbours(newCell, output, cells); } } } private double computeAngle(double[] t, double[] normal) { Vector3d v = new Vector3d(t); Vector3d n = new Vector3d(normal); double angle = n.angle(v); return Math.toDegrees(angle); } private void performSelection(int cellId) { if (selection.getMode() == SelectionMode.SELECT) { select(cellId); } else { deselect(cellId); } } private void select(int cellId) { list.InsertNextValue(cellId); } private void deselect(int cellId) { int index = -1; if ((index = alreadySelected(cellId)) >= 0) { list.RemoveTuple(index); } } private int alreadySelected(int cellId) { for (int i = 0; i < list.GetNumberOfTuples(); i++) { if (list.GetValue(i) == cellId) { return i; } } return -1; } private void applySelection(vtkDataSet dataSet) { vtkSelection selection = new vtkSelection(); vtkSelectionNode node = new vtkSelectionNode(); node.SetContentType(4); //INDICES node.SetFieldType(0); //CELL node.SetSelectionList(list); selection.AddNode(node); vtkExtractSelection filter = new vtkExtractSelection(); filter.SetInputData(0, dataSet); filter.SetInputData(1, selection); filter.Update(); vtkGeometryFilter geom = new vtkGeometryFilter(); geom.SetInputData(filter.GetOutput()); geom.Update(); selectionData = geom.GetOutput(); selection.Delete(); node.Delete(); filter.Delete(); geom.Delete(); selection = new vtkSelection(); node = new vtkSelectionNode(); node.SetContentType(4); // INDICES node.SetFieldType(0); // CELL node.SetSelectionList(list); node.GetProperties().Set(node.INVERSE(), 1); selection.AddNode(node); filter = new vtkExtractSelection(); filter.SetInputData(0, dataSet); filter.SetInputData(1, selection); // VTKProgressConsoleWrapper progressWrapper = new VTKProgressConsoleWrapper("", filter, monitor); // filter.AddObserver("StartEvent", progressWrapper, "onStart"); // filter.AddObserver("EndEvent", progressWrapper, "onEnd"); // filter.AddObserver("ProgressEvent", progressWrapper, "onProgress"); filter.Update(); geom = new vtkGeometryFilter(); geom.SetInputData(filter.GetOutput()); geom.Update(); inverseSelectionData = geom.GetOutput(); selection.Delete(); node.Delete(); filter.Delete(); geom.Delete(); } }
gpl-3.0
PE-INTERNATIONAL/soda4lca
Node/src/main/java/de/iai/ilcd/model/dao/DataSetRegistrationDataDao.java
742
package de.iai.ilcd.model.dao; import java.util.List; import de.iai.ilcd.model.process.Process; import de.iai.ilcd.model.registry.DataSetRegistrationData; public interface DataSetRegistrationDataDao extends GenericDAO<DataSetRegistrationData, Long> { List<DataSetRegistrationData> getRegistered( Long registryId ); List<DataSetRegistrationData> getRegisteredNotAccepted( Long registryId ); List<DataSetRegistrationData> getRegisteredAccepted( Long registryId ); List<DataSetRegistrationData> getRegisteredPendingDeregistration( Long registryId ); List<DataSetRegistrationData> getListOfRegistrations( Process process ); DataSetRegistrationData findByUUIDAndVersionAndRegistry( String UUID, String version, Long registryId ); }
gpl-3.0
mkulesh/microMathematics
app/src/main/java/javax/measure/quantity/Frequency.java
858
/* * JScience - Java(TM) Tools and Libraries for the Advancement of Sciences. * Copyright (C) 2006 - JScience (http://jscience.org/) * All rights reserved. * * Permission to use, copy, modify, and distribute this software is * freely granted, provided that this notice is preserved. */ package javax.measure.quantity; import javax.measure.unit.SI; import javax.measure.unit.Unit; /** * This interface represents the number of times a specified phenomenon occurs * within a specified interval. The system unit for this quantity is "Hz" * (Hertz). * * @author <a href="mailto:jean-marie@dautelle.com">Jean-Marie Dautelle</a> * @version 1.0, January 14, 2006 */ public interface Frequency extends Quantity { /** * Holds the SI unit (Système International d'Unités) for this quantity. */ Unit<Frequency> UNIT = SI.HERTZ; }
gpl-3.0
pantelis60/L2Scripts_Underground
gameserver/src/main/java/l2s/gameserver/network/l2/s2c/ExVitalityPointInfo.java
273
package l2s.gameserver.network.l2.s2c; public class ExVitalityPointInfo extends L2GameServerPacket { private final int _vitality; public ExVitalityPointInfo(int vitality) { _vitality = vitality; } @Override protected void writeImpl() { writeD(_vitality); } }
gpl-3.0
skyllias/alomatia
src/main/java/org/skyllias/alomatia/ui/filter/FilterSelectorComposer.java
7925
package org.skyllias.alomatia.ui.filter; import java.awt.Component; import java.awt.Dimension; import java.util.Collection; import java.util.LinkedList; import javax.swing.JPanel; import javax.swing.JRadioButton; import javax.swing.JTextField; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.text.BadLocationException; import javax.swing.text.Document; import org.apache.commons.lang.StringUtils; import org.skyllias.alomatia.display.FilterableDisplay; import org.skyllias.alomatia.filter.FilterFactory; import org.skyllias.alomatia.filter.NamedFilter; import org.skyllias.alomatia.i18n.LabelLocalizer; import org.skyllias.alomatia.ui.BasicControlPanelComposer; import org.skyllias.alomatia.ui.RadioSelector; import org.skyllias.alomatia.ui.RadioSelector.RadioSelectorListener; /** Composer of a selector of the filter to apply in a {@link FilterableDisplay}. */ public class FilterSelectorComposer implements RadioSelectorListener<NamedFilter> { protected static final String FILTER_LABEL = "filter.selector.title"; protected static final String SEARCH_LABEL = "filter.selector.search"; private final FilterSearchHistoryFactory filterSearchHistoryFactory; private final HistorySuggestionDecorator historySuggestionDecorator; private final LabelLocalizer labelLocalizer; private final FilterableDisplay filterableDisplay; private final FilterFactory factory; private final Collection<FilterSelectionListener> filterSelectionListeners = new LinkedList<>(); //============================================================================== /** Creates a new selector that will modify the passed display's filter with * one of the items from filterFactory. */ public FilterSelectorComposer(LabelLocalizer localizer, FilterableDisplay imageDisplay, FilterFactory filterFactory) { this(localizer, imageDisplay, filterFactory, new FilterSearchHistoryFactory(), new HistorySuggestionDecorator()); } //------------------------------------------------------------------------------ protected FilterSelectorComposer(LabelLocalizer localizer, FilterableDisplay imageDisplay, FilterFactory filterFactory, FilterSearchHistoryFactory filterSearchHistoryFactory, HistorySuggestionDecorator historySuggestionDecorator) { labelLocalizer = localizer; filterableDisplay = imageDisplay; factory = filterFactory; this.filterSearchHistoryFactory = filterSearchHistoryFactory; this.historySuggestionDecorator = historySuggestionDecorator; } //============================================================================== /** Returns a new component with the filter controls set up. */ public FilterSelector createFilterSelector() { final JPanel panel = new BasicControlPanelComposer().getPanel(labelLocalizer.getString(FILTER_LABEL)); JTextField searchField = createSearchField(panel); panel.add(searchField); RadioSelector<JRadioButton, NamedFilter> radioSelector = new RadioSelector<>(JRadioButton.class, labelLocalizer, this); for (NamedFilter namedFilter : factory.getAllAvailableFilters()) // consider sorting them { panel.add(radioSelector.createRadioObject(namedFilter.getNameKey(), namedFilter)); } return new FilterSelector(panel, radioSelector); } //------------------------------------------------------------------------------ /** Sets the selected filter to the image display. */ @Override public void onSelectionChanged(NamedFilter filter) { filterableDisplay.setImageFilter(filter); for (FilterSelectionListener filterSelectionListener : filterSelectionListeners) { filterSelectionListener.onFilterSelected(); } } //------------------------------------------------------------------------------ private JTextField createSearchField(final JPanel panel) { JTextField searchField = new JTextField(); searchField.setName(SEARCH_LABEL); searchField.setToolTipText(labelLocalizer.getString(SEARCH_LABEL)); searchField.setMaximumSize(new Dimension(Integer.MAX_VALUE, searchField.getPreferredSize().height)); // prevent the containing layout from streching the field vertically searchField.getDocument().addDocumentListener(new SearchFieldListener(panel)); FilterSearchHistory filterSearchHistory = filterSearchHistoryFactory.newInstance(); historySuggestionDecorator.decorate(searchField, filterSearchHistory); filterSelectionListeners.add(new FilterSearchHistoryUpdateListener(searchField, filterSearchHistory)); return searchField; } //------------------------------------------------------------------------------ /* Loops over all the radio buttons in panel and hides those that do not * contain text in their label or action command, showing the others. */ private void searchFilters(String text, JPanel panel) { String caselessText = text.toLowerCase(); for (Component childComponent : panel.getComponents()) { if (childComponent instanceof JRadioButton) { JRadioButton radioButton = (JRadioButton) childComponent; String caselessLabel = radioButton.getText().toLowerCase(); String caselessCommand = radioButton.getActionCommand().toLowerCase(); boolean matching = caselessLabel.contains(caselessText) || caselessCommand.contains(caselessText); radioButton.setVisible(matching); } } } //------------------------------------------------------------------------------ //****************************************************************************** private final class SearchFieldListener implements DocumentListener { private final JPanel panel; private SearchFieldListener(JPanel panel) { this.panel = panel; } @Override public void removeUpdate(DocumentEvent e) {searchFilters(e);} @Override public void insertUpdate(DocumentEvent e) {searchFilters(e);} @Override public void changedUpdate(DocumentEvent e) {searchFilters(e);} private void searchFilters(DocumentEvent e) { try { Document document = e.getDocument(); int textLength = document.getLength(); String fullText = document.getText(0, textLength); FilterSelectorComposer.this.searchFilters(fullText, panel); } catch (BadLocationException ble) {} // TODO manage exceptions } } //****************************************************************************** /* Interface to get notified whenever a new filter is selected. */ private static interface FilterSelectionListener { void onFilterSelected(); } //****************************************************************************** /* FilterSelectionListener that registers the non-empty contents of a text * field in a FilterSearchHistory. */ private static class FilterSearchHistoryUpdateListener implements FilterSelectionListener { private final JTextField searchField; private final FilterSearchHistory filterSearchHistory; public FilterSearchHistoryUpdateListener(JTextField searchField, FilterSearchHistory filterSearchHistory) { this.searchField = searchField; this.filterSearchHistory = filterSearchHistory; } @Override public void onFilterSelected() { String currentSearch = searchField.getText(); if (StringUtils.isNotBlank(currentSearch)) filterSearchHistory.registerSearchString(currentSearch); } } //****************************************************************************** }
gpl-3.0
westernarc/midnightsun
src/STG/shot/Bullet.java
2228
/* * Copyright 2012 Adrian Micayabas <deepspace30@gmail.com> * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ package STG.shot; import com.jme3.export.JmeExporter; import com.jme3.export.JmeImporter; import com.jme3.renderer.RenderManager; import com.jme3.renderer.ViewPort; import com.jme3.scene.Spatial; import com.jme3.scene.control.Control; import java.io.IOException; /** * * @author Adrian */ public class Bullet implements Control { float timescale = 1; public void setTimescale(float ts) { timescale = ts; } public float getTimescale() { return timescale; } public Control cloneForSpatial(Spatial spatial) { throw new UnsupportedOperationException("Not supported yet."); } public void setSpatial(Spatial spatial) { throw new UnsupportedOperationException("Not supported yet."); } public void setEnabled(boolean enabled) { throw new UnsupportedOperationException("Not supported yet."); } public boolean isEnabled() { throw new UnsupportedOperationException("Not supported yet."); } public void update(float tpf) { throw new UnsupportedOperationException("Not supported yet."); } public void render(RenderManager rm, ViewPort vp) { throw new UnsupportedOperationException("Not supported yet."); } public void write(JmeExporter ex) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } public void read(JmeImporter im) throws IOException { throw new UnsupportedOperationException("Not supported yet."); } }
gpl-3.0