public static void main(String[] args) { if (genPeople) { deleteDir(dirPeople); Generator g = new Generator(); List<Person> people = g.generateRandom(100); RdfFoafGenerator rdfGen = new RdfFoafGenerator(people); for (Person p : people) { writeRdf("people", p.getUid(), rdfGen.generatePerson(p)); } } if (genSkills) { deleteDir(dirSkills); for (String s : Skill.skills) { writeRdf("skills", s.replaceAll("\\s", ""), SkillsRDFGenerator.generateSkill(s)); } } if (genLevels) { deleteDir(dirLevels); for (String l : Skill.levels) { writeRdf("levels", l.replaceAll("\\s", ""), SkillsRDFGenerator.generateLevel(l)); } } System.out.println("End"); }
public static Person newInstance(Integer id, String name, Date birthDate) { Person person = new Person(); person.setId(id); person.setName(name); person.setBirthDate(birthDate); return person; }
@Test public void testLegAttributesIO() { final Population population = PopulationUtils.createPopulation(ConfigUtils.createConfig()); final Person person = population.getFactory().createPerson(Id.createPersonId("Donald Trump")); population.addPerson(person); final Plan plan = population.getFactory().createPlan(); person.addPlan(plan); final Leg leg = population.getFactory().createLeg("SUV"); plan.addActivity( population.getFactory().createActivityFromLinkId("speech", Id.createLinkId(1))); plan.addLeg(leg); plan.addActivity(population.getFactory().createActivityFromLinkId("tweet", Id.createLinkId(2))); leg.getAttributes().putAttribute("mpg", 0.000001d); final String file = utils.getOutputDirectory() + "/population.xml"; new PopulationWriter(population).writeV6(file); final Scenario readScenario = ScenarioUtils.createScenario(ConfigUtils.createConfig()); new PopulationReader(readScenario).readFile(file); final Person readPerson = readScenario.getPopulation().getPersons().get(Id.createPersonId("Donald Trump")); final Leg readLeg = (Leg) readPerson.getSelectedPlan().getPlanElements().get(1); Assert.assertEquals( "Unexpected Double attribute in " + readLeg.getAttributes(), leg.getAttributes().getAttribute("mpg"), readLeg.getAttributes().getAttribute("mpg")); }
public void changeName(Person who) { if (who.getName().equals("설까치")) { who = new Person("둘리"); } else if (who.getName().equals("홍길동")) { who = new Person("고길동"); } }
@Test public void testActivityAttributesIO() { final Population population = PopulationUtils.createPopulation(ConfigUtils.createConfig()); final Person person = population.getFactory().createPerson(Id.createPersonId("Donald Trump")); population.addPerson(person); final Plan plan = population.getFactory().createPlan(); person.addPlan(plan); final Activity act = population.getFactory().createActivityFromCoord("speech", new Coord(0, 0)); plan.addActivity(act); act.getAttributes().putAttribute("makes sense", false); act.getAttributes().putAttribute("length", 1895L); final String file = utils.getOutputDirectory() + "/population.xml"; new PopulationWriter(population).writeV6(file); final Scenario readScenario = ScenarioUtils.createScenario(ConfigUtils.createConfig()); new PopulationReader(readScenario).readFile(file); final Person readPerson = readScenario.getPopulation().getPersons().get(Id.createPersonId("Donald Trump")); final Activity readAct = (Activity) readPerson.getSelectedPlan().getPlanElements().get(0); Assert.assertEquals( "Unexpected boolean attribute in " + readAct.getAttributes(), act.getAttributes().getAttribute("makes sense"), readAct.getAttributes().getAttribute("makes sense")); Assert.assertEquals( "Unexpected Long attribute in " + readAct.getAttributes(), act.getAttributes().getAttribute("length"), readAct.getAttributes().getAttribute("length")); }
public static synchronized void create(String array[]) { SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy", Locale.ENGLISH); Date date; Person person; for (int i = 1; i < array.length; i++) { if (array[i].equals("м")) { try { date = format.parse(array[++i]); --i; person = Person.createMale(array[--i], date); ++i; allPeople.add(person); System.out.println(allPeople.indexOf(person)); } catch (ParseException e) { } } if (array[i].equals("ж")) { try { date = format.parse(array[++i]); --i; person = Person.createFemale(array[--i], date); ++i; allPeople.add(person); System.out.println(allPeople.indexOf(person)); } catch (ParseException e) { } } } }
@Test public void testJPALockScope() { doInJPA( this::entityManagerFactory, entityManager -> { Person person = new Person("John Doe"); entityManager.persist(person); Phone home = new Phone("123-456-7890"); Phone office = new Phone("098-765-4321"); person.getPhones().add(home); person.getPhones().add(office); entityManager.persist(person); }); doInJPA( this::entityManagerFactory, entityManager -> { log.info("testJPALockScope"); Long id = 1L; // tag::locking-jpa-query-hints-scope-example[] Person person = entityManager.find( Person.class, id, LockModeType.PESSIMISTIC_WRITE, Collections.singletonMap( "javax.persistence.lock.scope", PessimisticLockScope.EXTENDED)); // end::locking-jpa-query-hints-scope-example[] assertEquals(2, person.getPhones().size()); }); }
public static void main(String[] args) throws Exception { SparkConf sparkConf = new SparkConf().setAppName("JavaSparkSQL"); JavaSparkContext javaSparkContext = new JavaSparkContext(sparkConf); SQLContext sqlContext = new SQLContext(javaSparkContext); System.out.println("=== Data source: RDD ==="); // Load a text file and convert each line to a Java Bean. JavaRDD<Person> people = javaSparkContext .textFile("people.txt") .map( (line) -> { String[] parts = line.split(","); Person person = new Person(); person.setName(parts[0]); person.setAge(parts[1]); return person; }); // Apply a schema to an RDD of Java Beans and register it as a table. DataFrame dataFrame = sqlContext.createDataFrame(people, Person.class); dataFrame.registerTempTable("people"); // SQL can be run over RDDs that have been registered as tables. DataFrame teenagers = sqlContext.sql("SELECT name FROM people WHERE age >= 13 AND age <= 19"); // 通过DataFrame 获取对应的RDD collection 获取对应的结果内容 List<String> teenagersName = teenagers.toJavaRDD().map((row) -> "Name : " + row.getString(0)).collect(); teenagersName.forEach( (name) -> { System.out.println(name); }); }
/** * Redefinition of OnRecieve method from Actor. This class handles messages of EndDay and Person * types. */ public void onReceive(Object message) throws Exception { /* * If Person, add them to the list of jailed people. */ if (message instanceof Person) { Person p = (Person) message; printToTerminal("Person " + p.getPersonId() + " arrives at jail."); // System.err.println("Person " + p.getPersonId() // + " arrives at jail."); jailed.add(p); printToTerminal("Person " + p.getPersonId() + " placed in cell."); } /* * When EndDay received, increment the number of stations that have * shut down. When the number of stations shut down has reached the * number of stations. Print the List of all people in the jail and * shutdown all Actors */ else if (message instanceof EndDay) { numStationsClosed++; printToTerminal("Jail recieved end of day message " + numStationsClosed); if (numStationsClosed == numSecurityStations) { printJailed(); printToTerminal("Jail Closed"); getContext().stop(); } } /* * All other messages are errors. Message printed here for debugging * purposes. */ else { System.err.println("Security recieved invalid message: " + message.toString()); } }
@Test public void invokeListSizeMethod() throws PropertyAccessException { // create initial object relation Person peter = new Person("Peter"); List<String> foreNames = new ArrayList<String>(); foreNames.add("blub"); foreNames.add("blub2"); foreNames.add("blub3"); peter.setForeNamesAsList(foreNames); PropertyPathStart start = new PropertyPathStart(); start.setName("this"); start.setContentType(ParameterContentType.FIELD); PropertyPath path = new PropertyPath(); path.setName("foreNamesAsList"); start.setPathToContinue(path); PropertyPath path2 = new PropertyPath(); path2.setName("size()"); path.setPathToContinue(path2); String result = propertyAccessor.getPropertyContent(start, peter, null, resultValueMock); assertThat(Integer.parseInt(result), is(3)); Mockito.verifyZeroInteractions(resultValueMock); }
@Override public String toXML() { StringBuffer buffer = new StringBuffer(); buffer.append("<event>"); buffer.append(super.toXML()); buffer.append("<name>" + name + "</name>"); buffer.append("<location>" + location + "</location>"); buffer.append("<type>" + type + "</type>"); buffer.append("<other>" + other + "</other>"); buffer.append("<description>" + description + "</description>"); buffer.append("<dateTime>" + Utilities.getISODate(this.dateTime) + "</dateTime>"); buffer.append("<pictures>"); for (Picture picture : pictures) { buffer.append(picture.toXML()); } buffer.append("</pictures>"); buffer.append("<children>"); for (Person child : children) { buffer.append(child.toXML("child")); } buffer.append("</children>"); buffer.append("</event>"); return buffer.toString(); }
public static void main(String[] args) { // Part 1 Turtle t1, t2, t3; t1 = new Turtle(); t2 = new Turtle("Larry"); t3 = new Turtle("kevin", 100, 500); System.out.println("Turtle 1 is called" + " " + t1.getname()); System.out.println("Turtle 1 is" + " " + t1.getage() + " " + "years old"); System.out.println("Turtle 1 is going at" + " " + t1.getspeed() + " " + "mph"); System.out.println("Turtle 2 is called" + " " + t2.getname()); System.out.println("Turtle 2 is" + " " + t2.getage() + " " + "years old"); System.out.println("Turtle 2 is going at" + " " + t2.getspeed() + " " + "mph"); System.out.println("--------------------------"); // Part 2 Person p1; p1 = new Person("Vincent"); p1.setTurtle(t1); System.out.println(p1.getPersonName() + "'s turtle's speed is" + " " + p1.getTurtleSpeed()); System.out.println(p1.getPersonName() + "'s turtle's name is" + " " + p1.getPet()); }
// Faculty names are not added to the external courses by default // this method should fix ssp-3041 - Scody private void updateFactultyNames(ExternalStudentRecordsTO recordTO) { List<ExternalStudentTranscriptCourseTO> courses = recordTO.getTerms(); if (courses != null) { for (ExternalStudentTranscriptCourseTO course : courses) { try { Person person = !StringUtils.isNotBlank(course.getFacultySchoolId()) ? null : personService.getInternalOrExternalPersonBySchoolId( course.getFacultySchoolId(), false); // TODO: getInternalOrExternalPersonBySchoolId is slow refactor? if (person != null) { course.setFacultyName(person.getFullName()); } } catch (ObjectNotFoundException e) { course.setFacultyName("None Listed"); LOGGER.debug( "FACULTY SCHOOL ID WAS NOT RESOLVED WHILE LOADING TRANSCRIPT RECORD. Faculty School_id: " + course.getFacultySchoolId() + " Student ID: " + course.getSchoolId() + " Course: " + course.getFormattedCourse()); } } } }
@Test @Priority(10) public void initData() { Session session = openSession(); // Rev 1 session.getTransaction().begin(); Person p = new Person(); Name n = new Name(); n.setName("name1"); p.getNames().add(n); session.saveOrUpdate(p); session.getTransaction().commit(); // Rev 2 session.getTransaction().begin(); n.setName("Changed name"); session.saveOrUpdate(p); session.getTransaction().commit(); // Rev 3 session.getTransaction().begin(); Name n2 = new Name(); n2.setName("name2"); p.getNames().add(n2); session.getTransaction().commit(); personId = p.getId(); }
@Test public void test_sql_custom_crud() { Person _person = doInJPA( entityManager -> { Person person = new Person(); person.setName("John Doe"); entityManager.persist(person); return person; }); doInJPA( entityManager -> { Long postId = _person.getId(); Person person = entityManager.find(Person.class, postId); assertNotNull(person); entityManager.remove(person); }); doInJPA( entityManager -> { Long postId = _person.getId(); Person person = entityManager.find(Person.class, postId); assertNull(person); }); }
public Hospital() { super(); // TODO Auto-generated constructor stub patient.setPatient("honey singh"); patient.setId(1); patient.setHealthStatus(HealthStatus.BAD); }
@Test public void convertsJodaTimeTypesCorrectly() { List<Converter<?, ?>> converters = new ArrayList<Converter<?, ?>>(); converters.add(new LocalDateToDateConverter()); converters.add(new DateToLocalDateConverter()); List<Class<?>> customSimpleTypes = new ArrayList<Class<?>>(); customSimpleTypes.add(LocalDate.class); mappingContext.setCustomSimpleTypes(customSimpleTypes); converter = new MappingMongoConverter(mappingContext); converter.setConverters(converters); converter.afterPropertiesSet(); Person person = new Person(); person.birthDate = new LocalDate(); DBObject dbObject = new BasicDBObject(); converter.write(person, dbObject); assertTrue(dbObject.get("birthDate") instanceof Date); Person result = converter.read(Person.class, dbObject); assertThat(result.birthDate, is(notNullValue())); }
@Test public void test() { final Person person = Shroud.shroud(new Lando()).map("talk", "eat").map("eat", "talk").as(Person.class); assertEquals("baloney", person.talk()); assertEquals("words", person.eat()); }
public void sendMessage(final Person person) { System.out.println("Producer sends " + person); Map<String, Object> map = new HashMap<String, Object>(); map.put("name", person.getName()); map.put("age", person.getAge()); getJmsTemplate().convertAndSend(map); }
public void testToString() { Person p4 = new Person(); p4.setName("Fred Flintstone"); p4.setMaximumBooks(7); String testString = "Fred Flintstone (7 books)"; assertEquals(testString, p4.toString()); }
@Test public void testLazyLoadedOneToOne() { Datastore ds = new RedisDatastore(); ds.getMappingContext().addPersistentEntity(Person.class); Session conn = ds.connect(); Person p = new Person(); p.setName("Bob"); Address a = new Address(); a.setNumber("22"); a.setPostCode("308420"); p.setAddress(a); conn.persist(p); p = (Person) conn.retrieve(Person.class, p.getId()); Address proxy = p.getAddress(); assertTrue(proxy instanceof javassist.util.proxy.ProxyObject); assertTrue(proxy instanceof EntityProxy); EntityProxy ep = (EntityProxy) proxy; assertFalse(ep.isInitialized()); assertEquals(a.getId(), proxy.getId()); assertFalse(ep.isInitialized()); assertEquals("22", a.getNumber()); }
@Test public void testRequestClientValidation() { Person person = new Person(); try { disconnectedClient.saveValidateOut(person); fail("Expected exception"); } catch (SOAPFaultException sfe) { assertTrue(sfe.getMessage().contains("Marshalling Error")); } person.setFirstName(""); // empty string is valid try { disconnectedClient.saveValidateOut(person); fail("Expected exception"); } catch (SOAPFaultException sfe) { assertTrue(sfe.getMessage().contains("Marshalling Error")); } person.setLastName(""); // empty string is valid // this confirms that we passed client validation as we then got the connectivity error try { disconnectedClient.saveValidateOut(person); fail("Expected exception"); } catch (WebServiceException e) { assertTrue(e.getMessage().contains("Could not send Message")); } }
private static NumericMatrix getMatrix(Collection<PlainPerson> persons, LegPredicate pred) { NumericMatrix m = new NumericMatrix(); for (Person person : persons) { for (Episode episode : person.getEpisodes()) { for (int i = 0; i < episode.getLegs().size(); i++) { Segment leg = episode.getLegs().get(i); if (pred.test(leg)) { Segment prev = episode.getActivities().get(i); Segment next = episode.getActivities().get(i + 1); String origin = prev.getAttribute(SetZones.ZONE_KEY); String dest = next.getAttribute(SetZones.ZONE_KEY); if (origin != null && dest != null) { m.add(origin, dest, 1); String touched = leg.getAttribute(DBG_TOUCHED); int cnt = 0; if (touched != null) cnt = Integer.parseInt(touched); leg.setAttribute(DBG_TOUCHED, String.valueOf(cnt + 1)); } } } } } return m; }
public static Person deepCopy(Person person, String id, Factory factory) { Person clone = shallowCopy(person, id, factory); for (Episode e : person.getEpisodes()) { clone.addEpisode(deepCopy(e, factory)); } return clone; }
@Test public void testCoord3dIO() { final Population population = PopulationUtils.createPopulation(ConfigUtils.createConfig()); final Person person = population.getFactory().createPerson(Id.createPersonId("Donald Trump")); population.addPerson(person); final Plan plan = population.getFactory().createPlan(); person.addPlan(plan); plan.addActivity(population.getFactory().createActivityFromCoord("speech", new Coord(0, 0))); plan.addActivity( population.getFactory().createActivityFromCoord("tweet", new Coord(0, 0, -100))); final String file = utils.getOutputDirectory() + "/population.xml"; new PopulationWriter(population).writeV6(file); final Scenario readScenario = ScenarioUtils.createScenario(ConfigUtils.createConfig()); new PopulationReader(readScenario).readFile(file); final Person readPerson = readScenario.getPopulation().getPersons().get(Id.createPersonId("Donald Trump")); final Activity readSpeach = (Activity) readPerson.getSelectedPlan().getPlanElements().get(0); final Activity readTweet = (Activity) readPerson.getSelectedPlan().getPlanElements().get(1); Assert.assertFalse( "did not expect Z value in " + readSpeach.getCoord(), readSpeach.getCoord().hasZ()); Assert.assertTrue("did expect T value in " + readTweet.getCoord(), readTweet.getCoord().hasZ()); Assert.assertEquals( "unexpected Z value in " + readTweet.getCoord(), -100, readTweet.getCoord().getZ(), MatsimTestUtils.EPSILON); }
public static void main(String[] args) throws Exception { Thread.sleep(5000); Person.method(); Person p = new Person("java", 20); p.show(); }
public static final void main(String[] args) { try { // load up the knowledge base KnowledgeBase kbase = readKnowledgeBase(); StatefulKnowledgeSession ksession = kbase.newStatefulKnowledgeSession(); KnowledgeRuntimeLogger logger = KnowledgeRuntimeLoggerFactory.newThreadedFileLogger(ksession, "test", 1000); ksession.getWorkItemManager().registerWorkItemHandler("Human Task", new WSHumanTaskHandler()); // start a new process instance by setup of a Person and Request. Person person = new Person("erics", "Eric D. Schabell"); person.setAge(43); Request request = new Request("1"); request.setPersonId("erics"); request.setAmount(1999); ksession.insert(person); // put them in the Map to be passed to the startProcess. Map<String, Object> params = new HashMap<String, Object>(); params.put("person", person); params.put("request", request); // Fire it up! WorkflowProcessInstance processInstance = (WorkflowProcessInstance) ksession.startProcess("org.jbpm.demo.rulenode", params); ksession.insert(processInstance); ksession.fireAllRules(); // Finished, clean up the logger. System.out.println("Process Ended."); logger.close(); } catch (Throwable t) { t.printStackTrace(); } }
// Getting All Persons public List<Person> getAllPersons() { List<Person> personList = new ArrayList<Person>(); // Select All Query String selectQuery = "SELECT * FROM " + TABLE_PEOPLE; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); // looping through all rows and adding to list if (cursor.moveToFirst()) { do { Person person = new Person(); person.setID(Integer.parseInt(cursor.getString(0))); person.setName(cursor.getString(1)); person.setZIP(cursor.getString(2)); person.setAge(cursor.getString(3)); // Adding person to list personList.add(person); System.out.println("-->DO<--"); } while (cursor.moveToNext()); } // return person list return personList; }
public static void main(String[] args) { Person p = new Person("John", "Jones"); System.out.println(p.getFirstName()); System.out.println(p.getLastName()); Account acct = new Account(p, 1); acct.deposit(100); System.out.println(acct.getBalance()); acct.deposit(45.50); System.out.println(acct.getBalance()); if (acct.withdraw(95)) { System.out.println("New Balance is " + acct.getBalance()); } else { System.out.println("insufficent funds"); } if (acct.withdraw(100)) { System.out.println("New Balance is " + acct.getBalance()); } else { System.out.println("insufficent funds"); } System.out.println("Owner is: " + acct.getOwnersName()); System.out.println("Account number is: " + acct.getAcctNumber()); System.out.println("Transaction History: " + acct.getTransactions()); }
private static void dropDepTimes(Population population) { for (Person pers : population.getPersons().values()) { for (Plan p : pers.getPlans()) { ((Activity) p.getPlanElements().get(0)).setEndTime(0); } } }