text
stringlengths
10
2.72M
package scut218.pisces.beans; /** * Created by Lenovo on 2018/3/14. */ public class Request { }
package lawscraper.server.entities.law; import lawscraper.server.entities.superclasses.NameId; import javax.persistence.Entity; import javax.persistence.Table; /** * Created by erik, IT Bolaget Per & Per AB * Date: 10/2/12 * Time: 8:05 PM */ @Entity @Table(name = "consolidation") public class Consolidation extends NameId { }
import org.junit.jupiter.api.Test; import java.time.Duration; import java.time.LocalDate; import java.util.Date; import static org.junit.jupiter.api.Assertions.*; class DiscographyTDD { @Test void testTrack1() { Track track = new Track("You and I", Duration.ofMinutes(10).plusSeconds(8), false); assertEquals(track.getTitle(), "You and I"); assertEquals(track.getDuration(), Duration.ofMinutes(10).plusSeconds(8)); assertFalse(track.isBonusTrack()); } @Test void testTrack2() { Track track2 = new Track("America", Duration.ofMinutes(4).plusSeconds(12), true); assertEquals(track2.getTitle(), "America"); assertEquals(track2.duration, Duration.ofMinutes(4).plusSeconds(12)); assertTrue(track2.isBonusTrack()); } @Test void testEmptyRecordCreation() { Record record = new Record("single", "Under Production", LocalDate.of(2074, 10, 6)); assertEquals("single", record.getType()); assertEquals("Under production", record.getTitle()); assertEquals(LocalDate.of(2074, 10, 6), record.getReleaseDate()); assertEquals(0, record.getTrackCount()); assertEquals(Duration.ofSeconds(0), record.getPlayTime()); } @Test void testRecordCreationWithTwoTracks() { Record record = new Record("album", "Close to the Edge", LocalDate.of(1972, 9, 13)); assertEquals("album", record.getType()); assertEquals("Close to the Edge", record.getTitle()); assertEquals(LocalDate.of(1972, 9, 13), record.getReleaseDate()); assertEquals(2, record.getTrackCount()); assertEquals(Duration.ofMinutes(14).plusSeconds(20), record.getPlayTime()); } @Test void testEmptyDiscography() { Discography discography = new Discography("Future Artist"); assertEquals("Future Artist", discography.getArtistName()); assertEquals(0, discography.getRecordCount()); } @Test void testDiscographyWithOneRecord() { Discography discography = new Discography("Yes"); assertEquals("Yes", discography.getArtistName()); assertEquals(1, discography.getRecordCount()); assertEquals("Close to the Edge", discography.getAlbum()); } }
package com.trump.auction.web.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.trump.auction.activity.constant.ActivityConstant; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; import com.trump.auction.account.enums.EnumAccountType; import com.trump.auction.cust.api.UserProductCollectStubService; import com.trump.auction.trade.api.AuctionInfoStubService; import com.trump.auction.trade.model.AuctionInfoModel; import com.trump.auction.web.service.PersonalService; import com.trump.auction.web.service.SignService; import com.trump.auction.web.util.HandleResult; import com.trump.auction.web.util.RedisContants; import redis.clients.jedis.JedisCluster; import java.math.BigDecimal; import java.util.Map; /** * 签到 * Created by songruihuan on 2017/12/20. */ @Controller public class SignController extends BaseController{ Logger logger = LoggerFactory.getLogger(SignController.class); @Autowired private SignService signService; @Autowired private PersonalService personalService; @Autowired private JedisCluster jedisCluster; @Value("${aliyun.oss.domain}") private String aliyunOssDomain; @Value("${static.resources.domain}") private String staticResourcesDomain; @Autowired private UserProductCollectStubService userProductCollectStubService; @Autowired private AuctionInfoStubService auctionInfoStubService; /** * 签到规则 * @return */ @RequestMapping("sign-rule") public String signRule(Model model){ model.addAttribute("staticResourcesDomain",staticResourcesDomain); return "sign-rule"; } /** * 签到 * @return */ @RequestMapping("sign-in") public String signIn(HttpServletRequest request, HttpServletResponse response, Model model){ String userId = getUserIdFromRedis(request); HandleResult result = signService.checkIsSigned(Integer.valueOf(userId)); if(result.isResult()){//已签到 model.addAttribute("signFlag",true); }else{//未签到 model.addAttribute("signFlag",false); signService.userSign(Integer.valueOf(userId));//去签到 } Map<String, String> signConfigMap = jedisCluster.hgetAll(ActivityConstant.USER_SIGN); int basePoints = Integer.parseInt(signConfigMap.get(ActivityConstant.BASE_POINTS)); int extraPoints = Integer.parseInt(signConfigMap.get(ActivityConstant.EXTRA_POINTS)); int signCycle = Integer.parseInt(signConfigMap.get(ActivityConstant.SIGN_CYCLE)); Integer seriesSignDays = signService.findUserSignByUserId(Integer.valueOf(userId)).getSeriesSignDays();//连续签到天数 if(seriesSignDays.intValue()==signCycle){ model.addAttribute("todayPoints",basePoints+extraPoints);//今天签到积分数 }else{ model.addAttribute("todayPoints",basePoints);//今天签到积分数 } //拍卖推荐 String str = jedisCluster.get(RedisContants.RECOMMEND_AUCTION_PRODS); JSONArray array = null; if(null!=str){ array =JSONArray.parseArray(str); }else{ array = new JSONArray(); } for(int i=0;i<array.size();i++){ JSONObject jsonObject = (JSONObject) array.get(i); String productId = (String) jsonObject.get("auctionProdId"); String auctionId = (String) jsonObject.get("auctionId"); /*AuctionInfoModel auctionInfoModel = auctionInfoStubService.getAuctionInfoById(Integer.valueOf(auctionId)); Integer status = auctionInfoModel.getStatus(); if(status.equals(1)){ jsonObject.put("bidPrice", auctionInfoModel.getIncreasePrice().multiply( new BigDecimal(auctionInfoModel.getTotalBidCount())).add(auctionInfoModel.getStartPrice())); }else{ jsonObject.put("bidPrice", auctionInfoModel.getFinalPrice()); }*/ boolean flag = userProductCollectStubService.checkUserProductCollect(Integer.valueOf(userId),Integer.valueOf(productId),Integer.valueOf(auctionId));//商品id 期数id jsonObject.put("flag",flag); } model.addAttribute("signCycle",signCycle);//签到周期 model.addAttribute("extraPoints",extraPoints);//签到额外分数 model.addAttribute("basePoints",basePoints);//签到基础分数 model.addAttribute("seriesSignDays",seriesSignDays);//连续签到天数 model.addAttribute("points",personalService.getAuctionCoinByUserId(Integer.valueOf(userId), EnumAccountType.POINTS.getKey()));//当前积分数 model.addAttribute("recommend",array); model.addAttribute("token",request.getHeader("userToken"));//request.getHeader("userToken"));//87381e8d4ec54f98a5926f1e48172007 model.addAttribute("aliyunOssDomain",aliyunOssDomain); model.addAttribute("staticResourcesDomain",staticResourcesDomain); return "sign-in"; } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.context.groovy; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Properties; import groovy.lang.GroovyShell; import org.junit.jupiter.api.Test; import org.springframework.aop.SpringProxy; import org.springframework.beans.factory.BeanIsAbstractException; import org.springframework.beans.factory.ObjectFactory; import org.springframework.beans.factory.config.Scope; import org.springframework.beans.factory.groovy.GroovyBeanDefinitionReader; import org.springframework.context.support.GenericApplicationContext; import org.springframework.context.support.GenericGroovyApplicationContext; import org.springframework.core.io.ByteArrayResource; import org.springframework.stereotype.Component; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatExceptionOfType; /** * Tests for {@link GroovyBeanDefinitionReader}. * * @author Jeff Brown * @author Dave Syer * @author Sam Brannen */ class GroovyBeanDefinitionReaderTests { @Test void importSpringXml() { GenericApplicationContext appCtx = new GenericApplicationContext(); loadGroovyDsl(appCtx, """ beans { importBeans "classpath:org/springframework/context/groovy/test.xml" } """); assertThat(appCtx.getBean("foo")).isEqualTo("hello"); } @Test void importBeansFromGroovy() { GenericApplicationContext appCtx = new GenericApplicationContext(); loadGroovyDsl(appCtx, """ beans { importBeans "classpath:org/springframework/context/groovy/applicationContext.groovy" } """); assertThat(appCtx.getBean("foo")).isEqualTo("hello"); } @Test void singletonPropertyOnBeanDefinition() { GenericApplicationContext appCtx = new GenericApplicationContext(); loadGroovyDsl(appCtx, """ package org.springframework.context.groovy; beans { singletonBean(Bean1Impl) { bean -> bean.singleton = true } nonSingletonBean(Bean1Impl) { bean -> bean.singleton = false } unSpecifiedScopeBean(Bean1Impl) } """); assertThat(appCtx.isSingleton("singletonBean")).as("singletonBean should have been a singleton").isTrue(); assertThat(appCtx.isSingleton("nonSingletonBean")).as("nonSingletonBean should not have been a singleton").isFalse(); assertThat(appCtx.isSingleton("unSpecifiedScopeBean")).as("unSpecifiedScopeBean should not have been a singleton").isTrue(); } @Test void inheritPropertiesFromAbstractBean() { GenericApplicationContext appCtx = new GenericApplicationContext(); loadGroovyDsl(appCtx, """ package org.springframework.context.groovy; beans { myB(Bean1Impl) { person = "wombat" } myAbstractA(Bean2) { bean -> bean."abstract" = true age = 10 bean1 = myB } myConcreteB { it.parent = myAbstractA } } """); Bean2 bean = (Bean2) appCtx.getBean("myConcreteB"); assertThat(bean.getAge()).isEqualTo(10); assertThat(bean.bean1).isNotNull(); } @Test void contextComponentScanSpringTag() { GenericApplicationContext appCtx = new GenericApplicationContext(); loadGroovyDsl(appCtx, """ beans { xmlns context:"http://www.springframework.org/schema/context" context.'component-scan'( 'base-package':"org.springframework.context.groovy" ) } """); assertThat(appCtx.getBean("person")).isInstanceOf(AdvisedPerson.class); } @Test void useSpringNamespaceAsMethod() { GenericApplicationContext appCtx = new GenericApplicationContext(); loadGroovyDsl(appCtx, """ package org.springframework.context.groovy; beans { xmlns aop:"http://www.springframework.org/schema/aop" fred(AdvisedPersonImpl) { name = "Fred" age = 45 } birthdayCardSenderAspect(BirthdayCardSender) aop { config("proxy-target-class": false) { aspect(id: "sendBirthdayCard", ref: "birthdayCardSenderAspect") { after method: "onBirthday", pointcut: "execution(void org.springframework.context.groovy.AdvisedPerson.birthday()) and this(person)" } } } } """); AdvisedPerson fred = (AdvisedPerson) appCtx.getBean("fred"); assertThat(fred).isInstanceOf(SpringProxy.class); fred.birthday(); BirthdayCardSender birthDaySender = (BirthdayCardSender) appCtx.getBean("birthdayCardSenderAspect"); assertThat(birthDaySender.peopleSentCards).hasSize(1); assertThat(birthDaySender.peopleSentCards.get(0).getName()).isEqualTo("Fred"); } @Test @SuppressWarnings("unchecked") void useTwoSpringNamespaces() { GenericApplicationContext appCtx = new GenericApplicationContext(); TestScope scope = new TestScope(); appCtx.getBeanFactory().registerScope("test", scope); loadGroovyDsl(appCtx, """ package org.springframework.context.groovy beans { xmlns aop:"http://www.springframework.org/schema/aop" xmlns util:"http://www.springframework.org/schema/util" bean1(Bean1Impl) { bean -> bean.scope = "test" aop.'scoped-proxy'("proxy-target-class": false) } util.list(id: 'foo') { value 'one' value 'two' } } """); assertThat((List<String>)appCtx.getBean("foo")).containsExactly("one", "two"); assertThat(appCtx.getBean("bean1")).isNotNull(); assertThat(((Bean1)appCtx.getBean("bean1")).getPerson()).isNull(); assertThat(((Bean1)appCtx.getBean("bean1")).getPerson()).isNull(); // should only be true because bean not initialized until proxy called assertThat(scope.instanceCount).isEqualTo(2); appCtx = new GenericApplicationContext(); appCtx.getBeanFactory().registerScope("test", scope); loadGroovyDsl(appCtx, """ package org.springframework.context.groovy import java.util.ArrayList beans { xmlns aop:"http://www.springframework.org/schema/aop", util:"http://www.springframework.org/schema/util" bean1(Bean1Impl) { bean -> bean.scope = "test" aop.'scoped-proxy'("proxy-target-class": false) } util.list(id: 'foo') { value 'one' value 'two' } } """); assertThat((List<String>)appCtx.getBean("foo")).containsExactly("one", "two"); assertThat(appCtx.getBean("bean1")).isNotNull(); assertThat(((Bean1)appCtx.getBean("bean1")).getPerson()).isNull(); assertThat(((Bean1)appCtx.getBean("bean1")).getPerson()).isNull(); // should only be true because bean not initialized until proxy called assertThat(scope.instanceCount).isEqualTo(4); } @Test void springAopSupport() { GenericApplicationContext appCtx = new GenericApplicationContext(); loadGroovyDsl(appCtx, """ package org.springframework.context.groovy beans { xmlns aop:"http://www.springframework.org/schema/aop" fred(AdvisedPersonImpl) { name = "Fred" age = 45 } birthdayCardSenderAspect(BirthdayCardSender) aop.config("proxy-target-class": false) { aspect(id: "sendBirthdayCard", ref: "birthdayCardSenderAspect") { after method:"onBirthday", pointcut: "execution(void org.springframework.context.groovy.AdvisedPerson.birthday()) and this(person)" } } } """); AdvisedPerson fred = (AdvisedPerson) appCtx.getBean("fred"); assertThat(fred).isInstanceOf(SpringProxy.class); fred.birthday(); BirthdayCardSender birthDaySender = (BirthdayCardSender) appCtx.getBean("birthdayCardSenderAspect"); assertThat(birthDaySender.peopleSentCards).hasSize(1); assertThat(birthDaySender.peopleSentCards.get(0).getName()).isEqualTo("Fred"); } @Test void springScopedProxyBean() { GenericApplicationContext appCtx = new GenericApplicationContext(); TestScope scope = new TestScope(); appCtx.getBeanFactory().registerScope("test", scope); loadGroovyDsl(appCtx, """ package org.springframework.context.groovy beans { xmlns aop:"http://www.springframework.org/schema/aop" bean1(Bean1Impl) { bean -> bean.scope = "test" aop.'scoped-proxy'('proxy-target-class': false) } } """); assertThat(appCtx.getBean("bean1")).isNotNull(); assertThat(((Bean1)appCtx.getBean("bean1")).getPerson()).isNull(); assertThat(((Bean1)appCtx.getBean("bean1")).getPerson()).isNull(); // should only be true because bean not initialized until proxy called assertThat(scope.instanceCount).isEqualTo(2); } @Test @SuppressWarnings("unchecked") void springNamespaceBean() { GenericApplicationContext appCtx = new GenericApplicationContext(); loadGroovyDsl(appCtx, """ package org.springframework.context.groovy beans { xmlns util: 'http://www.springframework.org/schema/util' util.list(id: 'foo') { value 'one' value 'two' } } """); assertThat((List<String>) appCtx.getBean("foo")).containsExactly("one", "two"); } @Test void namedArgumentConstructor() { GenericApplicationContext appCtx = new GenericApplicationContext(); loadGroovyDsl(appCtx, """ package org.springframework.context.groovy beans { holyGrail(HolyGrailQuest) knights(KnightsOfTheRoundTable, "Camelot", leader: "lancelot", quest: holyGrail) } """); KnightsOfTheRoundTable knights = (KnightsOfTheRoundTable) appCtx.getBean("knights"); HolyGrailQuest quest = (HolyGrailQuest) appCtx.getBean("holyGrail"); assertThat(knights.getName()).isEqualTo("Camelot"); assertThat(knights.leader).isEqualTo("lancelot"); assertThat(knights.quest).isEqualTo(quest); } @Test void abstractBeanDefinition() { GenericApplicationContext appCtx = new GenericApplicationContext(); loadGroovyDsl(appCtx, """ package org.springframework.context.groovy beans { abstractBean { leader = "Lancelot" } quest(HolyGrailQuest) knights(KnightsOfTheRoundTable, "Camelot") { bean -> bean.parent = abstractBean quest = quest } } """); KnightsOfTheRoundTable knights = (KnightsOfTheRoundTable) appCtx.getBean("knights"); assertThat(knights).isNotNull(); assertThatExceptionOfType(BeanIsAbstractException.class) .isThrownBy(() -> appCtx.getBean("abstractBean")); assertThat(knights.leader).isEqualTo("Lancelot"); appCtx.close(); } @Test void abstractBeanDefinitionWithClass() { GenericApplicationContext appCtx = new GenericApplicationContext(); loadGroovyDsl(appCtx, """ package org.springframework.context.groovy beans { abstractBean(KnightsOfTheRoundTable) { bean -> bean.'abstract' = true leader = "Lancelot" } quest(HolyGrailQuest) knights("Camelot") { bean -> bean.parent = abstractBean quest = quest } } """); assertThatExceptionOfType(BeanIsAbstractException.class) .isThrownBy(() -> appCtx.getBean("abstractBean")); KnightsOfTheRoundTable knights = (KnightsOfTheRoundTable) appCtx.getBean("knights"); assertThat(knights).isNotNull(); assertThat(knights.leader).isEqualTo("Lancelot"); appCtx.close(); } @Test void scopes() { GenericApplicationContext appCtx = new GenericApplicationContext(); loadGroovyDsl(appCtx, """ package org.springframework.context.groovy beans { myBean(ScopeTestBean) { bean -> bean.scope = "prototype" } myBean2(ScopeTestBean) } """); Object b1 = appCtx.getBean("myBean"); Object b2 = appCtx.getBean("myBean"); assertThat(b1).isNotSameAs(b2); b1 = appCtx.getBean("myBean2"); b2 = appCtx.getBean("myBean2"); assertThat(b1).isEqualTo(b2); appCtx.close(); } @Test void simpleBean() { GenericApplicationContext appCtx = new GenericApplicationContext(); loadGroovyDsl(appCtx, """ package org.springframework.context.groovy beans { bean1(Bean1Impl) { person = "homer" age = 45 props = [overweight:"true", height:"1.8m"] children = ["bart", "lisa"] } } """); assertThat(appCtx.containsBean("bean1")).isTrue(); Bean1 bean1 = (Bean1) appCtx.getBean("bean1"); assertThat(bean1.getPerson()).isEqualTo("homer"); assertThat(bean1.getAge()).isEqualTo(45); assertThat(bean1.getProps().getProperty("overweight")).isEqualTo("true"); assertThat(bean1.getProps().getProperty("height")).isEqualTo("1.8m"); assertThat(bean1.getChildren()).containsExactly("bart", "lisa"); appCtx.close(); } @Test void beanWithParentRef() { GenericApplicationContext parentAppCtx = new GenericApplicationContext(); loadGroovyDsl(parentAppCtx, """ package org.springframework.context.groovy beans { homer(Bean1Impl) { person = "homer" age = 45 props = [overweight:true, height:"1.8m"] children = ["bart", "lisa"] } } """); GenericApplicationContext appCtx = new GenericApplicationContext(parentAppCtx); loadGroovyDsl(appCtx, """ package org.springframework.context.groovy beans { bart(Bean2) { person = "bart" parent = ref("homer", true) } } """); assertThat(appCtx.containsBean("bart")).isTrue(); Bean2 bart = (Bean2) appCtx.getBean("bart"); assertThat(bart.parent.getPerson()).isEqualTo("homer"); } @Test void withAnonymousInnerBean() { GenericApplicationContext appCtx = new GenericApplicationContext(); loadGroovyDsl(appCtx, """ package org.springframework.context.groovy beans { bart(Bean1Impl) { person = "bart" age = 11 } lisa(Bean1Impl) { person = "lisa" age = 9 } marge(Bean2) { person = "marge" bean1 = { Bean1Impl b -> person = "homer" age = 45 props = [overweight:true, height:"1.8m"] children = ["bart", "lisa"] } children = [bart, lisa] } } """); Bean2 marge = (Bean2) appCtx.getBean("marge"); assertThat(marge.bean1.getPerson()).isEqualTo("homer"); } @Test void withUntypedAnonymousInnerBean() { GenericApplicationContext appCtx = new GenericApplicationContext(); loadGroovyDsl(appCtx, """ package org.springframework.context.groovy beans { homer(Bean1Factory) bart(Bean1Impl) { person = "bart" age = 11 } lisa(Bean1Impl) { person = "lisa" age = 9 } marge(Bean2) { person = "marge" bean1 = { bean -> bean.factoryBean = "homer" bean.factoryMethod = "newInstance" person = "homer" } children = [bart, lisa] } } """); Bean2 marge = (Bean2) appCtx.getBean("marge"); assertThat(marge.bean1.getPerson()).isEqualTo("homer"); } @Test void beanReferences() { GenericApplicationContext appCtx = new GenericApplicationContext(); loadGroovyDsl(appCtx, """ package org.springframework.context.groovy beans { homer(Bean1Impl) { person = "homer" age = 45 props = [overweight:true, height:"1.8m"] children = ["bart", "lisa"] } bart(Bean1Impl) { person = "bart" age = 11 } lisa(Bean1Impl) { person = "lisa" age = 9 } marge(Bean2) { person = "marge" bean1 = homer children = [bart, lisa] } } """); Object homer = appCtx.getBean("homer"); Bean2 marge = (Bean2) appCtx.getBean("marge"); Bean1 bart = (Bean1) appCtx.getBean("bart"); Bean1 lisa = (Bean1) appCtx.getBean("lisa"); assertThat(marge.bean1).isEqualTo(homer); assertThat(marge.getChildren()).hasSize(2); assertThat(marge.getChildren()).containsExactly(bart, lisa); } @Test void beanWithConstructor() { GenericApplicationContext appCtx = new GenericApplicationContext(); loadGroovyDsl(appCtx, """ package org.springframework.context.groovy beans { homer(Bean1Impl) { person = "homer" age = 45 } marge(Bean3, "marge", homer) { age = 40 } } """); Bean3 marge = (Bean3) appCtx.getBean("marge"); assertThat(marge.getPerson()).isEqualTo("marge"); assertThat(marge.bean1.getPerson()).isEqualTo("homer"); assertThat(marge.getAge()).isEqualTo(40); } @Test void beanWithFactoryMethod() { GenericApplicationContext appCtx = new GenericApplicationContext(); loadGroovyDsl(appCtx, """ package org.springframework.context.groovy beans { homer(Bean1Impl) { person = "homer" age = 45 } def marge = marge(Bean4) { person = "marge" } marge.factoryMethod = "getInstance" } """); Bean4 marge = (Bean4) appCtx.getBean("marge"); assertThat(marge.getPerson()).isEqualTo("marge"); } @Test void beanWithFactoryMethodUsingClosureArgs() { GenericApplicationContext appCtx = new GenericApplicationContext(); loadGroovyDsl(appCtx, """ package org.springframework.context.groovy beans { homer(Bean1Impl) { person = "homer" age = 45 } marge(Bean4) { bean -> bean.factoryMethod = "getInstance" person = "marge" } } """); Bean4 marge = (Bean4) appCtx.getBean("marge"); assertThat(marge.getPerson()).isEqualTo("marge"); } @Test void beanWithFactoryMethodWithConstructorArgs() { GenericApplicationContext appCtx = new GenericApplicationContext(); loadGroovyDsl(appCtx, """ package org.springframework.context.groovy beans { beanFactory(Bean1FactoryWithArgs){} homer(beanFactory:"newInstance", "homer") { age = 45 } //Test with no closure body marge(beanFactory:"newInstance", "marge") //Test more verbose method mcBain("mcBain") { bean -> bean.factoryBean="beanFactory" bean.factoryMethod="newInstance" } } """); Bean1 homer = (Bean1) appCtx.getBean("homer"); assertThat(homer.getPerson()).isEqualTo("homer"); assertThat(homer.getAge()).isEqualTo(45); assertThat(((Bean1)appCtx.getBean("marge")).getPerson()).isEqualTo("marge"); assertThat(((Bean1)appCtx.getBean("mcBain")).getPerson()).isEqualTo("mcBain"); } @Test void getBeanDefinitions() { GenericApplicationContext appCtx = new GenericApplicationContext(); GroovyBeanDefinitionReader reader = new GroovyBeanDefinitionReader(appCtx); reader.loadBeanDefinitions(new ByteArrayResource((""" package org.springframework.context.groovy beans { jeff(Bean1Impl) { person = 'jeff' } graeme(Bean1Impl) { person = 'graeme' } guillaume(Bean1Impl) { person = 'guillaume' } } """).getBytes())); appCtx.refresh(); assertThat(reader.getRegistry().getBeanDefinitionCount()).as("beanDefinitions was the wrong size").isEqualTo(3); assertThat(reader.getRegistry().getBeanDefinition("jeff")).as("beanDefinitions did not contain jeff").isNotNull(); assertThat(reader.getRegistry().getBeanDefinition("guillaume")).as("beanDefinitions did not contain guillaume").isNotNull(); assertThat(reader.getRegistry().getBeanDefinition("graeme")).as("beanDefinitions did not contain graeme").isNotNull(); } @Test void beanWithFactoryBean() { GenericApplicationContext appCtx = new GenericApplicationContext(); loadGroovyDsl(appCtx, """ package org.springframework.context.groovy beans { myFactory(Bean1Factory) homer(myFactory) { bean -> bean.factoryMethod = "newInstance" person = "homer" age = 45 } } """); Bean1 homer = (Bean1) appCtx.getBean("homer"); assertThat(homer.getPerson()).isEqualTo("homer"); } @Test void beanWithFactoryBeanAndMethod() { GenericApplicationContext appCtx = new GenericApplicationContext(); loadGroovyDsl(appCtx, """ package org.springframework.context.groovy beans { myFactory(Bean1Factory) homer(myFactory:"newInstance") { bean -> person = "homer" age = 45 } } """); Bean1 homer = (Bean1) appCtx.getBean("homer"); assertThat(homer.getPerson()).isEqualTo("homer"); } @Test void loadExternalBeans() { GenericApplicationContext appCtx = new GenericGroovyApplicationContext("org/springframework/context/groovy/applicationContext.groovy"); assertThat(appCtx.containsBean("foo")).isTrue(); assertThat(appCtx.getBean("foo")).isEqualTo("hello"); appCtx.close(); } @Test void loadExternalBeansWithExplicitRefresh() { GenericGroovyApplicationContext appCtx = new GenericGroovyApplicationContext("org/springframework/context/groovy/applicationContext.groovy"); assertThat(appCtx.containsBean("foo")).isTrue(); assertThat(appCtx.getBean("foo")).isEqualTo("hello"); appCtx.close(); } @Test void holyGrailWiring() { GenericApplicationContext appCtx = new GenericApplicationContext(); loadGroovyDsl(appCtx, """ package org.springframework.context.groovy beans { quest(HolyGrailQuest) knights(KnightsOfTheRoundTable, "Bedivere") { quest = ref("quest") } } """); KnightsOfTheRoundTable knights = (KnightsOfTheRoundTable) appCtx.getBean("knights"); knights.embarkOnQuest(); } @Test void abstractBeanSpecifyingClass() { GenericApplicationContext appCtx = new GenericApplicationContext(); loadGroovyDsl(appCtx, """ package org.springframework.context.groovy beans { abstractKnight(KnightsOfTheRoundTable) { bean -> bean.'abstract' = true leader = "King Arthur" } lancelot("lancelot") { bean -> bean.parent = ref("abstractKnight") } abstractPerson(Bean1Impl) { bean -> bean.'abstract'=true age = 45 } homerBean { bean -> bean.parent = ref("abstractPerson") person = "homer" } } """); KnightsOfTheRoundTable lancelot = (KnightsOfTheRoundTable) appCtx.getBean("lancelot"); assertThat(lancelot.leader).isEqualTo("King Arthur"); assertThat(lancelot.name).isEqualTo("lancelot"); Bean1 homerBean = (Bean1) appCtx.getBean("homerBean"); assertThat(homerBean.getAge()).isEqualTo(45); assertThat(homerBean.getPerson()).isEqualTo("homer"); } @Test void groovyBeanDefinitionReaderWithScript() throws Exception { String script = """ def appCtx = new org.springframework.context.support.GenericGroovyApplicationContext() appCtx.reader.beans { quest(org.springframework.context.groovy.HolyGrailQuest) knights(org.springframework.context.groovy.KnightsOfTheRoundTable, "Bedivere") { quest = quest } } appCtx.refresh() return appCtx """; GenericGroovyApplicationContext appCtx = (GenericGroovyApplicationContext) new GroovyShell().evaluate(script); KnightsOfTheRoundTable knights = (KnightsOfTheRoundTable) appCtx.getBean("knights"); knights.embarkOnQuest(); } // test for GRAILS-5057 @Test void registerBeans() { GenericApplicationContext appCtx = new GenericApplicationContext(); loadGroovyDsl(appCtx, """ package org.springframework.context.groovy beans { personA(AdvisedPersonImpl) { name = "Bob" } } """); assertThat(((AdvisedPerson)appCtx.getBean("personA")).getName()).isEqualTo("Bob"); appCtx = new GenericApplicationContext(); loadGroovyDsl(appCtx, """ package org.springframework.context.groovy beans { personA(AdvisedPersonImpl) { name = "Fred" } } """); assertThat(((AdvisedPerson)appCtx.getBean("personA")).getName()).isEqualTo("Fred"); } @Test void listOfBeansAsConstructorArg() { GenericApplicationContext appCtx = new GenericApplicationContext(); loadGroovyDsl(appCtx, """ package org.springframework.context.groovy beans { someotherbean(SomeOtherClass, new File('somefile.txt')) someotherbean2(SomeOtherClass, new File('somefile.txt')) somebean(SomeClass, [someotherbean, someotherbean2]) } """); assertThat(appCtx.containsBean("someotherbean")).isTrue(); assertThat(appCtx.containsBean("someotherbean2")).isTrue(); assertThat(appCtx.containsBean("somebean")).isTrue(); } @Test void beanWithListAndMapConstructor() { GenericApplicationContext appCtx = new GenericApplicationContext(); loadGroovyDsl(appCtx, """ package org.springframework.context.groovy beans { bart(Bean1Impl) { person = "bart" age = 11 } lisa(Bean1Impl) { person = "lisa" age = 9 } beanWithList(Bean5, [bart, lisa]) // test runtime references both as ref() and as plain name beanWithMap(Bean6, [bart:bart, lisa:ref('lisa')]) } """); Bean5 beanWithList = (Bean5) appCtx.getBean("beanWithList"); assertThat(beanWithList.people).extracting(Bean1::getPerson).containsExactly("bart", "lisa"); Bean6 beanWithMap = (Bean6) appCtx.getBean("beanWithMap"); assertThat(beanWithMap.peopleByName).hasSize(2); assertThat(beanWithMap.peopleByName.get("lisa").getAge()).isEqualTo(9); assertThat(beanWithMap.peopleByName.get("bart").getPerson()).isEqualTo("bart"); } @Test void anonymousInnerBeanViaBeanMethod() { GenericApplicationContext appCtx = new GenericApplicationContext(); loadGroovyDsl(appCtx, """ package org.springframework.context.groovy beans { bart(Bean1Impl) { person = "bart" age = 11 } lisa(Bean1Impl) { person = "lisa" age = 9 } marge(Bean2) { person = "marge" bean1 = bean(Bean1Impl) { person = "homer" age = 45 props = [overweight:true, height:"1.8m"] children = ["bart", "lisa"] } children = [bart, lisa] } } """); Bean2 marge = (Bean2) appCtx.getBean("marge"); assertThat(marge.bean1.getPerson()).isEqualTo("homer"); } @Test void anonymousInnerBeanViaBeanMethodWithConstructorArgs() { GenericApplicationContext appCtx = new GenericApplicationContext(); loadGroovyDsl(appCtx, """ package org.springframework.context.groovy beans { bart(Bean1Impl) { person = "bart" age = 11 } lisa(Bean1Impl) { person = "lisa" age = 9 } marge(Bean2) { person = "marge" bean3 = bean(Bean3, "homer", lisa) { person = "homer" age = 45 } children = [bart, lisa] } } """); Bean2 marge = (Bean2) appCtx.getBean("marge"); assertThat(marge.bean3.getPerson()).isEqualTo("homer"); assertThat(marge.bean3.bean1.getPerson()).isEqualTo("lisa"); } private static void loadGroovyDsl(GenericApplicationContext context, String script) { new GroovyBeanDefinitionReader(context).loadBeanDefinitions(new ByteArrayResource((script).getBytes())); context.refresh(); } } class HolyGrailQuest { void start() { /* no-op */ } } class KnightsOfTheRoundTable { String name; String leader; KnightsOfTheRoundTable(String n) { this.name = n; } HolyGrailQuest quest; void embarkOnQuest() { quest.start(); } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getLeader() { return leader; } public void setLeader(String leader) { this.leader = leader; } public HolyGrailQuest getQuest() { return quest; } public void setQuest(HolyGrailQuest quest) { this.quest = quest; } } // simple bean interface Bean1 { String getPerson(); void setPerson(String person); int getAge(); void setAge(int age); Properties getProps(); void setProps(Properties props); List<String> getChildren(); void setChildren(List<String> children); } class Bean1Impl implements Bean1 { String person; int age; Properties props = new Properties(); List<String> children = new ArrayList<>(); @Override public String getPerson() { return person; } @Override public void setPerson(String person) { this.person = person; } @Override public int getAge() { return age; } @Override public void setAge(int age) { this.age = age; } @Override public Properties getProps() { return props; } @Override public void setProps(Properties props) { this.props.putAll(props); } @Override public List<String> getChildren() { return children; } @Override public void setChildren(List<String> children) { this.children = children; } } // bean referencing other bean class Bean2 { int age; Bean1 bean1; Bean3 bean3; String person; Bean1 parent; List<Bean1> children = new ArrayList<>(); public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getPerson() { return person; } public void setPerson(String person) { this.person = person; } public Bean1 getParent() { return parent; } public void setParent(Bean1 parent) { this.parent = parent; } public Bean1 getBean1() { return bean1; } public void setBean1(Bean1 bean1) { this.bean1 = bean1; } public Bean3 getBean3() { return bean3; } public void setBean3(Bean3 bean3) { this.bean3 = bean3; } public List<Bean1> getChildren() { return children; } public void setChildren(List<Bean1> children) { this.children = children; } } // bean with constructor args class Bean3 { Bean3(String person, Bean1 bean1) { this.person = person; this.bean1 = bean1; } String person; Bean1 bean1; int age; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getPerson() { return person; } public void setPerson(String person) { this.person = person; } public Bean1 getBean1() { return bean1; } public void setBean1(Bean1 bean1) { this.bean1 = bean1; } } // bean with factory method class Bean4 { private Bean4() {} static Bean4 getInstance() { return new Bean4(); } String person; public String getPerson() { return person; } public void setPerson(String person) { this.person = person; } } // bean with List-valued constructor arg class Bean5 { Bean5(List<Bean1> people) { this.people = people; } List<Bean1> people; } // bean with Map-valued constructor arg class Bean6 { Bean6(Map<String, Bean1> peopleByName) { this.peopleByName = peopleByName; } Map<String, Bean1> peopleByName; } // a factory bean class Bean1Factory { Bean1 newInstance() { return new Bean1Impl(); } } class ScopeTestBean { } class TestScope implements Scope { int instanceCount; @Override public Object remove(String name) { // do nothing return null; } @Override public void registerDestructionCallback(String name, Runnable callback) { } @Override public String getConversationId() { return null; } @Override public Object get(String name, ObjectFactory<?> objectFactory) { instanceCount++; return objectFactory.getObject(); } @Override public Object resolveContextualObject(String s) { return null; } } class BirthdayCardSender { List<AdvisedPerson> peopleSentCards = new ArrayList<>(); public void onBirthday(AdvisedPerson person) { peopleSentCards.add(person); } } interface AdvisedPerson { void birthday(); int getAge(); void setAge(int age); String getName(); void setName(String name); } @Component("person") class AdvisedPersonImpl implements AdvisedPerson { int age; String name; @Override public void birthday() { ++age; } @Override public int getAge() { return age; } @Override public void setAge(int age) { this.age = age; } @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } } class SomeClass { public SomeClass(List<SomeOtherClass> soc) {} } class SomeOtherClass { public SomeOtherClass(File f) {} } // a factory bean that takes arguments class Bean1FactoryWithArgs { Bean1 newInstance(String name) { Bean1 bean = new Bean1Impl(); bean.setPerson(name); return bean; } }
package com.example; import com.example.model.Role; import com.example.model.User; import com.example.service.UserService; import jdk.nashorn.internal.AssertsEnabled; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import java.util.Arrays; import java.util.HashSet; @RunWith(SpringRunner.class) @SpringBootTest public class DemoApplicationTests { @Autowired UserService userService; @Test public void contextLoads() { } @Test public void test01(){ User u1 = userService.findUserByEmail("test@test.com"); Assert.assertNotNull(u1); } @Test public void test02(){ } }
package br.com.viniciusprojetos.jogodavelha.inteligencia; import android.widget.Button; import java.util.List; import java.util.Random; /** * Created by vinicius on 18/09/17. */ public class Regras { static int answer; static Random rn = new Random(); List<Button> btns; public Regras(List<Button> btns) { this.btns = btns; } public Button tentarVencer() { if (btns.get(0).getText().equals("O")) { if (btns.get(1).getText().equals("O")) { if (btns.get(2).getText().equals("")) { return btns.get(2); } } if (btns.get(2).getText().equals("O")) { if (btns.get(1).getText().equals("")) { return btns.get(1); } } if (btns.get(3).getText().equals("O")) { if (btns.get(6).getText().equals("")) { return btns.get(6); } } if (btns.get(4).getText().equals("O")) { if (btns.get(8).getText().equals("")) { return btns.get(8); } } if (btns.get(6).getText().equals("O")) { if (btns.get(3).getText().equals("")) { return btns.get(3); } } if (btns.get(8).getText().equals("O")) { if (btns.get(4).getText().equals("")) { return btns.get(4); } } } if (btns.get(1).getText().equals("O")) { if (btns.get(2).getText().equals("O")) { if (btns.get(0).getText().equals("")) { return btns.get(0); } } if (btns.get(4).getText().equals("O")) { if (btns.get(7).getText().equals("")) { return btns.get(7); } } if (btns.get(7).getText().equals("O")) { if (btns.get(4).getText().equals("")) { return btns.get(4); } } } if (btns.get(2).getText().equals("O")) { if (btns.get(4).getText().equals("O")) { if (btns.get(6).getText().equals("")) { return btns.get(6); } } if (btns.get(5).getText().equals("O")) { if (btns.get(8).getText().equals("")) { return btns.get(8); } } if (btns.get(6).getText().equals("O")) { if (btns.get(4).getText().equals("")) { return btns.get(4); } } if (btns.get(8).getText().equals("O")) { if (btns.get(5).getText().equals("")) { return btns.get(5); } } } if (btns.get(3).getText().equals("O")) { if (btns.get(4).getText().equals("O")) { if (btns.get(5).getText().equals("")) { return btns.get(5); } } if (btns.get(5).getText().equals("O")) { if (btns.get(4).getText().equals("")) { return btns.get(4); } } if (btns.get(6).getText().equals("O")) { if (btns.get(0).getText().equals("")) { return btns.get(0); } } } if (btns.get(5).getText().equals("O")) { if (btns.get(8).getText().equals("O")) { if (btns.get(2).getText().equals("")) { return btns.get(2); } } if (btns.get(4).getText().equals("O")) { if (btns.get(3).getText().equals("")) { return btns.get(3); } } } if (btns.get(6).getText().equals("O")) { if (btns.get(4).getText().equals("O")) { if (btns.get(2).getText().equals("")) { return btns.get(2); } } if (btns.get(7).getText().equals("O")) { if (btns.get(8).getText().equals("")) { return btns.get(8); } } if (btns.get(8).getText().equals("O")) { if (btns.get(7).getText().equals("")) { return btns.get(7); } } } if (btns.get(7).getText().equals("O")) { if (btns.get(4).getText().equals("O")) { if (btns.get(1).getText().equals("")) { return btns.get(1); } } if (btns.get(8).getText().equals("O")) { if (btns.get(6).getText().equals("")) { return btns.get(6); } } } if (btns.get(8).getText().equals("O")) { if (btns.get(4).getText().equals("O")) { if (btns.get(0).getText().equals("")) { return btns.get(0); } } } return null; } public Button impedirVitoria() { if (btns.get(0).getText().equals("X")) { if (btns.get(1).getText().equals("X")) { if (btns.get(2).getText().equals("")) { return btns.get(2); } } if (btns.get(2).getText().equals("X")) { if (btns.get(1).getText().equals("")) { return btns.get(1); } } if (btns.get(3).getText().equals("X")) { if (btns.get(6).getText().equals("")) { return btns.get(6); } } if (btns.get(4).getText().equals("X")) { if (btns.get(8).getText().equals("")) { return btns.get(8); } } if (btns.get(6).getText().equals("X")) { if (btns.get(3).getText().equals("")) { return btns.get(3); } } if (btns.get(8).getText().equals("X")) { if (btns.get(4).getText().equals("")) { return btns.get(4); } } } if (btns.get(1).getText().equals("X")) { if (btns.get(2).getText().equals("X")) { if (btns.get(0).getText().equals("")) { return btns.get(0); } } if (btns.get(4).getText().equals("X")) { if (btns.get(7).getText().equals("")) { return btns.get(7); } } if (btns.get(7).getText().equals("X")) { if (btns.get(4).getText().equals("")) { return btns.get(4); } } } if (btns.get(2).getText().equals("X")) { if (btns.get(4).getText().equals("X")) { if (btns.get(6).getText().equals("")) { return btns.get(6); } } if (btns.get(5).getText().equals("X")) { if (btns.get(8).getText().equals("")) { return btns.get(8); } } if (btns.get(6).getText().equals("X")) { if (btns.get(4).getText().equals("")) { return btns.get(4); } } if (btns.get(8).getText().equals("X")) { if (btns.get(5).getText().equals("")) { return btns.get(5); } } } if (btns.get(3).getText().equals("X")) { if (btns.get(4).getText().equals("X")) { if (btns.get(5).getText().equals("")) { return btns.get(5); } } if (btns.get(5).getText().equals("X")) { if (btns.get(4).getText().equals("")) { return btns.get(4); } } if (btns.get(6).getText().equals("X")) { if (btns.get(0).getText().equals("")) { btns.get(0).setText("O"); return btns.get(0); } } } if (btns.get(5).getText().equals("X")) { if (btns.get(4).getText().equals("X")) { if (btns.get(3).getText().equals("")) { return btns.get(3); } } if (btns.get(8).getText().equals("X")) { if (btns.get(2).getText().equals("")) { return btns.get(2); } } } if (btns.get(6).getText().equals("X")) { if (btns.get(4).getText().equals("X")) { if (btns.get(2).getText().equals("")) { return btns.get(2); } } if (btns.get(7).getText().equals("X")) { if (btns.get(8).getText().equals("")) { return btns.get(8); } } if (btns.get(8).getText().equals("X")) { if (btns.get(7).getText().equals("")) { return btns.get(7); } } } if (btns.get(7).getText().equals("X")) { if (btns.get(4).getText().equals("X")) { if (btns.get(1).getText().equals("")) { return btns.get(1); } } if (btns.get(8).getText().equals("X")) { if (btns.get(6).getText().equals("")) { return btns.get(6); } } } if (btns.get(8).getText().equals("X")) { if (btns.get(4).getText().equals("X")) { if (btns.get(0).getText().equals("")) { return btns.get(0); } } } return null; } public Button iniciandoJogo() { //comecando o jogo if (btns.get(0).getText().equals("") && btns.get(1).getText().equals("") && btns.get(2).getText().equals("") && btns.get(3).getText().equals("") && btns.get(4).getText().equals("") && btns.get(5).getText().equals("") && btns.get(6).getText().equals("") && btns.get(7).getText().equals("") && btns.get(8).getText().equals("")) { answer = rn.nextInt(5) + 1; switch(answer) { case 1:if (btns.get(0).getText().equals("")) { return btns.get(0); } case 2:if (btns.get(2).getText().equals("")) { return btns.get(2); } case 3:if (btns.get(4).getText().equals("")) { return btns.get(4); } case 4:if (btns.get(6).getText().equals("")) { return btns.get(6); } case 5:if (btns.get(8).getText().equals("")) { return btns.get(8); } } } //se meio vazio, jogar no meio if (btns.get(4).getText().equals("")) { return btns.get(4); } //se oponente jogar no meio, joga em um dos cantos if (btns.get(4).getText().equals("X") && btns.get(0).getText().equals("") && btns.get(2).getText().equals("") && btns.get(6).getText().equals("") && btns.get(8).getText().equals("")) { answer = rn.nextInt(4) + 1; switch(answer) { case 1:if (btns.get(0).getText().equals("")) { return btns.get(0); } case 2:if (btns.get(2).getText().equals("")) { return btns.get(2); } case 3:if (btns.get(6).getText().equals("")) { return btns.get(6); } case 4:if (btns.get(8).getText().equals("")) { return btns.get(8); } } } return null; } public Button defesaJogo() { //impedir chance dupla de vitoria no proximo round if (btns.get(4).getText().equals("X")) { if (btns.get(0).getText().equals("X") && btns.get(8).getText().equals("O")) { if (btns.get(2).getText().equals("")) { return btns.get(2); } if (btns.get(6).getText().equals("")) { return btns.get(6); } } if (btns.get(2).getText().equals("X") && btns.get(6).getText().equals("O")) { if (btns.get(0).getText().equals("")) { return btns.get(0); } if (btns.get(8).getText().equals("")) { return btns.get(8); } } if (btns.get(6).getText().equals("X") && btns.get(2).getText().equals("O")) { if (btns.get(0).getText().equals("")) { return btns.get(0); } if (btns.get(8).getText().equals("")) { return btns.get(8); } } if (btns.get(8).getText().equals("X") && btns.get(0).getText().equals("O")) { if (btns.get(2).getText().equals("")) { return btns.get(2); } if (btns.get(6).getText().equals("")) { return btns.get(6); } } } //impedir chance de dupla vitoria 2 if (btns.get(4).getText().equals("O")) { if (btns.get(0).getText().equals("X") && btns.get(8).getText().equals("X")) { answer = rn.nextInt(4) + 1; switch(answer) { case 1:if (btns.get(1).getText().equals("")) { return btns.get(1); } case 2:if (btns.get(3).getText().equals("")) { return btns.get(3); } case 3:if (btns.get(5).getText().equals("")) { return btns.get(5); } case 4:if (btns.get(7).getText().equals("")) { return btns.get(7); } } } if (btns.get(2).getText().equals("X") && btns.get(6).getText().equals("X")) { answer = rn.nextInt(4) + 1; switch(answer) { case 1:if (btns.get(1).getText().equals("")) { return btns.get(1); } case 2:if (btns.get(3).getText().equals("")) { return btns.get(3); } case 3:if (btns.get(5).getText().equals("")) { return btns.get(5); } case 4:if (btns.get(7).getText().equals("")) { return btns.get(7); } } } } return null; } public Button ataqueJogo() { //tentativa de dupla chance de vitoria if (btns.get(4).getText().equals("O")) { if (btns.get(0).getText().equals("X") && btns.get(8).getText().equals("")) { return btns.get(8); } if (btns.get(8).getText().equals("X") && btns.get(0).getText().equals("")) { return btns.get(0); } if (btns.get(2).getText().equals("X") && btns.get(6).getText().equals("")) { return btns.get(6); } if (btns.get(6).getText().equals("X") && btns.get(2).getText().equals("")) { return btns.get(2); } } //cria possibilidade de vitoria, impedindo chance dupla de vitoria do adversario if (btns.get(4).getText().equals("O")) { if (btns.get(1).getText().equals("X") && btns.get(3).getText().equals("X")) { if (btns.get(0).getText().equals("")) { return btns.get(0); } } if (btns.get(3).getText().equals("X") && btns.get(7).getText().equals("X")) { if (btns.get(6).getText().equals("")) { return btns.get(6); } } if (btns.get(5).getText().equals("X") && btns.get(7).getText().equals("X")) { if (btns.get(8).getText().equals("")) { return btns.get(8); } } if (btns.get(5).getText().equals("X") && btns.get(1).getText().equals("X")) { if (btns.get(2).getText().equals("")) { return btns.get(2); } } } //Terminar jogo answer = 1; switch(answer) { case 1:if (btns.get(0).getText().equals("")) { return btns.get(0); } else answer++; case 2:if (btns.get(1).getText().equals("")) { return btns.get(1); } else answer++; case 3:if (btns.get(2).getText().equals("")) { return btns.get(2); } else answer++; case 4:if (btns.get(3).getText().equals("")) { return btns.get(3); } else answer++; case 5:if (btns.get(4).getText().equals("")) { return btns.get(4); } else answer++; case 6:if (btns.get(5).getText().equals("")) { return btns.get(5); } else answer++; case 7:if (btns.get(6).getText().equals("")) { return btns.get(6); } else answer++; case 8:if (btns.get(7).getText().equals("")) { return btns.get(7); } else answer++; case 9:if (btns.get(8).getText().equals("")) { return btns.get(8); } } return null; } public Button getBtVazio() { int j, i = 0; for (j = 0; j < btns.size(); j++) { //i = geraNum(); if (btns.get(j).getText().toString().isEmpty()) break; } return btns.get(i); } }
/** * 在一条x轴上有n个点,每个点画出一条垂直线,两条直线与x轴构成一个容器,找出能含有最多水的容器。 * Created by mengwei on 2019/4/12. */ public class ContainerWithMostWater { /** * 采用全局扫一遍的方式,这个算法的复杂度是O(2^n) * @param height * @return */ public int maxArea(int[] height) { int area=0; for (int i = 0; i < height.length; i++) { for(int j = 0; j < height.length; j++){ if(j < i){ continue; } int one = height[i]; int two = height[j]; if(one < two){ int rs = (j - i) * one; if(area < rs){ area = rs; } }else{ int rs = (j - i) * two; if(area < rs){ area = rs; } } } } return area; } /** * 贪心算法:从两边开始向中间缩小;每一步比较左右边界高度,高度小的那个向里走一步 * 参考:https://www.cnblogs.com/whu-gbf/p/9173582.html * @param height * @return */ public int maxArea2(int[] height) { int area = 0; int left = 0; int right = height.length - 1; while(left < right){ int len = right - left; if(height[left] < height[right]){ int rs = height[left] * len; if(area < rs){ area = rs; } left++; }else{ int rs = height[right] * len; if(area < rs){ area = rs; } right--; } } return area; } public static void main(String[] args) { int[] n = {1,8,6,2,5,4,8,3,7}; int i = new ContainerWithMostWater().maxArea2(n); System.out.println(i); } }
package ua.com.rd.pizzaservice.service.address; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import ua.com.rd.pizzaservice.domain.address.Address; import ua.com.rd.pizzaservice.repository.address.AddressRepository; import java.util.Set; @Service @Transactional public class AddressServiceImpl implements AddressService { @Autowired private AddressRepository addressRepository; public AddressServiceImpl() { } @Override @Transactional(readOnly = true) public Address getAddressById(Long id) { return addressRepository.getAddressById(id); } @Override public Address saveAddress(Address address) { return addressRepository.saveAddress(address); } @Override public void updateAddress(Address address) { addressRepository.updateAddress(address); } @Override public Address deleteAddress(Address address) { return addressRepository.deleteAddress(address); } @Override @Transactional(readOnly = true) public Set<Address> findAll() { return addressRepository.findAll(); } }
package zookeeperTest.distributedlock; import org.apache.curator.framework.CuratorFramework; import org.apache.zookeeper.Watcher; import zookeeperTest.factory.ZKclient; import java.util.Collections; import java.util.List; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; /** * Lock implement * just for demonstrate how distributed lock works * in production, just use the official dis lock (InterProcessMutex) * * Author: zirui liu * Date: 2021/7/18 */ public class ZkLock implements Lock{ private static final String ZK_PATH = "/test/lock"; private static final String LOCK_PREFIX = ZK_PATH + "/"; private static final long WAIT_TIME = 1000; private String locked_short_path = null; private String locked_path = null; private String prior_path = null; private Thread thread; final AtomicInteger lockCount = new AtomicInteger(0); CuratorFramework client = null; public ZkLock() { ZKclient.instance.init(); if (!ZKclient.instance.isNodeExist(ZK_PATH)) { ZKclient.instance.createNode(ZK_PATH, null); } client = ZKclient.instance.getClient(); } @Override public boolean lock() { synchronized (this) { if (lockCount.get() == 0) { thread = Thread.currentThread(); lockCount.incrementAndGet(); } else { if (!thread.equals(Thread.currentThread())) { return false; } lockCount.incrementAndGet(); return true; } } try { boolean locked = false; // first time to lock(try) locked = tryLock(); if (locked) { return true; } while (!locked) { await(); List<String> waiters = getWaiters(); if (checkLocked(waiters)) { locked = true; } } return true; } catch (Exception e) { e.printStackTrace(); unlock(); } return false; } @Override public boolean unlock() { if (!thread.equals(Thread.currentThread())) { return false; } int newLockCount = lockCount.decrementAndGet(); if (newLockCount < 0) { throw new IllegalMonitorStateException("counting error: " + locked_path); } if (newLockCount != 0) { return true; } try { if (ZKclient.instance.isNodeExist(locked_path)) { client.delete().forPath(locked_path); } } catch (Exception e) { e.printStackTrace(); return false; } return true; } private boolean tryLock() throws Exception { locked_path = ZKclient.instance.createEphemeralSeqNode(LOCK_PREFIX); if (null == locked_path) { throw new Exception("zk error"); } // get index in queue locked_short_path = getShortPath(locked_path); // get queue List<String> waiters = getWaiters(); // check if the first of the queue if (checkLocked(waiters)) { return true; } int index = Collections.binarySearch(waiters, locked_short_path); if (index < 0) { // not exists throw new Exception("can not find node: " + locked_short_path); } prior_path = ZK_PATH + "/" + waiters.get(index - 1); return false; } private boolean checkLocked(List<String> waiters) { Collections.sort(waiters); if (locked_short_path.equals(waiters.get(0))) { System.out.println("get lock successfully, node=" + locked_short_path); return true; } return false; } private void await() throws Exception { if (null == prior_path) { throw new Exception("prior_path error"); } final CountDownLatch latch = new CountDownLatch(1); Watcher w = watchedEvent -> { System.out.println("get change = " + watchedEvent); System.out.println("node deleted"); latch.countDown(); }; client.getData().usingWatcher(w).forPath(prior_path); /* TreeCache treeCache = new TreeCache(client, prior_path); TreeCacheListener l = (curatorFramework, event) -> { ChildData data = event.getData(); if (data != null) { switch (event.getType()) { case NODE_REMOVED: System.out.println("[TreeCache] node delete, path=" + data.getPath() + " data=" + Arrays.toString(data.getData())); break; default: break; } } }; treeCache.getListenable().addListener(l); treeCache.start(); */ latch.await(WAIT_TIME, TimeUnit.SECONDS); } private String getShortPath(String locked_path) { int index = locked_path.lastIndexOf(ZK_PATH + "/"); if (index >= 0) { index += ZK_PATH.length() + 1; return index <= locked_path.length() ? locked_path.substring(index) : ""; } return null; } /** * get all waiting node from zk */ protected List<String> getWaiters() { List<String> children = null; try { children = client.getChildren().forPath(ZK_PATH); } catch (Exception e) { e.printStackTrace(); return null; } return children; } }
package com.example.chungyu.topic; import android.content.Intent; import android.graphics.Bitmap; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ImageView; import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.assist.ImageScaleType; import com.nostra13.universalimageloader.core.assist.QueueProcessingType; import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer; public class FullImage extends AppCompatActivity { private ImageLoader imageLoader = ImageLoader.getInstance(); private ImageView imageView; private DisplayImageOptions options; private ImageLoaderConfiguration config; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_full_image); options = new DisplayImageOptions.Builder() .resetViewBeforeLoading(true) .cacheOnDisk(true) .imageScaleType(ImageScaleType.EXACTLY) .considerExifParams(true) .bitmapConfig(Bitmap.Config.RGB_565) .displayer(new FadeInBitmapDisplayer(300)) .build(); config = new ImageLoaderConfiguration.Builder(this) .threadPriority(Thread.MAX_PRIORITY - 2) .denyCacheImageMultipleSizesInMemory() .diskCacheFileNameGenerator(new Md5FileNameGenerator()) .diskCacheSize(50 * 1024 * 1024) .tasksProcessingOrder(QueueProcessingType.LIFO) .defaultDisplayImageOptions(options) .build(); imageLoader.init(config); new Handler().postDelayed(new Runnable(){ public void run() { imageView = (ImageView) findViewById(R.id.imageView); imageLoader.displayImage("http://120.113.173.208/UserUploadFile/test/image/1506237595760.jpg",imageView); } },500); } }
/*16. Find the determinant, for the quadratic equations. */ import java.lang.*; class DeterminantQuadEquation{ public static void main(String args[]){ double firstroot = 0; double secondroot = 0; double a = 10; double b = 25; double c = 5; double determinant = (b*b)-(4*a*c); double root = Math.sqrt(determinant); if(determinant>0){ firstroot = (-b + root)/(2*a); secondroot = (-b - root)/(2*a); System.out.println("The roots are "+ firstroot +" and "+secondroot); }else if(determinant == 0){ System.out.println("The root is "+(-b + root)/(2*a)); } } }
package com.example.g0294.tutorial.ui; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.Gravity; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.example.g0294.tutorial.R; public class UserInterfaceActivity extends AppCompatActivity { private Button btn_textView, btn_editText, btn_imageView, btn_button, btn_ratoteImage, btn_imageResize, btn_checkBox, btn_radioButton, btn_datetimePicker, btn_progressBar, btn_seekBar, btn_toast, btn_alertDialog, btn_webView, btn_menu; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.user_interface_layout); SelectActivity listener = new SelectActivity(); btn_textView = (Button) findViewById(R.id.btn_textView); btn_textView.setOnClickListener(listener); btn_editText = (Button) findViewById(R.id.btn_editText); btn_editText.setOnClickListener(listener); btn_imageView = (Button) findViewById(R.id.btn_imageView); btn_imageView.setOnClickListener(listener); btn_button = (Button) findViewById(R.id.btn_button); btn_button.setOnClickListener(listener); btn_ratoteImage = (Button) findViewById(R.id.btn_rotateImage); btn_ratoteImage.setOnClickListener(listener); btn_imageResize = (Button) findViewById(R.id.btn_imageResize); btn_imageResize.setOnClickListener(listener); btn_toast = (Button) findViewById(R.id.btn_toast); btn_toast.setOnClickListener(listener); btn_checkBox = (Button) findViewById(R.id.btn_checkBox); btn_checkBox.setOnClickListener(listener); btn_progressBar = (Button) findViewById(R.id.btn_progressBar); btn_progressBar.setOnClickListener(listener); btn_seekBar = (Button) findViewById(R.id.btn_seekBar); btn_seekBar.setOnClickListener(listener); btn_alertDialog = (Button) findViewById(R.id.btn_alertDialog); btn_alertDialog.setOnClickListener(listener); btn_radioButton = (Button) findViewById(R.id.btn_radioButton); btn_radioButton.setOnClickListener(listener); btn_webView = (Button) findViewById(R.id.btn_webView); btn_webView.setOnClickListener(listener); btn_datetimePicker = (Button) findViewById(R.id.btn_datetimePicker); btn_datetimePicker.setOnClickListener(listener); btn_menu = (Button) findViewById(R.id.btn_menu); btn_menu.setOnClickListener(listener); } class SelectActivity implements View.OnClickListener { @Override public void onClick(View view) { Intent intent = new Intent(); switch (view.getId()) { case R.id.btn_textView: intent.setClass(getApplicationContext(), TextViewActivity.class); startActivity(intent); break; case R.id.btn_editText: intent.setClass(getApplicationContext(), EditTextActivity.class); startActivity(intent); break; case R.id.btn_imageView: intent.setClass(getApplicationContext(), ImageViewActivity.class); startActivity(intent); break; case R.id.btn_rotateImage: intent.setClass(getApplicationContext(), ImageZoomActivity.class); startActivity(intent); break; case R.id.btn_imageResize: intent.setClass(getApplicationContext(), ImageResizeActivity.class); startActivity(intent); break; case R.id.btn_button: intent.setClass(getApplicationContext(), ButtonActivity.class); startActivity(intent); break; case R.id.btn_checkBox: intent.setClass(getApplicationContext(), CheckBoxActivity.class); startActivity(intent); break; case R.id.btn_progressBar: intent.setClass(getApplicationContext(), ProgressBarActivity.class); startActivity(intent); break; case R.id.btn_seekBar: intent.setClass(getApplicationContext(), SeekRatingBarActivity.class); startActivity(intent); break; case R.id.btn_alertDialog: intent.setClass(getApplicationContext(), AlertDialogActivity.class); startActivity(intent); break; case R.id.btn_radioButton: intent.setClass(getApplicationContext(), RadioButtonActivity.class); startActivity(intent); break; case R.id.btn_webView: intent.setClass(getApplicationContext(), WebViewActivity.class); startActivity(intent); break; case R.id.btn_datetimePicker: intent.setClass(getApplicationContext(), DateTimePickerActivity.class); startActivity(intent); break; case R.id.btn_menu: intent.setClass(getApplicationContext(), MenusActivity.class); startActivity(intent); break; case R.id.btn_toast: LayoutInflater inflater = getLayoutInflater(); View customToast = inflater.inflate(R.layout.mytoast_layout, null); TextView text = (TextView) customToast.findViewById(R.id.tvContent); text.setText("This is a custom toast"); Toast toast = new Toast(getApplicationContext()); toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0); toast.setDuration(Toast.LENGTH_SHORT); toast.setView(customToast); toast.show(); break; } } } }
package com.billpay.billpaymodel.item; import java.math.BigDecimal; import lombok.Data; @Data public class PaymentItem { public enum PaymentMethod{ ELECTRONIC,CHECK }; public enum PaymentCategory{ ONE_TIME,RECURRING }; public enum RepeatUntil{ PAYMENT_COUNT_REACHED,PAYMENT_AMOUNT_REACHED,CANCELLED }; public enum RecurringLimitType{ WEEKLY,MONTHLY,EVERY_TWO_WEEK,QUATERLY,SEMI_ANNUALLY,ANNUALLY }; private PaymentMethod paymentMethod; private PaymentCategory paymentCategory; private RepeatUntil repeatUntil; private RecurringLimitType recurringLimitType; private String payeeNickname; private String paymentDate; private BigDecimal paymentAmount; private String nextPaymentDate; private BigDecimal totalPaymentCount; private BigDecimal paymentCountToDate; private BigDecimal totalAmountCount; private BigDecimal amountPaidToDate; //private String paymentReferenceNumber; }
package example.lgcode.launchstatus.models; import android.os.AsyncTask; import com.squareup.otto.Bus; import java.io.IOException; import java.util.ArrayList; import java.util.List; import example.lgcode.launchstatus.dtos.LaunchDTO; import example.lgcode.launchstatus.dtos.LaunchListResultDTO; import example.lgcode.launchstatus.network.LaunchClient; import example.lgcode.launchstatus.network.LaunchResponse; /** * Created by leojg on 1/20/17. */ public class LaunchStatusModel { private Bus bus; private LaunchClient client; private Integer currentCount; private List<LaunchDTO> launches; private Integer total; private Integer currentOffset = 0; private Integer OFFSET = 10; public LaunchStatusModel(Bus bus) { this.bus = bus; launches = new ArrayList<>(); client = new LaunchClient(); fetchLaunchStatus(); } public List<LaunchDTO> getLaunches() { return launches; } public Integer getCurrentCount() { return currentCount; } public void fetchLaunchStatus() { new AsyncTask<Void, Void, Void>() { @Override protected Void doInBackground(Void... voids) { try { LaunchListResultDTO launchListResult = client.fetchLaunches(currentOffset); if (total == null) { total = launchListResult.getTotal(); } currentCount = launchListResult.getCount(); for (LaunchDTO launch : launchListResult.getLaunches()) { launches.add(launch); } } catch (IOException e) { e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); currentOffset += OFFSET; bus.post(new LaunchesFetchedEvent()); } }.execute(); } public class LaunchesFetchedEvent {} }
/* * Copyright (C) 2017 GetMangos * * 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 eu.mangos.dbc.model.map; /** * Entry representing the type of liquid within the game. * @author GetMangos */ public class LiquidType { /** * 0 - ID in the DBC. */ private int id; /** * 1 - Liquid type (23 Water, 29 Ocean, 35 Magma, 41 Slime, 47 Naxxramas - Slime). */ private int liquidID; /** * 2 - Type (0 Magma, 2 Slime, 3 Water) */ private int liquidType; /** * 3 - Reference to Spell.dbc */ private int spellID; public LiquidType() { } public LiquidType(int id, int liquidID, int liquidType, int spellID) { this.id = id; this.liquidID = liquidID; this.liquidType = liquidType; this.spellID = spellID; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getLiquidID() { return liquidID; } public void setLiquidID(int liquidID) { this.liquidID = liquidID; } public int getLiquidType() { return liquidType; } public void setLiquidType(int liquidType) { this.liquidType = liquidType; } public int getSpellID() { return spellID; } public void setSpellID(int spellID) { this.spellID = spellID; } }
package lab_8_9; import java.lang.Character; public class UpperCase { public static void isUpperCase(String str) { int upperCount = 0; for (int i = 0; i < str.length(); i++) { if (Character.isUpperCase(str.charAt(i))) upperCount++; } System.out.println("Number of capitals in sentence, \"" + str + "\"" + "\n--> " +upperCount); } public static void main(String[] args) { isUpperCase("There Are Capitals"); } }
package com.youthlin.example.plugin.api; import java.lang.reflect.Array; import java.util.Map; import java.util.PriorityQueue; import java.util.concurrent.ConcurrentHashMap; public class Plugins { private static Map<String, QueueWarp> MAP = new ConcurrentHashMap<>(); public enum State { READY, DOING, DONE; } private static class QueueWarp { State state = State.READY; PriorityQueue<Pluginable> queue = new PriorityQueue<>(); } private static class Pluginable implements Comparable<Pluginable> { Object target; int priority; int acceptArgs; private Pluginable(Object target, int priority, int acceptArgs) { this.target = target; this.priority = priority; this.acceptArgs = acceptArgs; } @Override public int compareTo(Pluginable o) { return Integer.compare(priority, o.priority); } } private static void add(String tag, Object actionOrFilter, int priority, int acceptArgs) { QueueWarp warp = MAP.computeIfAbsent(tag, k -> new QueueWarp()); if (warp.state == State.READY) { warp.queue.add(new Pluginable(actionOrFilter, priority, acceptArgs)); } else { log("can not add %1$s on tag `%2$s` cause it's state is not READY, state: %3$s", (actionOrFilter instanceof Action) ? "Action" : "Filter", tag, warp.state); } } private static void log(String format, Object... args) { System.err.println(String.format(format, args)); } public static void addAction(String tag, Action action, int priority, int acceptArgs) { add(tag, action, priority, acceptArgs); } public static <T> void addFilter(String tag, Filter<T> filter, int priority, int acceptArgs) { add(tag, filter, priority, acceptArgs); } public static void doAction(String tag, Object... args) { QueueWarp wrap = MAP.get(tag); if (wrap != null) { wrap.state = State.DOING; for (Pluginable pluginable : wrap.queue) { if (pluginable.target instanceof Action) { if (pluginable.acceptArgs <= args.length) { ((Action) pluginable.target).doAction(sub(args, pluginable.acceptArgs)); } else { log("tag `%1$s` args length: %2$d, action `%3$s` accept args length: %4$d", tag, args.length, pluginable.target, pluginable.acceptArgs); } } } wrap.state = State.DONE; } } @SuppressWarnings("unchecked") private static <T> T[] sub(T[] input, int length) { assert length <= input.length; if (input.length == 0) { return input; } T[] array = (T[]) Array.newInstance(input[0].getClass(), length); System.arraycopy(input, 0, array, 0, length); return array; } @SuppressWarnings("unchecked") public static <T> T applyFilter(String tag, T input, Object... args) { QueueWarp wrap = MAP.get(tag); if (wrap != null) { wrap.state = State.DOING; for (Pluginable pluginable : wrap.queue) { if (pluginable.target instanceof Filter) { if (pluginable.acceptArgs <= args.length) { input = ((Filter<T>) pluginable.target).applyFilter(input, sub(args, pluginable.acceptArgs)); } else { log("tag `%1$s` args length: %2$d, filter `%3$s` accept args length: %4$d", tag, args.length, pluginable.target, pluginable.acceptArgs); } } } wrap.state = State.DONE; } return input; } }
package org.digdata.swustoj.aop; import java.lang.reflect.Method; import java.util.List; import java.util.Map; import org.apache.log4j.Logger; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.reflect.MethodSignature; import org.digdata.swustoj.base.BasePointCut; import org.digdata.swustoj.base.IMemCacheTemplate; import org.digdata.swustoj.model.annotation.CacheAccess; import org.digdata.swustoj.model.annotation.CacheFlush; import org.digdata.swustoj.util.ClassUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; /** * * @author wwhhf * @since 2016年6月1日 * @comment 缓存切面管理 order值越小,顺序越高 cacheKey->className.methodName(args).version * cacheValue->data versionKey->className.version cacheValue->Integer */ @Order(3) @Aspect @Component public class MemCacheAspect extends BasePointCut { private static Logger logger = Logger.getLogger(MemCacheAspect.class); private static final Class VERSION_KEY_TYPE = Long.class; private static final String VERSION_SUFFIX = "version"; @Autowired private IMemCacheTemplate iMemCacheTemplate = null; /** * * @author wwhhf * @since 2016年6月1日 * @comment 先进行访问缓存,若命中则直接返回,否则继续执行方法 * @param joinpoint * @throws Throwable */ @Around("DaoPointCut()") public Object cacheAccess(ProceedingJoinPoint joinpoint) throws Throwable { String clazzName = joinpoint.getTarget().getClass().getName(); String methodName = joinpoint.getSignature().getName(); Object[] args = joinpoint.getArgs(); Method method = ((MethodSignature) joinpoint.getSignature()) .getMethod(); boolean hasAnnotation = method.isAnnotationPresent(CacheAccess.class); if (hasAnnotation) {// 存在需要缓存数据的注解 String version_key = getVersionKey(clazzName);// 获取缓存版本号的key Long version_value = (Long) this.iMemCacheTemplate.getObject( version_key, VERSION_KEY_TYPE); // 获取缓存版本号 if (version_value == null) { // 版本号过期了,重新建立缓存版本号,该类以前的缓存全部过期 this.iMemCacheTemplate.set(version_key, version_value = getNextVersionValue());// 重新设置缓存版本号 logger.debug("CACHE INIT: " + version_key + " -> " + version_value); String cache_key = ClassUtil.getMethodInfo(clazzName, methodName, args, version_value);// 获得缓存的key // ============================================ Object cache_value = joinpoint.proceed(args);// 缓存未命中 // ============================================ logger.debug("CACHE NOT HIT: " + cache_key); this.iMemCacheTemplate.set(cache_key, cache_value);// 缓存数据 return cache_value; } else {// 版本号未过期,查询该类此版本的缓存 CacheAccess annotation = method .getAnnotation(CacheAccess.class);// 获得注解 Class clazz = annotation.type(); // 获得json的class String cache_key = ClassUtil.getMethodInfo(clazzName, methodName, args, version_value);// 获得cache_key Object cache_value = null; if (clazz == String.class) { // String cache_value = this.iMemCacheTemplate.getString(cache_key); } else if (clazz == List.class) { // List Class subClazz = annotation.subType(); cache_value = this.iMemCacheTemplate.getList(cache_key, subClazz); } else if (clazz == Map.class) { // Map cache_value = this.iMemCacheTemplate.getMap(cache_key); } else { // Object cache_value = this.iMemCacheTemplate.getObject(cache_key, clazz); } if (cache_value == null) { // 缓存未命中,需要缓存数据 logger.debug("CACHE NOT HIT: " + cache_key); // ==================================== cache_value = joinpoint.proceed(args); // ==================================== this.iMemCacheTemplate.set(cache_key, cache_value); } else { // 缓存命中 logger.debug("CACHE HIT: " + cache_key); } return cache_value; } } else {// 不存在注解 return joinpoint.proceed(args); } } /** * * @author wwhhf * @since 2016年6月1日 * @comment 先进行缓存清除,再执行方法 * @param joinpoint * @throws Throwable */ @Around("DaoPointCut()") public Object cacheFlush(ProceedingJoinPoint joinpoint) throws Throwable { String clazzName = joinpoint.getTarget().getClass().getName(); Object[] args = joinpoint.getArgs(); Method method = ((MethodSignature) joinpoint.getSignature()) .getMethod(); boolean hasAnnotation = method.isAnnotationPresent(CacheFlush.class); if (hasAnnotation) {// 存在清除缓存的注解 improveVersion(clazzName);// 提高缓存的版本号 } return joinpoint.proceed(args); } /** * @author wwhhf * @since 2016年6月5日 * @comment 提高相应类的版本 * @param clazzName * @throws Exception */ private void improveVersion(String clazzName) throws Exception { // 获取缓存版本号的key String version_key = getVersionKey(clazzName); // 获取缓存版本号 Long version = (Long) this.iMemCacheTemplate.getObject(version_key, VERSION_KEY_TYPE); if (version != null) { // 版本号过期则不管,让查询统一处理 // 版本号未过期,提高版本号 this.iMemCacheTemplate.set(version_key, version = getNextVersionValue()); logger.debug("CACHE VERSION IMPROVE: " + version_key + " -> " + version); } } /** * * @author wwhhf * @since 2016年6月2日 * @comment 获取类名对应的缓存版本号 * @param className * @return */ private String getVersionKey(String className) { StringBuffer sb = new StringBuffer(className).append(".").append( VERSION_SUFFIX); return sb.toString(); } /** * * @author wwhhf * @since 2016年6月2日 * @comment 获取类名对应的下一次的缓存版本号(时间戳) * @param className * @return */ private Long getNextVersionValue() { return System.currentTimeMillis(); } }
package com.example.insurance; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.Toast; public class FindBrokersActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_find_brokers); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. MenuInflater inflater = getMenuInflater(); getMenuInflater().inflate(R.menu.main, menu); CharSequence text = "You are on the Find A Broker Activity"; int duration = Toast.LENGTH_SHORT; Context context = getApplicationContext(); Toast toast = Toast.makeText(context, text, duration); toast.show(); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_profile) { Intent intent = new Intent(getBaseContext(),ProfileActivity.class); if(intent!=null) startActivity(intent); } else if(id == R.id.action_Accident){ Intent intent = new Intent(getBaseContext(),AccidentActivity.class); if(intent!=null) startActivity(intent); } else if(id == R.id.action_NewInsurance){ Intent intent = new Intent(getBaseContext(),NewInsuranceActivity.class); if(intent!=null) startActivity(intent); } else if(id == R.id.action_findBrokers){ //we are in findBrokers } else if(id == R.id.action_exit){ System.exit(0); } else if(id == R.id.menu_home){ Intent intent = new Intent(getBaseContext(),MainActivity.class); if(intent!=null) startActivity(intent); } return super.onOptionsItemSelected(item); } }
package automation.oop; import automation.interfacesclassgroup.Light; public class ArrayExercise { public static void main(String[] args) { // Light lightBulb = new Light(); Light[] lights = { new Light(), new Light() }; System.out.println(lights.length); Light light = lights[1]; light.brighten(); System.out.println(light.getIntensity()); // ----------------------- Light[] lights2 = new Light[2]; lights2[1] = new Light(); System.out.println(lights2.length); System.out.println(lights2[1].getIntensity()); for (int i = 0; i < lights.length; i++) { // System.out.println(lights[i].getIntensity()); System.out.println(lights[i].getIsOn()); } } }
package com.qst.chapter04.activity; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import com.qst.chapter04.R; public class Activity_Main extends AppCompatActivity { private Button button1, button2, button3, button4, button5, button6, button7, button8, button9, button10, button11, button12, button13, button14, button15, button16, button17, button18, button19; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chapter04); findViewById(); setListeners(); } private void findViewById() { button1 = findViewById(R.id.button1); button2 = findViewById(R.id.button2); button3 = findViewById(R.id.button3); button4 = findViewById(R.id.button4); button5 = findViewById(R.id.button5); button6 = findViewById(R.id.button6); button7 = findViewById(R.id.button7); button8 = findViewById(R.id.button8); button9 = findViewById(R.id.button9); button10 = findViewById(R.id.button10); button11 = findViewById(R.id.button11); button12 = findViewById(R.id.button12); button13 = findViewById(R.id.button13); button14 = findViewById(R.id.button14); button15 = findViewById(R.id.button15); button16 = findViewById(R.id.button16); button17 = findViewById(R.id.button17); button18 = findViewById(R.id.button18); button19 = findViewById(R.id.button19); } class OnClick implements View.OnClickListener { @Override public void onClick(View v) { Intent intent = null; switch (v.getId()) { case R.id.button1: intent = new Intent(Activity_Main.this, ActionBarDemoActivity.class); break; case R.id.button2: intent = new Intent(Activity_Main.this, ContextMenuDemoActivity.class); break; case R.id.button3: intent = new Intent(Activity_Main.this, FragmentDemoActivity.class); break; case R.id.button4: intent = new Intent(Activity_Main.this, FragmentLifecircleActivity.class); break; case R.id.button5: intent = new Intent(Activity_Main.this, GridViewDemoActivity.class); break; case R.id.button6: intent = new Intent(Activity_Main.this, ListActivityDemo.class); break; case R.id.button7: intent = new Intent(Activity_Main.this, ListVewImageDemoActivity.class); break; case R.id.button8: intent = new Intent(Activity_Main.this, ListVewSimpleDemoActivity.class); break; case R.id.button9: intent = new Intent(Activity_Main.this, ListViewDemoActivity.class); break; case R.id.button10: intent = new Intent(Activity_Main.this, MenuDemoActivity.class); break; case R.id.button11: intent = new Intent(Activity_Main.this, ProviderActivityDemo.class); break; case R.id.button12: intent = new Intent(Activity_Main.this, SubMenuDemoActivity.class); break; case R.id.button13: intent = new Intent(Activity_Main.this, TabDemoActivity.class); break; case R.id.button14: intent = new Intent(Activity_Main.this, TabHostDemo1Activity.class); break; case R.id.button15: intent = new Intent(Activity_Main.this, TabHostDemo2Activity.class); break; case R.id.button16: intent = new Intent(Activity_Main.this, TestFragment.class); break; case R.id.button17: intent = new Intent(Activity_Main.this, ToolbarActivity.class); break; case R.id.button18: intent = new Intent(Activity_Main.this, WebViewDemoActivity.class); break; case R.id.button19: intent = new Intent(Activity_Main.this, XMLContextMenuDemoActivity.class); break; } startActivity(intent); } } private void setListeners() { OnClick onClick = new OnClick(); button1.setOnClickListener(onClick); button2.setOnClickListener(onClick); button3.setOnClickListener(onClick); button4.setOnClickListener(onClick); button5.setOnClickListener(onClick); button6.setOnClickListener(onClick); button7.setOnClickListener(onClick); button8.setOnClickListener(onClick); button9.setOnClickListener(onClick); button10.setOnClickListener(onClick); button11.setOnClickListener(onClick); button12.setOnClickListener(onClick); button13.setOnClickListener(onClick); button14.setOnClickListener(onClick); button15.setOnClickListener(onClick); button16.setOnClickListener(onClick); button17.setOnClickListener(onClick); button18.setOnClickListener(onClick); button19.setOnClickListener(onClick); } }
package byview.prim.com.lib_annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author prim * @version 1.0.0 * @desc * @time 2018/7/10 - 下午12:45 */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface BYView { int value() default 0; }
package com.git.cloud.tenant.model.vo; import java.util.List; import java.util.Map; import com.git.cloud.common.model.base.BaseBO; import com.git.cloud.request.model.vo.BmSrAttrValVo; public class RequestInfo extends BaseBO implements java.io.Serializable { private String operModelType; //操作类型 private Integer cpu; //请求的总cpu private Integer mem; //请求的总内存 private Integer disk; //请求的总磁盘 private Integer vmNum; //机器数 private String tenantId; // 租户ID private String platformTypeCode;//平台类型编码 private String quotaCode; //配额编码 public RequestInfo(String tenantId) { this.tenantId = tenantId ; } @Override public String getBizId() { // TODO Auto-generated method stub return null; } public String getOperModelType() { return operModelType; } public void setOperModelType(String operModelType) { this.operModelType = operModelType; } public Integer getCpu() { return cpu; } public void setCpu(Integer cpu) { this.cpu = cpu; } public Integer getMem() { return mem; } public void setMem(Integer mem) { this.mem = mem; } public Integer getDisk() { return disk; } public void setDisk(Integer disk) { this.disk = disk; } public Integer getVmNum() { return vmNum; } public void setVmNum(Integer vmNum) { this.vmNum = vmNum; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getPlatformTypeCode() { return platformTypeCode; } public void setPlatformTypeCode(String platformTypeCode) { this.platformTypeCode = platformTypeCode; } public String getQuotaCode() { return quotaCode; } public void setQuotaCode(String quotaCode) { this.quotaCode = quotaCode; } }
package com.coach.service.CoachService.entities; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonManagedReference; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty.Access; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.ToString; import javax.persistence.*; import java.util.Collection; import java.util.List; import java.util.Set; @Entity @AllArgsConstructor @NoArgsConstructor @ToString @Data public class Sport { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; private String code; private String label; private String description; }
package org.gatein.wcm.ui; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.annotation.Resource; import javax.faces.bean.ManagedBean; import javax.faces.bean.ManagedProperty; import javax.faces.bean.RequestScoped; import org.gatein.wcm.api.model.content.WCMFolder; import org.gatein.wcm.api.model.content.WCMObject; import org.gatein.wcm.api.services.WCMContentService; import org.gatein.wcm.api.services.WCMRepositoryService; import org.gatein.wcm.api.services.exceptions.WCMContentException; import org.gatein.wcm.api.services.exceptions.WCMContentIOException; import org.gatein.wcm.api.services.exceptions.WCMContentSecurityException; import org.gatein.wcm.ui.model.TreeContent; import org.jboss.logging.Logger; import org.richfaces.component.UITree; import org.richfaces.event.TreeSelectionChangeEvent; @ManagedBean @RequestScoped public class Tree extends BaseBean { private static final Logger log = Logger.getLogger(Tree.class); @ManagedProperty(value="#{connect}") private Connect connect; @ManagedProperty(value="#{panel}") private Panel panel; private List<TreeContent> root; private Date ping; public Tree() { ping = new java.util.Date(); } public void setConnect(Connect connect) { this.connect = connect; } public Date getPing() { return ping; } public void setPing(Date ping) { this.ping = ping; } public List<TreeContent> getRoot() { if (root == null) queryRoot(); return root; } public Panel getPanel() { return panel; } public void setPanel(Panel panel) { this.panel = panel; } // Logic @Resource(mappedName = "java:jboss/gatein-wcm") WCMRepositoryService repos; private void queryRoot() { if (connect == null || !connect.isConnected()) return; try { WCMContentService cs = repos.createContentSession(connect.getUser(), connect.getPassword()); WCMObject rootContent = null; // TODO cs.getContent("/", getLocale()); root = new ArrayList<TreeContent>(); // We don't show root node in the UI, only children if (rootContent instanceof WCMFolder) { WCMFolder f = (WCMFolder)rootContent; for (WCMObject c : f.getChildren()) { root.add(new TreeContent(c)); } } } catch (WCMContentIOException e) { msg("Cannot connect with repository " + connect.getRepository()); log.error(e.getMessage(), e); connect.setConnected(false); } catch (WCMContentSecurityException e) { msg("User " + connect.getUser() + " incorrect for " + connect.getRepository() + "/" + connect.getWorkspace() + ""); log.warn("ContentSecurityException for " + connect.getUser() + " repository " + connect.getRepository() + " workspace " + connect.getWorkspace() + ". Msg: " + e.getMessage()); connect.setConnected(false); } } public void selectionChanged(TreeSelectionChangeEvent selectionChangeEvent) { List<Object> selection = new ArrayList<Object>(selectionChangeEvent.getNewSelection()); Object currentSelectionKey = selection.get(0); UITree tree = (UITree) selectionChangeEvent.getSource(); tree.setRowKey(currentSelectionKey); TreeContent currentSelection = (TreeContent)tree.getRowData(); panel.setSelected(currentSelection); } }
/* * Copyright (C) 2013-2020 American Registry for Internet Numbers (ARIN) * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR * IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ package net.arin.rdap_bootstrap.json; /** * An RDAP JSON link. */ public class Link { private String value; private String rel; private String type; private String href; public String getValue() { return value; } public void setValue( String value ) { this.value = value; } public String getRel() { return rel; } public void setRel( String rel ) { this.rel = rel; } public String getType() { return type; } public void setType( String type ) { this.type = type; } public String getHref() { return href; } public void setHref( String href ) { this.href = href; } }
package blog.api.post.service; import blog.api.post.dao.PostRepository; import blog.api.post.model.entity.Post; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @Service public class PostService { private final PostRepository postRepository; @Autowired public PostService(PostRepository postRepository) { this.postRepository = postRepository; } @Transactional public Post savePost(Post post) { return postRepository.save(post); } }
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.aop.interceptor; import org.aopalliance.intercept.MethodInvocation; import org.apache.commons.logging.Log; import org.springframework.util.StopWatch; /** * Simple AOP Alliance {@code MethodInterceptor} for performance monitoring. * This interceptor has no effect on the intercepted method call. * * <p>Uses a {@code StopWatch} for the actual performance measuring. * * @author Rod Johnson * @author Dmitriy Kopylenko * @author Rob Harrop * @see org.springframework.util.StopWatch */ @SuppressWarnings("serial") public class PerformanceMonitorInterceptor extends AbstractMonitoringInterceptor { /** * Create a new PerformanceMonitorInterceptor with a static logger. */ public PerformanceMonitorInterceptor() { } /** * Create a new PerformanceMonitorInterceptor with a dynamic or static logger, * according to the given flag. * @param useDynamicLogger whether to use a dynamic logger or a static logger * @see #setUseDynamicLogger */ public PerformanceMonitorInterceptor(boolean useDynamicLogger) { setUseDynamicLogger(useDynamicLogger); } @Override protected Object invokeUnderTrace(MethodInvocation invocation, Log logger) throws Throwable { String name = createInvocationTraceName(invocation); StopWatch stopWatch = new StopWatch(name); stopWatch.start(name); try { return invocation.proceed(); } finally { stopWatch.stop(); writeToLog(logger, stopWatch.shortSummary()); } } }
package DP; import generic.ExcelReadWrite; import generic.base_class; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.testng.annotations.DataProvider; public class login_dp { @DataProvider(name="invalidlogin") public static Iterator<String[]> dp_invalidlogin() throws IOException { login_dp l = new login_dp(); List<String[]> ls =l.xlreader(base_class.b.wb,"Invalid_Login_test"); return ls.iterator(); } @DataProvider(name="validlogin") public static Iterator<String[]> dp_validlogin() throws IOException { login_dp l = new login_dp(); List<String[]> ls =l.xlreader(base_class.b.wb,"Valid_Login_test"); return ls.iterator(); } public List<String[]> xlreader(XSSFWorkbook wb, String scriptname) throws IOException { ExcelReadWrite xl = new ExcelReadWrite(wb); XSSFSheet sheet = xl.Setsheet("Scenario_login"); int rowcount = xl.getrowcount(sheet); List<String[]> ls = new ArrayList<String[]>(); for (int i=1;i<=rowcount;i++) { if(xl.Readvalue(sheet, i, "Scriptname").equalsIgnoreCase(scriptname)) { if(xl.Readvalue(sheet, i, "Execute_Flag").equalsIgnoreCase("Y")) { String[] s = new String[5]; s[0] = xl.Readvalue(sheet, i, "TC_ID"); s[1] = xl.Readvalue(sheet, i, "Order"); s[2] = xl.Readvalue(sheet, i, "Uname"); s[3] = xl.Readvalue(sheet, i, "Pwd"); s[4] = xl.Readvalue(sheet, i, "Exp_Res"); ls.add(s); } } }return ls; } }
package uz.pdp.lesson5task1.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import org.springframework.security.core.GrantedAuthority; import uz.pdp.lesson5task1.entity.enums.RoleEnum; import javax.persistence.*; @Data @AllArgsConstructor @NoArgsConstructor @Entity public class Role implements GrantedAuthority { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @Enumerated(EnumType.STRING) private RoleEnum name; @Override public String getAuthority() { return name.name(); } }
package DataStructures.trees; import java.util.*; /** Input tree, key * 5 * / \ * 4 7 * / / \ * 2 6 11 * / \ / \ * 1 3 8 12 * * Output, list of two nodes equals key */ public class TwoSumBinaryTree { public List<String> inorder(TreeNode root1, TreeNode root2, int k) { List<String> list = new ArrayList<>(); if (root1 == null || root2 == null) return list; boolean loop1 = true; boolean loop2 = true; int leftVal = 0; int rightVal = 0; Stack<TreeNode> leftSt = new Stack<>(); Stack<TreeNode> rightSt = new Stack<>(); while(true) { while (loop1) { if (root1 != null) { while (root1 != null) { leftSt.push(root1); root1 = root1.left; } } else { if (!leftSt.isEmpty()) { TreeNode temp = leftSt.pop(); leftVal = temp.val; root1 = temp.right; } loop1 = false; } } while (loop2) { if (root2 != null) { while (root2 != null) { rightSt.push(root2); root2 = root2.right; } } else { if (!rightSt.isEmpty()) { TreeNode temp = rightSt.pop(); rightVal = temp.val; root2 = temp.left; } loop2 = false; } } if (leftVal >= rightVal) break; if (leftVal + rightVal == k) { list.add(leftVal + "," + rightVal); loop1 = loop2 = true; continue; } if (leftVal + rightVal > k) { loop2 = true; } else { loop1 = true; } } return list; } public static boolean twoSum(TreeNode root, int target) { if (root == null) return false; return findTargetRecursion(root, new HashSet<>(), target); } public static boolean findTargetRecursion(TreeNode root, Set<Integer> set, int k) { /*if (root == null) return false; boolean isTargetAvail = false; if (set.contains(k - Math.abs(root.val))) { return true; } else { set.add(root.val); } if (!isTargetAvail) { isTargetAvail = findTargetRecursion(root.left, set, k); } if (!isTargetAvail) { isTargetAvail = findTargetRecursion(root.right, set, k); } return isTargetAvail;*/ if (root == null) return false; if (set.contains(k - root.val)) { return true; } set.add(root.val); boolean left = findTargetRecursion(root.left, set, k); boolean right = findTargetRecursion(root.right, set, k); return left || right; } public static boolean twoSumRecursion1(TreeNode root, Set<Integer> set, int target) { if (root == null) return false; boolean isSum = twoSumRecursion1(root.left, set, target); if (set.contains(target - root.val)) { return true; } else { set.add(root.val); } isSum = twoSumRecursion1(root.right, set, target); return isSum; } public static void main(String a[]) { TwoSumBinaryTree twosum = new TwoSumBinaryTree(); TreeNode root = new TreeNode(5, new TreeNode(4, new TreeNode(2, new TreeNode(1, null, null), new TreeNode(3, null, null)), null), new TreeNode(7, new TreeNode(6, null, null), new TreeNode(11, new TreeNode(8, null, null), new TreeNode(12, null, null)))); /*TreeNode root = new TreeNode(2, new TreeNode(1, null, null), new TreeNode(3, null, null));*/ //twosum.inorder(root, root, 0); boolean isTwoSum = twoSum(root, 23); System.out.println(isTwoSum); } }
package com.example.qiumishequouzhan.Utils; import com.example.qiumishequouzhan.Constant; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class HttpUtils { /** * 从一个URL上面读取内容 * @param URL */ private static byte[] GetURLContent(String URL, String Method, String Params, String ContentType, String CharSet) { byte[] Buffer = null; if(Params == null) Params = ""; try { Method = Method.toUpperCase(); URL url = new URL(URL); // 使用HttpURLConnection打开连接 HttpURLConnection urlConn = (HttpURLConnection)url.openConnection(); if(Method.equals("POST") == true) { //因为这个是post请求,设立需要设置为true urlConn.setDoOutput(true); urlConn.setDoInput(true); // Post 请求不能使用缓存 urlConn.setUseCaches(false); urlConn.setInstanceFollowRedirects(true); // 配置本次连接的Content-type,配置为application/x-www-form-urlencoded的 urlConn.setRequestProperty("Content-Type",ContentType); //设置编码格式 urlConn.setRequestProperty("Accept-Charset", CharSet); } // 设置Method urlConn.setRequestMethod(Method); //设置超时 urlConn.setConnectTimeout(50 * 1000); // 连接,从postUrl.openConnection()至此的配置必须要在connect之前完成, // 要注意的是connection.getOutputStream会隐含的进行connect。 urlConn.connect(); if(Method.equals("POST") == true) { byte[] sBuffer = Params.getBytes(CharSet); //DataOutputStream流 DataOutputStream out = new DataOutputStream(urlConn.getOutputStream()); //将要上传的内容写入流中 out.write(sBuffer, 0, sBuffer.length); //刷新、关闭 out.flush(); out.close(); } int ResponseCode = urlConn.getResponseCode(); if (ResponseCode == 200) { final InputStream inputStream = urlConn.getInputStream(); final ByteArrayOutputStream ByteArray = new ByteArrayOutputStream(); final byte[] b = new byte[256]; int rv = 0; while ( ( rv = inputStream.read(b) ) > 0 ) ByteArray.write(b, 0, rv); Buffer = ByteArray.toByteArray(); ByteArray.close(); inputStream.close(); } urlConn.disconnect(); } catch (Exception e) { LogUitls.WriteLog("HttpUtils", "GetURLContent", URL, e); } return Buffer; } /** * 以Get方式获取服务器返回数据 * @param URL 服务器地址 * @return */ public static byte[] GetURLContent(String URL) { return GetURLContent(URL, "GET", "", "text/html", Constant.DEFAULT_CHARSET); } public static byte[] GetWebServiceJsonContent(String URL, String Params) { return GetURLContent(URL, "POST", Params, "application/json;utf-8", Constant.DEFAULT_CHARSET); } public static byte[] GetURLContent_img(String URL) { byte[] Buffer = null; final InputStream inputStream = getInputStream(URL); final ByteArrayOutputStream ByteArray = new ByteArrayOutputStream(); try { final byte[] b = new byte[256]; int rv = 0; while ( ( rv = inputStream.read(b) ) > 0 ) ByteArray.write(b, 0, rv); Buffer = ByteArray.toByteArray(); ByteArray.close(); inputStream.close(); } catch (Exception e) { LogUitls.WriteLog("HttpUtils", "GetURLContent", URL, e); } return Buffer; } public static InputStream getInputStream(String path) { InputStream inputStream = null; HttpURLConnection httpURLConnection = null; try { URL url = new URL(path); if (null != url) { httpURLConnection = (HttpURLConnection) url.openConnection(); // 设置连接网络的超时时间 httpURLConnection.setConnectTimeout(5000); // 打开输入流 httpURLConnection.setDoInput(true); // 设置本次Http请求使用的方法 httpURLConnection.setRequestMethod("GET"); if (200 == httpURLConnection.getResponseCode()) { // 从服务器获得一个输入流 inputStream = httpURLConnection.getInputStream(); } } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return inputStream; } }
package io.chark.food.domain.restaurant; import io.chark.food.domain.BaseEntity; import javax.persistence.*; import javax.validation.constraints.Size; @Entity public class RestaurantDetails extends BaseEntity { // Imones kodas @Size(max = DEFAULT_LENGTH) @Column(unique = true, nullable = false, length = DEFAULT_LENGTH) private String registrationCode; //moketojo kodas @Size(max = DEFAULT_LENGTH) @Column(unique = true, nullable = false, length = DEFAULT_LENGTH) private String vat; @Size(max = DEFAULT_LENGTH) @Column(nullable = false, length = DEFAULT_LENGTH) private String manager; private String phoneNumber; private String fax; private String website; private int employees; private String mobileNumber; @Size(max = DEFAULT_LENGTH) @Column(unique = true, nullable = false, length = DEFAULT_LENGTH) private String bankAccountNumber; @ManyToOne private Bank bank; @OneToOne() private Restaurant restauant; public RestaurantDetails() { } public RestaurantDetails(String mobileNumber, String bankAccountNumber, String vat, String registrationCode, String manager) { this.mobileNumber = mobileNumber; this.bankAccountNumber = bankAccountNumber; this.vat = vat; this.registrationCode = registrationCode; this.manager = manager; } public void setRestauant(Restaurant restauant) { this.restauant = restauant; } public String getRegistrationCode() { return registrationCode; } public void setRegistrationCode(String registrationCode) { this.registrationCode = registrationCode; } public String getVat() { return vat; } public void setVat(String vat) { this.vat = vat; } public String getManager() { return manager; } public void setManager(String manager) { this.manager = manager; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getFax() { return fax; } public void setFax(String fax) { this.fax = fax; } public String getWebsite() { return website; } public void setWebsite(String website) { this.website = website; } public int getEmployees() { return employees; } public void setEmployees(int employees) { this.employees = employees; } public String getMobileNumber() { return mobileNumber; } public void setMobileNumber(String mobileNumber) { this.mobileNumber = mobileNumber; } public String getBankAccountNumber() { return bankAccountNumber; } public void setBankAccountNumber(String bankAccountNumber) { this.bankAccountNumber = bankAccountNumber; } public void setBank(Bank bank) { this.bank = bank; } public Bank getBank() { return bank; } public Restaurant getRestauant() { return restauant; } }
package com.classroom.services.infrastructure.persistence.hibernate; import java.util.ArrayList; import java.util.List; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import org.hibernate.criterion.CriteriaQuery; import org.joda.time.LocalDateTime; import org.springframework.stereotype.Repository; import com.classroom.services.domain.model.Circulars; import com.classroom.services.domain.model.CircularsBatch; import com.classroom.services.domain.model.repositories.ICircularsBatchRepository; import com.classroom.services.domain.model.repositories.ICircularsRepository; import com.classroom.services.domain.model.repositories.criteria.CircularsBatchSearchCriteria; import com.classroom.services.domain.model.repositories.criteria.CircularsSearchCriteria; import com.classroom.services.facade.dto.entities.CircularBatchSearchDTO; import com.classroom.services.facade.dto.entities.CircularDTO; import com.classroom.services.facade.dto.entities.CircularSearchDTO; @Repository public class CircularsBatchRepository extends BaseRepository<CircularsBatch, CircularsBatchSearchCriteria> implements ICircularsBatchRepository{ public List<CircularsBatch> getCircularBatch(CircularBatchSearchDTO searchDTO) { List<CircularsBatch> circulars = null; javax.persistence.criteria.CriteriaQuery<CircularsBatch> query = getCriteriaBuilder() .createQuery(CircularsBatch.class); Root<CircularsBatch> from = query.from(CircularsBatch.class); Predicate[] predicates = new Predicate[2]; predicates[0] = getCriteriaBuilder().equal(from.get("eventID"), searchDTO.getEventID()); predicates[1] = getCriteriaBuilder().equal(from.get("batchID"), searchDTO.getBatchID()); query.where(predicates); query.select(from); // System.out.println("before query"); circulars = getResultList(query); //System.out.println("homework size "+ circulars.size()); //Homework getHomework = new Homework(); List<CircularsBatch> circularslist = new ArrayList<CircularsBatch>(); if (circulars.size() >= 1) { for (Integer i = 0; i < circulars.size(); i++) { circularslist.add(circulars.get(i)); } } return circularslist; } }
package action; public class turntoregister { }
package com.mertcan.myapplication; import android.content.Context; import android.os.Handler; import android.util.Log; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.net.Socket; /** * Created by Mertcan on 31.12.2016. */ public class Client { boolean logged=false; String nick=""; Socket mySocket; Thread myThread; DataInputStream datain; DataOutputStream dataout; int sayac=0; receiverActivity activity; public void destroy(){ try { myThread.interrupt(); Log.i("TCP","disconnected:"+mySocket); dataout.close(); datain.close(); mySocket.close(); } catch (IOException e) { e.printStackTrace(); } } public void dinle(){ Runnable runnable=new Runnable() { String komut=""; @Override public void run() { while(!myThread.isInterrupted()){ try { sayac++; if(!mySocket.isClosed()) if(datain.available()>0){ int ekle=datain.read(); if(ekle!=13){ komut+=(char)ekle;}else{ cozumle(komut); komut=""; } sayac=0; } myThread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if(sayac==6000){ destroy(); } }} }; myThread=new Thread(runnable); myThread.start(); } public void cozumle(String komut){ Log.i("TCP","komut:"+komut); if(komut.length()>0) { if (komut.charAt(0) == '&') { selfCommand(komut); } else { Log.i("TCP", komut); } } } private void selfCommand(String komut){ Log.i("TCP","komut:"+komut); if(komut.length()>6) switch(komut.substring(1,5)){ case "LOGN": String[] cikti=(komut.substring(6,komut.length())).split("\\|"); System.out.println(komut); nick=cikti[0]; String sifre=cikti[1]; Log.i("TCP","loginAttempt:"+nick+":"+sifre); if(sifre.equals("123456789")){logged=true; yenile(); }else{ gonder("&FAIL"); } break; case "CHNG": if(logged){ String[] cikti2=(komut.substring(6,komut.length())).split("\\|"); byte x=(byte)Integer.parseInt(cikti2[0]),y=(byte)Integer.parseInt(cikti2[1]); Log.i("TCP","YAP:"+x+":"+y); byte yap=(byte)((x<<1)|y); activity.ackapa(yap); try { Thread.currentThread().sleep(1002); } catch (InterruptedException e) { e.printStackTrace(); } }else{ Log.i("TCP","Not logged in"); } break; } } public void yenile(){ String gonder=""; for(int i =0;i<8;i++){ gonder+=""+((activity.durum>>i)&0x01); } gonder("&UPDT&"+gonder); } public void gonder(String x){ final String komut=x+"\r"; Runnable xx= new Runnable() { @Override public void run() { try { dataout.write(komut.getBytes()); dataout.flush(); } catch (IOException e) { e.printStackTrace(); } } }; new Thread(xx).start(); } public Client(Context cont,Socket socket){ mySocket=socket; try { datain=new DataInputStream(socket.getInputStream()); dataout=new DataOutputStream(socket.getOutputStream()); } catch (IOException e) { e.printStackTrace(); } activity=(receiverActivity) cont; dinle(); } }
package com.example.van.baotuan.VP.home.MsgBoard; import android.content.Context; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.TextView; import com.andview.refreshview.recyclerview.BaseRecyclerAdapter; import com.example.van.baotuan.R; import butterknife.BindView; import butterknife.ButterKnife; /** * Created by Van on 2016/11/07. */ public class MsgBoardAdapter extends BaseRecyclerAdapter<MsgBoardAdapter.MsgViewHolder> { private Context context; public MsgBoardAdapter(Context context) { this.context = context; } @Override public void onBindViewHolder(MsgViewHolder holder, int position, boolean isItem) { } @Override public int getAdapterItemCount() { return 10; } @Override public MsgViewHolder getViewHolder(View view) { return new MsgViewHolder(view,false); } @Override public MsgViewHolder onCreateViewHolder(ViewGroup parent, int viewType, boolean isItem) { MsgViewHolder holder = new MsgViewHolder(LayoutInflater.from(context) .inflate(R.layout.item_msg, parent, false),true); return holder; } //ViewHolder class MsgViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.IV_avatar) ImageView IV_Avatar; @BindView(R.id.TV_userName) TextView TV_UserName; @BindView(R.id.TV_time) TextView TV_Time; @BindView(R.id.TV_content) TextView TV_Content; public MsgViewHolder(View itemView,boolean isItem) { super(itemView); if (!isItem){ return; } ButterKnife.bind(this, itemView); } } }
package xyz.noark.core.exception; import xyz.noark.core.annotation.Autowired; import xyz.noark.core.annotation.StaticComponent; import xyz.noark.core.event.EventManager; import xyz.noark.core.network.NetworkListener; import xyz.noark.core.network.NetworkPacket; import xyz.noark.core.network.Session; /** * 异常小助手. * * @author 小流氓[176543888@qq.com] */ @StaticComponent public class ExceptionHelper { @Autowired(required = false) private static NetworkListener networkListener; @Autowired(required = false) private static EventManager eventManager; private ExceptionHelper() { } /** * 监控Socket业务中的未知异常. * * @param session Socket会话 * @param packet 封包 * @param e 异常堆栈 */ public static void monitor(Session session, NetworkPacket packet, Throwable e) { // 额外处理逻辑 if (networkListener != null) { networkListener.handleException(session, packet, e); } } public static void monitor(Throwable e) { // 以事件形式发布这个异常,由具体项目来决定是打印还是上报... eventManager.publish(new ExceptionEvent(e)); } }
package com.mouris.mario.captainmovie.UI; import android.arch.lifecycle.ViewModelProviders; import android.content.Intent; import android.net.Uri; import android.os.Handler; import android.support.constraint.ConstraintLayout; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ProgressBar; import android.widget.TextView; import com.mouris.mario.captainmovie.Data.Movie; import com.mouris.mario.captainmovie.R; import com.mouris.mario.captainmovie.Utils.NetworkUtils; import com.squareup.picasso.Picasso; public class MainActivity extends AppCompatActivity { // private static final String LOG_TAG = MainActivity.class.getSimpleName(); private static final int ANIMATION_DURATION = 600; private ImageView mSkyImageView; private ConstraintLayout mCaptainLayout; private LinearLayout mMovieLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTheme(R.style.AppTheme); setContentView(R.layout.activity_main); MainViewModel viewModel = ViewModelProviders.of(this).get(MainViewModel.class); //To update the mode we're in viewModel.getRandomMovie().observe(this, movie -> { if (movie != null) { //Go to movie mode bindDataToMovieLayout(movie); goToMovieMode(); } else { //Go to captain mode goToCaptainMode(); } }); //To update the loading state ProgressBar progressBar = findViewById(R.id.progressBar); viewModel.isLoading().observe(this, isLoading -> { if (isLoading) { progressBar.setVisibility(View.VISIBLE); } else { progressBar.setVisibility(View.GONE); } }); mCaptainLayout = findViewById(R.id.captainLayout); mMovieLayout = findViewById(R.id.movieLayout); mSkyImageView = findViewById(R.id.sky); FloatingActionButton cancelFab = findViewById(R.id.cancelFAB); Button askCaptainButton = findViewById(R.id.askCaptainButton); cancelFab.setOnClickListener(v-> { viewModel.removeCurrentMovie(); askCaptainButton.setEnabled(true); }); askCaptainButton.setOnClickListener(v-> { if (NetworkUtils.isNetworkConnected(this)) { askCaptainButton.setEnabled(false); viewModel.loadRandomMovie(); } else { Snackbar.make(mSkyImageView, R.string.no_internet_message, Snackbar.LENGTH_LONG).show(); } }); } private void bindDataToMovieLayout(Movie movie) { TextView titleTV = findViewById(R.id.titleTextView); TextView genresTV = findViewById(R.id.generesTextView); TextView overviewTV = findViewById(R.id.overviewTextView); TextView rateTV = findViewById(R.id.rateTextView); ImageView posterImageView = findViewById(R.id.posterImageView); Button visitHomePageButton = findViewById(R.id.visitHomePageButton); new Handler().postDelayed(()-> { titleTV.setText(movie.title); overviewTV.setText(movie.overview); String rateString = String.format(getResources().getString(R.string.movie_vote_average), String.valueOf((int) movie.vote_average)); rateTV.setText(rateString); String genresString = String.format(getResources().getString(R.string.movie_genres), movie.genres); genresTV.setText(genresString); if (movie.homepage.isEmpty()) { visitHomePageButton.setVisibility(View.GONE); } else { visitHomePageButton.setVisibility(View.VISIBLE); visitHomePageButton.setOnClickListener(v->{ Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(movie.homepage)); startActivity(intent); }); } }, 100); posterImageView.setImageResource(R.drawable.poster_placeholder); new Handler().postDelayed(()-> Picasso.with(this).load(movie.poster_path) .placeholder(R.drawable.poster_placeholder) .into(posterImageView), 700); } private void goToCaptainMode() { //Show the captain layout mCaptainLayout.animate().withLayer().translationY(0).setDuration(ANIMATION_DURATION); //Hide the movie layout mMovieLayout.animate().withLayer().translationY(-1550).setDuration(ANIMATION_DURATION); //Zoom out of the sky mSkyImageView.animate().withLayer().scaleXBy(-0.8f) .scaleYBy(-0.8f).setDuration(ANIMATION_DURATION); } private void goToMovieMode() { //Hide the captain layout mCaptainLayout.animate().withLayer().translationY(1250).setDuration(ANIMATION_DURATION); //Show the movie layout mMovieLayout.setTranslationY(-1550); mMovieLayout.setVisibility(View.VISIBLE); mMovieLayout.animate().withLayer().translationY(0).setDuration(ANIMATION_DURATION); //Zoom into the sky mSkyImageView.animate().withLayer().scaleXBy(0.8f) .scaleYBy(0.8f).setDuration(ANIMATION_DURATION); } }
/* * 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 com.danilocarreiro.carros.models; import com.danilocarreiro.carros.entities.CarEntity; import com.danilocarreiro.carros.helpers.ResponseStatus; import java.util.List; /** * * @author DANILODOSSANTOSCARRE */ public interface ICarModel { public ResponseStatus<CarEntity> select(int carcode,String carChassi, String carPlaque); public ResponseStatus<CarEntity> create(CarEntity carEntity); public ResponseStatus<List<CarEntity>> list(); public ResponseStatus<CarEntity> update(CarEntity carEntity); public ResponseStatus<CarEntity> delete(CarEntity carEntity); }
package es.codeurjc.gameweb.models; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Lob; import javax.persistence.OneToMany; import javax.persistence.OneToOne; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonView; import java.sql.Blob; import org.hibernate.annotations.DynamicUpdate; @Entity @DynamicUpdate public class Game { public interface gameBasico{} @Id @GeneratedValue(strategy = GenerationType.AUTO) @JsonView(gameBasico.class) private Long id; @Lob @JsonIgnore private Blob imageFile; @JsonIgnore private boolean image; @JsonView(gameBasico.class) private String gameTitle; @JsonView(gameBasico.class) private Genres genre; @Column(columnDefinition = "LONGBLOB") HashMap<Long, Integer> mapScores = new HashMap<Long, Integer>(); @JsonView(gameBasico.class) private float averageScore; @Column(columnDefinition = "TEXT") @JsonView(gameBasico.class) private String description; @OneToOne(cascade=CascadeType.ALL) private Chat chat; @OneToMany(mappedBy = "fromGame",cascade = CascadeType.ALL,orphanRemoval = true) private List<Post> thePosts=new ArrayList<>(); @JsonView(gameBasico.class) private String imagePath; public String getImagePath() { return this.imagePath; } public void setImagePath(String imagePath) { this.imagePath = imagePath; } public Game(){} public Game(String gameTitle, Genres genre, String description) { super(); this.gameTitle = gameTitle; this.genre = genre; this.description = description; this.mapScores.put((long) 0, 0); } public List<Post> getThePosts() { return this.thePosts; } public void addPost(Post p){ thePosts.add(p); p.setFromGame(this); } public void removePost(Post p){ thePosts.remove(p); p.setFromGame(null); } public void setThePosts(List<Post> thePosts) { this.thePosts = thePosts; } public String getGameTitle() { return gameTitle; } public void setGameTitle(String gameTitle) { this.gameTitle = gameTitle; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Genres getGenre() { return genre; } public void setGenre(Genres genre) { this.genre = genre; } public float getAverageScore() { return averageScore; } public void setAverageScore(float averageScore) { this.averageScore = averageScore; } public Chat getChat() { return chat; } public void setChat(Chat chat) { this.chat = chat; } public Blob getImageFile() { return imageFile; } public void setImageFile(Blob blob) { this.imageFile = blob; } public boolean isImage() { return this.image; } public void setImage(boolean image) { this.image = image; } public HashMap<Long, Integer> getMapScores() { return mapScores; } public void setMapScores(HashMap<Long, Integer> mapScores) { this.mapScores = mapScores; } }
package org; public class Lol {}
package macro2; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.FileReader; import java.io.IOException; import java.io.OutputStream; class MNT{ String name; int pp; int kp; int mdtp; int kpdtp; MNT(String n,int p,int kp,int m,int k){ name = n; pp = p; this.kp= kp; mdtp = m; kpdtp = k; } static int Search(MNT mnt[],int n,String key) { int index =-1; for(int i =1;i<n;i++) { if(mnt[i].name.equals(key)){ return i; } } return index; } } class KPTAB{ int index; String name; String value; public KPTAB(String name, String value) { this.name = name; this.value = value; } static int searchByName(KPTAB kptab[],int n,String key) { int index=-1; for(int i =0;i<n;i++) { if(kptab[i].name.equals(key)) { return i; } } return index; } } public class Pass2 { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub String mdt[] = new String[100]; MNT mnt[] = new MNT[100]; String calls[] = new String[100]; KPTAB kptab[] = new KPTAB[20]; String line; int mntptr =1,mdtptr =1, kpptr = 1,call=1; FileReader fr = new FileReader("MNT.txt"); BufferedReader br = new BufferedReader(fr); FileReader fr1 = new FileReader("MDT.txt"); BufferedReader br1 = new BufferedReader(fr1); FileReader fr2 = new FileReader("KPDTAB.txt"); BufferedReader br2 = new BufferedReader(fr2); FileReader fr3 = new FileReader("calls.txt"); BufferedReader br3 = new BufferedReader(fr3); OutputStream os = new FileOutputStream(new File("final.txt")); while((line = br.readLine())!=null){ String s[] = line.split(" "); mnt[mntptr] = new MNT(s[0],Integer.parseInt(s[1]),Integer.parseInt(s[2]),Integer.parseInt(s[3]),Integer.parseInt(s[4])); //System.out.println(mnt[mntptr].name + " "+ mnt[mntptr].pp + " " + mnt[mntptr].kp + " " + mnt[mntptr].mdtp + " "+ mnt[mntptr].kpdtp); mntptr++; } while((line = br1.readLine()) != null){ //String s[] = line.split(" "); mdt[mdtptr] = line; mdtptr++; } while((line = br3.readLine()) != null){ //String s[] = line.split(" "); calls[call] = line; call++; } while((line = br2.readLine()) != null){ String s[] = line.split(" "); kptab[kpptr] = new KPTAB(s[1],s[2]); //System.out.println(kptab[kpptr].name +" "+ kptab[kpptr].value ); kpptr++; } //process every call; for(int i =1;i<call;i++){ String s[] = calls[i].split(" ");//current call //search for name in MNT and get pp and kp to form APTAB int mnt_index = MNT.Search(mnt,mntptr,s[0]); String[] params = s[1].split(","); int kp = mnt[mnt_index].kp; int pp = mnt[mnt_index].pp; String aptab[] = new String[kp+pp+1]; //copy value of positional parameters from call for(int j=0;j<pp;j++) { aptab[j+1] = params[j]; } //copy value of default keyword parameters from kptab int kp_ptr = mnt[mnt_index].kpdtp; for(int j=0;j<kp;j++) { aptab[pp+j+1]=kptab[kp_ptr+j].value; } //search for keyword parameters in call, if present, replace their values in aptab if(params.length>pp) { for(int j=kp_ptr;j<kp_ptr+kp;j++) { String sub = "&" + kptab[j].name; //search sub in params for(int k =pp;k<params.length;k++) { if(params[k].contains(sub)) { // int aptab_ptr = j+1 - kp_ptr +pp; aptab[aptab_ptr]=params[k].split("=")[1]; } } } } //now replace (P,n) with aptab[n] in MDT till MEND and write it to "finalcode.txt" int j = mnt[mnt_index].mdtp; while(mdt[j].equals("MEND")==false) { for(int k =1;k<aptab.length;k++) { mdt[j] = mdt[j].replace("(P,"+k+")", aptab[k]); } line = mdt[j]+'\n'; os.write(line.getBytes(),0,line.length()); j++; } } os.close(); br.close(); br1.close(); br2.close(); br3.close(); } }
package com.esum.comp.ftasoap.message; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Hashtable; import java.util.Iterator; import java.util.Properties; import javax.xml.soap.MessageFactory; import javax.xml.soap.SOAPBody; import javax.xml.soap.SOAPBodyElement; import javax.xml.soap.SOAPEnvelope; import javax.xml.soap.SOAPException; import javax.xml.soap.SOAPFactory; import javax.xml.soap.SOAPHeader; import javax.xml.soap.SOAPHeaderElement; import javax.xml.soap.SOAPMessage; import org.apache.commons.io.IOUtils; import org.apache.log4j.Logger; import com.esum.comp.ftasoap.message.util.SOAPDimeUtils; /** * SOAP 메시지를 Build 하는 클래스 * * @author kim.misun (eSum Technologies) * @since 2011. 6. */ public class SOAPBuilder { private static Logger logger = Logger.getLogger(SOAPBuilder.class); /** * Dime 파일 없이 메시지 생성 (수신완료 요청 생성 등...) */ public static byte[] build(SOAPMessageInfo soapMsgInfo) throws SOAPException, IOException { SOAPMessage soapMsg = buildSOAPMessage(soapMsgInfo, false); addHeaderElement(soapMsg, SOAPElement.ACTION, soapMsgInfo.getAction()); if (soapMsgInfo.getMessageId() != null) addHeaderElement(soapMsg, SOAPElement.MESSAGE_ID, soapMsgInfo.getMessageId()); if (soapMsgInfo.getSearchUser() != null) addHeaderElement(soapMsg, SOAPElement.SEARCH_USER, soapMsgInfo.getSearchUser()); if (soapMsgInfo.getSearchFromToDate() != null) addHeaderElement(soapMsg, SOAPElement.SEARCH_FROM_TO_DATE, soapMsgInfo.getSearchFromToDate()); if (soapMsgInfo.getOption() != null) addHeaderElement(soapMsg, SOAPElement.OPTION, soapMsgInfo.getOption()); if (soapMsgInfo.getParams() != null) addHeaderElement(soapMsg, SOAPElement.PARAMS, soapMsgInfo.getParams()); if (soapMsgInfo.getRespCode() != null) addHeaderElement(soapMsg, SOAPElement.RESPONSE_CODE, soapMsgInfo.getRespCode()); if (soapMsgInfo.getRespMsg() != null) addHeaderElement(soapMsg, SOAPElement.RESPONSE_MSG, soapMsgInfo.getRespMsg()); FileInfo fileList[] = soapMsgInfo.getFileList(); for (int i = 0; i < fileList.length; i++) { FileInfo fileInfo = fileList[i]; Properties fileInfos = new Properties(); fileInfos.setProperty(FileInfo.FILE_ID, fileInfo.fileId); fileInfos.setProperty(FileInfo.FILE_SENDER, fileInfo.fileSender); fileInfos.setProperty(FileInfo.FILE_RECEIVER, fileInfo.fileReceiver); fileInfos.setProperty(FileInfo.FILE_TYPE, fileInfo.fileType); fileInfos.setProperty(FileInfo.FILE_NUMBER, fileInfo.fileNumber); fileInfos.setProperty(FileInfo.FILE_VERSION, fileInfo.fileVersion); fileInfos.setProperty(FileInfo.FILE_NAME, fileInfo.fileName); fileInfos.setProperty(FileInfo.FILE_SIZE, fileInfo.fileSize); addBodyElementAttributes(soapMsg, SOAPElement.FILE_LIST, fileInfo.filePath, fileInfos); } ByteArrayOutputStream out = null; try { out = new ByteArrayOutputStream(); soapMsg.writeTo(out); return SOAPDimeUtils.buildDimeMessage(out.toByteArray()); } finally { IOUtils.closeQuietly(out); } } /** * Dime 파일에 메시지 생성 (송신 요청, 수신 응답 생성) */ public static void build(SOAPMessageInfo soapMsgInfo, OutputStream output) throws SOAPException, IOException { SOAPMessage soapMsg = buildSOAPMessage(soapMsgInfo, true); addHeaderElement(soapMsg, SOAPElement.ACTION, soapMsgInfo.getAction()); if (soapMsgInfo.getMessageId() != null) addHeaderElement(soapMsg, SOAPElement.MESSAGE_ID, soapMsgInfo.getMessageId()); if (soapMsgInfo.getSearchUser() != null) addHeaderElement(soapMsg, SOAPElement.SEARCH_USER, soapMsgInfo.getSearchUser()); if (soapMsgInfo.getSearchFromToDate() != null) addHeaderElement(soapMsg, SOAPElement.SEARCH_FROM_TO_DATE, soapMsgInfo.getSearchFromToDate()); if (soapMsgInfo.getRespCode() != null) addHeaderElement(soapMsg, SOAPElement.RESPONSE_CODE, soapMsgInfo.getRespCode()); if (soapMsgInfo.getRespMsg() != null) addHeaderElement(soapMsg, SOAPElement.RESPONSE_MSG, soapMsgInfo.getRespMsg()); Hashtable<String, Object> payloads = new Hashtable<String, Object>(); FileInfo fileList[] = soapMsgInfo.getFileList(); for (int i = 0; i < fileList.length; i++) { FileInfo fileInfo = fileList[i]; Properties fileInfos = new Properties(); fileInfos.setProperty(FileInfo.FILE_ID, fileInfo.fileId); fileInfos.setProperty(FileInfo.FILE_SENDER, fileInfo.fileSender); fileInfos.setProperty(FileInfo.FILE_RECEIVER, fileInfo.fileReceiver); fileInfos.setProperty(FileInfo.FILE_TYPE, fileInfo.fileType); fileInfos.setProperty(FileInfo.FILE_NUMBER, fileInfo.fileNumber); fileInfos.setProperty(FileInfo.FILE_VERSION, fileInfo.fileVersion); fileInfos.setProperty(FileInfo.FILE_NAME, fileInfo.fileName); fileInfos.setProperty(FileInfo.FILE_SIZE, fileInfo.fileSize); if(fileInfo.filePath!=null && fileInfo.filePath.equals("")) addBodyElementAttributes(soapMsg, SOAPElement.FILE_LIST, fileInfo.filePath, fileInfos); else addBodyElementAttributes(soapMsg, SOAPElement.FILE_LIST, fileInfo.fileName, fileInfos); payloads.put(fileInfo.fileName, fileInfo.fileData); } ByteArrayOutputStream out = null; try { out = new ByteArrayOutputStream(); soapMsg.writeTo(out); SOAPDimeUtils.buildDimeMessage(out.toByteArray(), payloads, output); } finally { IOUtils.closeQuietly(out); } } public static SOAPMessage buildSOAPMessage(SOAPMessageInfo soapMsgInfo, boolean hasBody) throws SOAPException { SOAPMessage soapMsg = MessageFactory.newInstance().createMessage(); soapMsg.setProperty(javax.xml.soap.SOAPMessage.WRITE_XML_DECLARATION, "true"); SOAPFactory soapFactory = SOAPFactory.newInstance(); SOAPEnvelope soapEnvelope = soapMsg.getSOAPPart().getEnvelope(); soapEnvelope.setPrefix(SOAPMessageUtil.NS1); soapEnvelope.removeNamespaceDeclaration("SOAP-ENV"); soapEnvelope.removeNamespaceDeclaration("soapenv"); soapEnvelope.addNamespaceDeclaration(SOAPMessageUtil.NS1, "http://schemas.xmlsoap.org/soap/envelope/"); soapEnvelope.addNamespaceDeclaration("xsi", "http://www.w3.org/2001/XMLSchema-instance"); soapEnvelope.addNamespaceDeclaration("xlink", "http://www.w3.org/1999/xlink"); soapEnvelope.addAttribute(soapFactory.createName("schemaLocation", "xsi", ""), "http://schemas.xmlsoap.org/soap/envelope/ " + "http://www.oasis-open.org/committees/ebxml-msg/schema/envelope.xsd"); // SOAP Header 초기화 SOAPHeader soapHeader = soapEnvelope.getHeader(); soapHeader.setPrefix(SOAPMessageUtil.NS1); soapHeader.addNamespaceDeclaration(SOAPMessageUtil.NS2, SOAPMessageUtil.NS2_URL); soapHeader.addAttribute(soapFactory.createName("schemaLocation", "xsi", ""), SOAPMessageUtil.NS2_LOCATION); // SOAP Body 초기화 SOAPBody soapBody = soapEnvelope.getBody(); soapBody.setPrefix(SOAPMessageUtil.NS1); // SOAP Body 가 없을 경우 if (hasBody != false) { soapBody.addNamespaceDeclaration(SOAPMessageUtil.NS2, SOAPMessageUtil.NS2_URL); soapBody.addAttribute(soapFactory.createName("schemaLocation", "xsi", ""), SOAPMessageUtil.NS2_LOCATION); } return soapMsg; } public static SOAPMessage addHeaderElement(SOAPMessage soapMsg, String elementName, String elementValue) throws SOAPException { SOAPFactory soapFactory = SOAPFactory.newInstance(); SOAPEnvelope soapEnv = soapMsg.getSOAPPart().getEnvelope(); SOAPHeaderElement SoapHeaderElement = soapEnv.getHeader().addHeaderElement( soapFactory.createName(elementName, SOAPMessageUtil.NS2, SOAPMessageUtil.NS2_URL)); SoapHeaderElement.setValue(elementValue); return soapMsg; } public static SOAPMessage addBodyElement(SOAPMessage soapMsg, String elementName, String elementValue) throws SOAPException { SOAPFactory soapFactory = SOAPFactory.newInstance(); SOAPEnvelope soapEnv = soapMsg.getSOAPPart().getEnvelope(); SOAPBodyElement soapBodyElement = soapEnv.getBody().addBodyElement( soapFactory.createName(elementName, SOAPMessageUtil.NS2, SOAPMessageUtil.NS2_URL)); soapBodyElement.setValue(elementValue); return soapMsg; } /** * add body element with child element 자식노드에는 정해진 네임스페이스를 넣지 않는다. */ public static SOAPMessage addBodyElementChilds(SOAPMessage soapMsg, String elementName, Properties childElements) throws SOAPException { SOAPFactory soapFactory = SOAPFactory.newInstance(); SOAPEnvelope soapEnv = soapMsg.getSOAPPart().getEnvelope(); SOAPBodyElement soapBodyElement = soapEnv.getBody().addBodyElement( soapFactory.createName(elementName, SOAPMessageUtil.NS2, SOAPMessageUtil.NS2_URL)); if (childElements != null && !childElements.isEmpty()) { Iterator childIter = childElements.keySet().iterator(); for (String key, value = null; childIter.hasNext();) { key = (String) childIter.next(); value = childElements.getProperty(key); soapBodyElement.addChildElement(soapFactory.createName(key)).setValue(value); logger.debug("addChildElement : " + key + "=" + value); } } return soapMsg; } /** * add body Element with attribute */ public static SOAPMessage addBodyElementAttributes(SOAPMessage soapMsg, String elementName, String elementValue, Properties attributes) throws SOAPException { SOAPFactory soapFactory = SOAPFactory.newInstance(); SOAPEnvelope soapEnv = soapMsg.getSOAPPart().getEnvelope(); SOAPBodyElement soapBodyElement = soapEnv.getBody().addBodyElement( soapFactory.createName(elementName, SOAPMessageUtil.NS2, SOAPMessageUtil.NS2_URL)); soapBodyElement.setValue(elementValue); if (attributes != null && !attributes.isEmpty()) { Iterator attIter = attributes.keySet().iterator(); for (String key, value = null; attIter.hasNext();) { key = (String) attIter.next(); value = attributes.getProperty(key); soapBodyElement.setAttribute(key, value); } } return soapMsg; } }
package com.agilesoftware.bookgonara.bookgo.Database; public class BookgoClient { }
package com.androidsample.contentprovidersample; import android.content.ContentResolver; import android.content.ContentValues; import android.database.ContentObserver; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.EditText; import android.widget.ListView; import android.widget.SimpleCursorAdapter; public class MainActivity extends AppCompatActivity { private SimpleCursorAdapter mAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final ListView listView = (ListView) findViewById(R.id.data_list); final EditText editText = (EditText) findViewById(R.id.name_et); final ContentResolver contentResolver = getContentResolver(); findViewById(R.id.btn_add).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (editText.getText().length() <= 0) return; ContentValues contentValues = new ContentValues(); contentValues.put("name", editText.getText().toString()); contentResolver.insert(Uri.parse("content://com.androidsample.contentprovidersample/names/"), contentValues); Cursor cursor = contentResolver.query(Uri.parse("content://com.androidsample.contentprovidersample/names/"), new String[]{"name", "_id"}, null, null, "name ASC"); mAdapter.swapCursor(cursor); editText.setText(""); } }); getContentResolver(). registerContentObserver( Uri.parse("content://com.androidsample.contentprovidersample/names/"), true, new MyObserver()); mAdapter = new SimpleCursorAdapter(MainActivity.this, android.R.layout.simple_expandable_list_item_1, contentResolver.query(Uri.parse("content://com.androidsample.contentprovidersample/names/"), new String[]{"name", "_id"}, null, null, "name ASC"), new String[]{"name"}, new int[]{android.R.id.text1}); listView.setAdapter(mAdapter); } class MyObserver extends ContentObserver { MyObserver() { super(new Handler()); } @Override public void onChange(boolean selfChange) { this.onChange(selfChange, null); mAdapter.notifyDataSetChanged(); } @Override public void onChange(boolean selfChange, Uri uri) { } } }
package ch.erp.management.mvp.utils.General; /** * 字符串常量实体类 * * @author ChenHong */ public class MConstStr { /*MSharedPreferencesUtils文件名*/public static final String M_ERP_FINLENAME = "m_erp_filename"; /* 网络请求格式 */public static final String M_CHARSET = "UTF-8"; /* 登录人ID标识 */public static final String M_USERID = "userid"; /* 用户名标识 */public static final String M_USERNAME = "name"; /* 密码标识 */public static final String M_PASSWORD = "password"; /* 是否注销 */public static final String M_LOGOUT = "islogout"; /* 裁剪头像 */public static final int CLIP_TOU_XIANG_RESULT = 0x17; /* 头像字符串 */public static final String M_PHOTOSTR_MARK = "mphotostrmark"; }
package com.lenovohit.ssm.treat.web.rest; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import com.lenovohit.core.dao.Page; import com.lenovohit.core.web.MediaTypes; import com.lenovohit.core.web.rest.BaseRestController; import com.lenovohit.core.web.utils.Result; import com.lenovohit.core.web.utils.ResultUtils; import com.lenovohit.ssm.SSMConstants; import com.lenovohit.ssm.treat.manager.HisAssayManager; import com.lenovohit.ssm.treat.model.AssayItem; import com.lenovohit.ssm.treat.model.AssayRecord; import com.lenovohit.ssm.treat.model.Patient; /** * 化验单 */ @RestController @RequestMapping("/ssm/treat/assay") public class AssayRestController extends BaseRestController { @Autowired private HisAssayManager hisAssayManager; /** * 化验单列表 * @param start * @param limit * @return */ @RequestMapping(value="/page/{start}/{limit}",method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result forPage(@PathVariable("start") String start, @PathVariable("limit") String limit){ //获取当前患者 Patient patient = this.getCurrentPatient(); List<AssayRecord> assayRecord = hisAssayManager.getAssayRecordPage(patient); Page page = new Page(); page.setStart(start); page.setPageSize(limit); //page.setQuery("from AssayRecord where 1=1 order by sort"); page.setTotal(assayRecord==null?0:assayRecord.size()); page.setResult(assayRecord); return ResultUtils.renderSuccessResult(page); } /** * 化验单详情 * @param id * @return */ @RequestMapping(value="/{id}",method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result forInfo(@PathVariable("id") String id){ List<AssayItem> assayItem = hisAssayManager.getAssayItem(id); return ResultUtils.renderSuccessResult(assayItem); } /** * 打印结果回传 * @param id * @return */ @RequestMapping(value="/printed/{id}",method = RequestMethod.PUT, produces = MediaTypes.JSON_UTF_8) public Result forPrint(@PathVariable("id") String id){ AssayRecord assayRecord = new AssayRecord(); assayRecord = hisAssayManager.print(assayRecord); return ResultUtils.renderSuccessResult(); } private Patient getCurrentPatient(){ // 获取当前患者 Patient patient = (Patient)this.getSession().getAttribute(SSMConstants.SSM_PATIENT_KEY); if(patient == null ){//TODO 生产时修改 //patient = hisPatientManager.getPatientByHisID(""); //TODO 异常,找不到当前患者 未登录 } return patient; } }
// MainGame.java // Armaan Randhawa and Shivan Gaur // Class that creates the JFrame and sets up all Main Classes/Panels import javax.imageio.ImageIO; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.File; import java.io.IOException; public class MainGame extends JFrame { // Declaring constants public static final String GAMEPANEL = "game"; public static final String MENUPANEL = "menu"; public static final String SHOPPANEL = "shop"; public static final String TRANSITIONPANEL = "transition"; public static final String ENDPANEL = "ending"; // Declaring fields private GamePanel game; private MainMenu menu; private ShopPanel shop; private TransitionPanel transition; private EndingPanel ending; private JPanel panelManager; private String activePanel; private Timer myTimer; // Timer to call the game functions each frame private int runTime; // Variable to keep track of the milliseconds that have passed since the start of the game public MainGame() throws IOException { super("Quest of Embers"); // Setting the title // Initalizing Main Classes Button.init(); // Creating the JPanels for the game game = new GamePanel(this); menu = new MainMenu(this); shop = new ShopPanel(this); transition = new TransitionPanel(this); ending = new EndingPanel(this); panelManager = new JPanel(new CardLayout()); // Setting up the CardLayout in panelManager panelManager.add(game, GAMEPANEL); panelManager.add(menu, MENUPANEL); panelManager.add(shop, SHOPPANEL); panelManager.add(transition, TRANSITIONPANEL); panelManager.add(ending, ENDPANEL); switchPanel(MENUPANEL); // Creating the JFrame and JPanels setSize(960,590); setResizable(false); setLocationRelativeTo(null); add(panelManager); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Image icon = ImageIO.read(new File("Assets/Images/Chests/chestOpen.png")); setIconImage(icon); setVisible(true); // Starting a timer to update the frames myTimer = new Timer(10, new TickListener()); // trigger every 10 ms myTimer.start(); // Running panel setups menu.init(); shop.init(); } // Method to switch the current panel on screen public void switchPanel(String targetPanel){ CardLayout cardLayout = (CardLayout) panelManager.getLayout(); cardLayout.show(panelManager, targetPanel); activePanel = targetPanel; addNotify(); // Getting the focus of the current panel } // TickListener Class class TickListener implements ActionListener { public void actionPerformed(ActionEvent evt){ // Switch case to run the proper game loop switch(activePanel){ case GAMEPANEL: if(!game.isPaused()){ // Main game loop game.checkInputs(); game.update(); game.checkCollision(); game.updateGraphics(); game.repaint(); // Counter to keep track of time elapsed runTime += 10; // The main game loop is called every 10ms if(runTime == 1000){ // If 1 second has passed runTime = 0; game.iterateTime(); } } break; case MENUPANEL: menu.update(); menu.checkButtons(); menu.repaint(); break; case SHOPPANEL: shop.update(); shop.checkButtons(); shop.repaint(); break; case TRANSITIONPANEL: transition.update(); transition.repaint(); break; case ENDPANEL: ending.update(); ending.updateStats(); ending.repaint(); break; } } } public GamePanel getGame(){ return game; } public static void main(String[] args) throws IOException{ System.setProperty("sun.java2d.opengl", "true"); MainGame game = new MainGame(); } }
package util; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; public enum FileUtil { I; public void safeFile(final String fileName, final File srcFile) { try { final OutputStream oos = new FileOutputStream(fileName); final byte[] buf = new byte[8192]; final InputStream is = new FileInputStream(srcFile); int c = 0; while ((c = is.read(buf, 0, buf.length)) > 0) { oos.write(buf, 0, c); oos.flush(); } oos.close(); System.out.println("stop"); is.close(); } catch (final FileNotFoundException e) { e.printStackTrace(); } catch (final IOException e) { e.printStackTrace(); } } }
package com.gmail.raynlegends.adventofcode.puzzles; import java.security.MessageDigest; import com.gmail.raynlegends.adventofcode.Puzzle; public class _04_2_Puzzle implements Puzzle { @Override public String calculate(String input) { try { MessageDigest md = MessageDigest.getInstance("MD5"); int current = 1; byte[] hash; while (true) { hash = md.digest((input + current).getBytes("UTF-8")); StringBuffer result = new StringBuffer(); for (int i = 0; i < hash.length; i++) { if ((0xff & hash[i]) < 0x10) { result.append("0" + Integer.toHexString((0xFF & hash[i]))); } else { result.append(Integer.toHexString(0xFF & hash[i])); } } if (result.toString().startsWith("000000")) { return current + ""; } current++; } } catch (Exception e) { e.printStackTrace(); return e.getMessage(); } } @Override public String toString() { return "Day 4, Part 2"; } }
package mygame; import com.jme3.app.SimpleApplication; import com.jme3.network.Client; import com.jme3.network.ClientStateListener; import com.jme3.network.Message; import com.jme3.network.MessageListener; import com.jme3.network.Network; import com.jme3.renderer.RenderManager; import com.jme3.scene.Node; import com.jme3.scene.Spatial; import com.jme3.system.AppSettings; import com.jme3.terrain.geomipmap.TerrainQuad; import java.io.IOException; import java.util.List; import java.util.logging.Level; import java.util.logging.Logger; import mygame.appstate.RunLevel; import static mygame.appstate.RunLevel.networkedPlayersNode; import static mygame.appstate.RunLevel.queuedPlayerActionMessages; import mygame.control.NetworkPlayableCharacter; import mygame.server.ServerMain; import mygame.server.ServerMain.EntityMessage; import mygame.server.ServerMain.JoinMessage; import mygame.server.ServerMain.PlayerActionMessage; import mygame.server.ServerMain.PlayerLeaveMessage; import mygame.server.ServerMain.PlayerPositionMessage; import mygame.server.ServerMain.ServerMessage; import mygame.server.ServerMain.SyncLevelMessage; public class Main extends SimpleApplication implements ClientStateListener{ public static Main main; public static Client client; public static RunLevel level; Main(){ try { client = Network.connectToServer("Rabi-Bounce-Bounce-Rabi", ServerMain.VERSION, "localhost", 19919, 19919); //client = Network.connectToServer("localhost",19919); client.addMessageListener(new ClientListener(), ServerMessage.class); client.addMessageListener(new ClientListener(), PlayerPositionMessage.class); client.addMessageListener(new ClientListener(), SyncLevelMessage.class); client.addMessageListener(new ClientListener(), EntityMessage.class); client.addMessageListener(new ClientListener(), JoinMessage.class); //client.addMessageListener(new ClientListener(), PlayerJoinMessage.class); client.addMessageListener(new ClientListener(), PlayerActionMessage.class); client.addMessageListener(new ClientListener(), PlayerLeaveMessage.class); client.addClientStateListener(this); client.start(); } catch (IOException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } public static void main(String[] args) { AppSettings settings = new AppSettings(true); settings.setResolution(1600,900); settings.setVSync(true); settings.setFrameRate(120); Main app = new Main(); app.setSettings(settings); main = app; app.setPauseOnLostFocus(false); app.start(); } @Override public void simpleInitApp() { flyCam.setEnabled(false); //flyCam.setMoveSpeed(50); level = new RunLevel("TestLevel"); stateManager.attach(level); //stateManager.detach(level); } @Override public void simpleUpdate(float tpf) { } @Override public void simpleRender(RenderManager rm) { //TODO: add render code } @Override public void clientConnected(Client c) { System.out.println("Client successfully connected!"); } @Override public void clientDisconnected(Client c, DisconnectInfo info) { System.out.println("Client disconnected. Reason:"+((info!=null)?info.reason+". Error: "+info.error.getMessage():"Leave")); } public class ClientListener implements MessageListener<Client> { public void messageReceived(Client source, Message message) { if (message instanceof ServerMessage) { System.out.println("Client #"+source.getId()+" received: "+message); } else if (message instanceof PlayerPositionMessage) { System.out.println("Client #"+source.getId()+" position updated: "+message); } else if (message instanceof SyncLevelMessage) { level.getSyncLevelMessage((SyncLevelMessage)message); } else /*if (message instanceof PlayerJoinMessage) { level.getPlayerJoinMessage((PlayerJoinMessage)message); } else*/ if (message instanceof PlayerActionMessage) { level.getPlayerActionMessage((PlayerActionMessage)message); } else if (message instanceof JoinMessage) { level.getPlayerJoinMessage((JoinMessage)message); } else if (message instanceof PlayerLeaveMessage) { level.getPlayerLeaveMessage((PlayerLeaveMessage)message); } } } public static TerrainQuad SearchForTerrain(Node node) { for (Spatial s : node.getChildren()) { if (s instanceof TerrainQuad) { return (TerrainQuad)s; } else { Node n = (Node)s; return SearchForTerrain(n); } } return null; } @Override public void destroy() { client.close(); super.destroy(); } }
package com.uniinfo.cloudplat.eo; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Id; import javax.persistence.Table; /** * MagAccountMain entity. @author hongzhou.yi */ @Entity @Table(name = "mag_account_main") public class MagAccountMainEO implements java.io.Serializable { private static final long serialVersionUID = 1L; // Fields private String userId; private String email; private String mobileNo; private String password; private String realName; private Date createTime; private String userState; private String remark; // Constructors /** default constructor */ public MagAccountMainEO() { } /** minimal constructor */ public MagAccountMainEO(String userId) { this.userId = userId; } /** full constructor */ public MagAccountMainEO(String userId, String email, String mobileNo, String password, String realName, Date createTime, String userState, String remark) { this.userId = userId; this.email = email; this.mobileNo = mobileNo; this.password = password; this.realName = realName; this.createTime = createTime; this.userState = userState; this.remark = remark; } // Property accessors @Id @Column(name = "USER_ID", unique = true, nullable = false) public String getUserId() { return this.userId; } public void setUserId(String userId) { this.userId = userId; } @Column(name = "EMAIL") public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; } @Column(name = "MOBILE_NO") public String getMobileNo() { return this.mobileNo; } public void setMobileNo(String mobileNo) { this.mobileNo = mobileNo; } @Column(name = "PASSWORD") public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } @Column(name = "REAL_NAME") public String getRealName() { return this.realName; } public void setRealName(String realName) { this.realName = realName; } @Column(name = "CREATE_TIME") public Date getCreateTime() { return this.createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } @Column(name = "USER_STATE") public String getUserState() { return this.userState; } public void setUserState(String userState) { this.userState = userState; } @Column(name = "REMARK") public String getRemark() { return this.remark; } public void setRemark(String remark) { this.remark = remark; } }
package org.giddap.dreamfactory.leetcode.onlinejudge.implementations; import org.giddap.dreamfactory.leetcode.onlinejudge.DistinctSubsequences; /** * <ul> * <li>Time: O(i*j); Space: O(i*j)</li> * </ul> * In the above algorithm, in its i-th iteration, it only needs results in * (i-1)-th iteration. More specifically, it only needs table[i-1][j] and * table[i][j-1]. So, we can use one row, i.e. O(j) space, rather than a 2D table, * i.e. O(i*j) space. * <p> * When we use an 1-dimensional array, at the beginning of i-th iteration, * recurs[j] means the number of recurrences of T(0:j) in S(0:i-1) and it can be * updated as recurs[j]+=recurs[j-1] if the current character matches. * <p> * In i-th iteration,<br/> * at the beginning, recurs[j] = the number of distinct subsequences of T[0,j] * in S[0,i-1];<br/> * after being updated, recurs[i] = the number of distinct subsequences of T[0,j] * in S[0,i]. * <p> * We have to run from T.length down to 0 since we don't want to overwrite * recurs[j] which would be used for recurs[j+1] later. */ public class DistinctSubsequencesDpWith1DArrayImpl implements DistinctSubsequences { @Override public int numDistinct(String S, String T) { int si = S.length(), ti = T.length(); if (si <= 0 || ti <= 0 || si < ti) return 0; int[] recurs = new int[ti]; for (int i = 0; i < si; ++i) { for (int j = Math.min(i, ti - 1); j >= 0; --j) { if (S.charAt(i) == T.charAt(j)) { recurs[j] += (j == 0) ? 1 : recurs[j - 1]; } } } return recurs[ti - 1]; } }
import java.util.LinkedList; /** NNeq.java * * Author: Greg Choice c9311718@uon.edu.au * * Created: * Updated: 28/09/2018 * * Description: * STNode sub-class for NNEQ rule * */ public class NNeq extends STNode { public NNeq(LinkedList<Token> tokenList, SymbolTable table) { super(NID.NNEQ); setRight(processExpression(tokenList, table)); } }
package by.client.android.railwayapp; import android.app.Application; /** * Класс инициализации приложения * * @author PRV */ public class AndroidApplication extends Application { private ApplicationComponent applicationComponent; private static AndroidApplication application; @Override public void onCreate() { super.onCreate(); application = this; getApplicationComponent().inject(this); } public static AndroidApplication getApp() { return application; } public ApplicationComponent getApplicationComponent() { if (applicationComponent == null) { applicationComponent = DaggerApplicationComponent.builder() .applicationModule(new ApplicationModule(this)) .applicationCacheModule(new ApplicationCacheModule(this)) .build(); } return applicationComponent; } private void initCrashReporting() { Thread.setDefaultUncaughtExceptionHandler((thread, throwable) -> { }); } }
package com.social.server.dao; import com.social.server.entity.Dialog; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.stereotype.Repository; import java.util.Set; @Repository public interface DialogRepository extends JpaRepository<Dialog, Long> { Page<Dialog> findByUsersIdInOrderByDateLastMessageDesc(long rootUserId, Pageable page); @Query("select d from Dialog d join d.users as u where u.id in (:users) group by d.id having count(d) = 2") Dialog findOneByUsersId(Set<Long> users); }
package com.gaoshin.sorma.examples.addressbook; import com.gaoshin.sorma.annotation.Table; @Table( name = "email", // table name keyColumn = "id", // primary key column name autoId = true, // is primary key autoincrement? create = { "create table if not exists email (" + " id INTEGER primary key autoincrement" + ", contactId INTEGER " + ", email text" + ")", }) public class Email { private Integer id; private Integer contactId; private String email; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getContactId() { return contactId; } public void setContactId(Integer contactId) { this.contactId = contactId; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
package com.kbi.qwertech.client; import com.kbi.qwertech.api.armor.IArmorStats; import com.kbi.qwertech.api.armor.MultiItemArmor; import com.kbi.qwertech.api.data.QTConfigs; import com.kbi.qwertech.armor.ArmorIcon; import com.kbi.qwertech.client.gui.GuiSplat; import com.kbi.qwertech.loaders.RegisterArmor; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import gregapi.oredict.OreDictMaterial; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.entity.RenderItem; import net.minecraft.client.renderer.texture.TextureMap; import net.minecraft.item.ItemArmor; import net.minecraft.item.ItemStack; import net.minecraftforge.client.event.RenderGameOverlayEvent; import net.minecraftforge.client.event.RenderGameOverlayEvent.ElementType; import org.lwjgl.opengl.GL11; public class QT_GUIHandler { public static int[] splats; public static short[][] colors; public QT_GUIHandler() { QT_GUIHandler.splats = new int[8]; QT_GUIHandler.colors = new short[][]{{255, 255, 255, 255}, {255, 255, 255, 255}, {255, 255, 255, 255}, {255, 255, 255, 255}, {255, 255, 255, 255}, {255, 255, 255, 255}, {255, 255, 255, 255}, {255, 255, 255, 255}}; } @SubscribeEvent public void onRendertext(RenderGameOverlayEvent.Text event) { Minecraft minecraft = Minecraft.getMinecraft(); if (QTConfigs.enableArmor && event.type == ElementType.TEXT) { //event.setCanceled(true); GL11.glEnable(GL11.GL_ALPHA_TEST); double weight = 0; double protec = 100; for (int i = 0; i < 4; i++) { ItemStack armorSlot = minecraft.thePlayer.getCurrentArmor(i); if (armorSlot != null) { if (armorSlot.getItem() instanceof MultiItemArmor) { IArmorStats tStats = ((MultiItemArmor)armorSlot.getItem()).getArmorStats(armorSlot); if (tStats != null) { OreDictMaterial mat = MultiItemArmor.getPrimaryMaterial(armorSlot); weight = weight + mat.getWeight(tStats.getMaterialAmount()/500); protec = protec * tStats.getDamageProtection(); } } else if (armorSlot.getItem() instanceof ItemArmor) { ItemArmor armor = (ItemArmor)armorSlot.getItem(); int reduction = armor.damageReduceAmount * 4; protec = protec - (reduction); weight = weight + (reduction * 0.66); } } } int x = (event.resolution.getScaledWidth() / 2) - 91; int y = (event.resolution.getScaledHeight()) - 48; protec = 100 - protec; GL11.glColor4f(1, 1, 1, 1); String protect = protec < 1? "noShield" : protec < 16 ? "woodShield" : protec < 33 ? "bronzeShield" : protec < 50 ? "blueMetalShield" : "purpleShield"; minecraft.renderEngine.bindTexture(TextureMap.locationItemsTexture); RenderItem.getInstance().renderIcon(x, y - 12, ((ArmorIcon)RegisterArmor.iconTitle.get(protect)).getIcon(0), 16, 16); String weighty = weight < 1 ? "weightNone" : weight < 20 ? "weightLight" : weight < 40 ? "weightLittle" : weight < 70 ? "weightSignificant" : "weightMuch"; RenderItem.getInstance().renderIcon(x + 26, y - 12, ((ArmorIcon)RegisterArmor.iconTitle.get(weighty)).getIcon(0), 16, 16); if (protec > 0) { minecraft.fontRenderer.drawString((int)(protec) + "%", x + 18 - (minecraft.fontRenderer.getStringWidth((int)(protec) + "%")), y, 16777215, true); } if (weight > 0) { String drawit = (int)weight + "kg"; minecraft.fontRenderer.drawString(drawit, x + 46 - (minecraft.fontRenderer.getStringWidth(drawit)), y, 16777215, true); } } } @SubscribeEvent public void onRendergui(RenderGameOverlayEvent.Pre event) { if (QTConfigs.enableArmor && event.type == ElementType.ARMOR) { event.setCanceled(true); } } @SubscribeEvent public void onRenderGui(RenderGameOverlayEvent.Post event) { Minecraft minecraft = Minecraft.getMinecraft(); if (event.type != ElementType.EXPERIENCE) return; for (int q = 0; q < 8; q++) { if (splats[q] != 0) { if (minecraft.thePlayer.ticksExisted > splats[q] + 60) { //System.out.println("Old splat resetting"); splats[q] = 0; } else { new GuiSplat(Minecraft.getMinecraft(), splats[q], minecraft.thePlayer.ticksExisted, colors[q]); } } } } public static void addNewSplat(short[] color) { //System.out.println("Splat adding"); int minimum = splats[0]; int pos = 0; for (int q = 0; q < 8; q++) { if (splats[q] < minimum) { minimum = splats[q]; pos = q; } } splats[pos] = Minecraft.getMinecraft().thePlayer.ticksExisted; colors[pos] = color; } }
package ru.ifmo.diploma.synchronizer.protocol.handshake; import java.io.Serializable; /** * Created by ksenia on 25.05.2017. */ public abstract class HandshakeMessage implements Serializable { private String fromAddr; public HandshakeMessage(String fromAddr) { this.fromAddr = fromAddr; } public String getFromAddr() { return fromAddr; } }
package com.aaron.mvpsample.model; import android.content.Context; public interface IMainModel { void save(Context context, String data); void load(Context context, RequestListener listener); void clearData(Context context); }
package com.stocktrading.stockquote.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @AllArgsConstructor @NoArgsConstructor public class ClientChangeModel { private String type; private String action; private String clientId; private String correlationId; }
package Recursion; import java.util.Scanner; public class PerfectRec { static boolean isPerfect(int n, int i, int sum){ if(i>n/2) return sum==n; if(n%i==0) sum= sum+i; return isPerfect(n, i+1, sum); } public static void main(String[] args) { Scanner in = new Scanner(System.in); System.out.println("Enter the value of n: "); int n = in.nextInt(); boolean res = isPerfect(n, 1, 0); if(res == true) System.out.println(n+" is a perfect Number"); else System.out.println(n+" is not a perfect number"); in.close(); } }
package com.demo.nestedscroll_demo.utils; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.demo.nestedscroll_demo.adapter.BaseRecyclerAdapter; import com.demo.nestedscroll_demo.adapter.OnRecyclerViewItemClickListener; import com.demo.nestedscroll_demo.adapter.OnRecyclerViewItemLongClickListener; /** * RecyclerView帮助类 * Created by lishilin on 2016/11/4. */ public class RecyclerViewHelper { private static class HelperHolder { private static final RecyclerViewHelper instance = new RecyclerViewHelper(); } public static RecyclerViewHelper getInstance() { return HelperHolder.instance; } private RecyclerViewHelper() { super(); } /** * 滚动RecyclerView到顶部 * * @param recyclerView recyclerView */ public void scrollToTop(RecyclerView recyclerView) { scrollToPositionByLayoutManager(recyclerView, 0); } /** * 滚动RecyclerView到底部 * * @param recyclerView recyclerView */ public void scrollToBottom(RecyclerView recyclerView) { RecyclerView.Adapter adapter = recyclerView.getAdapter(); int position = 0; if (adapter != null) { int count = adapter.getItemCount(); position = count - 1; } scrollToPositionByLayoutManager(recyclerView, position); } /** * 滚动RecyclerView到指定位置(通过RecyclerView自身,如果position在屏幕可见范围内,则不会滚动,即不会置顶position) * * @param recyclerView recyclerView * @param position position */ public void scrollToPosition(RecyclerView recyclerView, int position) { recyclerView.scrollToPosition(position); } /** * 滚动RecyclerView到指定位置(通过LayoutManager,会把position置顶) * RecyclerView 自身scrollToPosition方法定位不会置顶,所以使用LinearLayoutManager中的定位方法 * * @param recyclerView recyclerView * @param position position */ public void scrollToPositionByLayoutManager(RecyclerView recyclerView, int position) { RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager(); if (layoutManager instanceof LinearLayoutManager) { LinearLayoutManager linearLayoutManager = (LinearLayoutManager) layoutManager; linearLayoutManager.scrollToPositionWithOffset(position, 0); } else { scrollToPosition(recyclerView, position); } } /** * 设置点击监听 * * @param adapter adapter * @param onItemClickListener 单击监听回调 */ public void setItemClickListener(BaseRecyclerAdapter adapter, OnRecyclerViewItemClickListener onItemClickListener) { adapter.setOnItemClickListener(onItemClickListener); } /** * 设置点击监听 * * @param adapter adapter * @param onItemLongClickListener 长按监听回调 */ public void setItemLongClickListener(BaseRecyclerAdapter adapter, final OnRecyclerViewItemLongClickListener onItemLongClickListener) { OnRecyclerViewItemLongClickListener onItemLongClickListenerTemp = null; if (onItemLongClickListener != null) { onItemLongClickListenerTemp = new OnRecyclerViewItemLongClickListener() { @Override public boolean onItemLongClick(RecyclerView.ViewHolder holder) { return onItemLongClickListener.onItemLongClick(holder); } }; } adapter.setOnItemLongClickListener(onItemLongClickListenerTemp); } /** * 设置点击监听 * * @param recyclerView RecyclerView * @param onItemClickListener 单击监听回调 */ public void setItemClickListener(RecyclerView recyclerView, OnRecyclerViewItemClickListener onItemClickListener) { RecyclerView.Adapter adapter = recyclerView.getAdapter(); if (adapter instanceof BaseRecyclerAdapter) { setItemClickListener((BaseRecyclerAdapter) adapter, onItemClickListener); } // OnRecyclerViewItemTouchListener onRecyclerItemTouchListener = new OnRecyclerViewItemTouchListener(recyclerView); // onRecyclerItemTouchListener.setOnItemClickListener(onItemClickListener); // recyclerView.addOnItemTouchListener(onRecyclerItemTouchListener); } /** * 设置点击监听 * * @param recyclerView RecyclerView * @param onItemLongClickListener 长按监听回调 */ public void setItemLongClickListener(RecyclerView recyclerView, final OnRecyclerViewItemLongClickListener onItemLongClickListener) { RecyclerView.Adapter adapter = recyclerView.getAdapter(); if (adapter instanceof BaseRecyclerAdapter) { setItemLongClickListener((BaseRecyclerAdapter) adapter, onItemLongClickListener); } // OnRecyclerViewItemLongClickListener onItemLongClickListenerTemp = null; // if (onItemLongClickListener != null) { // onItemLongClickListenerTemp = new OnRecyclerViewItemLongClickListener() { // @Override // public boolean onItemLongClick(RecyclerView.ViewHolder holder) { // VibratorHelper.getInstance().vibrate(); // return onItemLongClickListener.onItemLongClick(holder); // } // }; // } // // OnRecyclerViewItemTouchListener onRecyclerItemTouchListener = new OnRecyclerViewItemTouchListener(recyclerView); // onRecyclerItemTouchListener.setOnItemLongClickListener(onItemLongClickListenerTemp); // recyclerView.addOnItemTouchListener(onRecyclerItemTouchListener); } }
package com.example.priceapp.model; import com.sun.istack.NotNull; import javax.persistence.*; @Entity @Table(name="BRANDS") public class Brand { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotNull @Column(name="NAME") private String name; public Brand() { } public Brand(Long id, String name) { this.id = id; this.name = name; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package game; import java.awt.Color; import java.awt.Graphics2D; import java.awt.event.KeyEvent; import java.awt.Font; import java.awt.FontMetrics; import java.io.File; /** * * @author Nitro */ public class StateRoam extends GameState{ private EnemyManager enemyMgr; private RibbonsManager ribsMan; private BricksManager bricksMan; private Player strider; //private TestEnemy testE; private boolean bDrawColBox; private HUD hud; private Font HUDFont;//TODO: remove these when the HUD class is completed private FontMetrics fMetric; int movesize = 5; //TODO: check if we can remove this. private AudioManager audioMgr; public StateRoam(Game game) { super(game); audioMgr = game.getAudioManager(); audioMgr.Insert(new File("forest.wav"), "forest.wav"); bIsEntering = true; ribsMan = game.getRibsMan(); bricksMan = game.getBricksMan(); strider = game.getPlayer(); hud = game.getHUD(); enemyMgr = game.getEnemyMgr(); // testE = (TestEnemy)game.getEnemy(); bDrawColBox = false; HUDFont = new Font("Arial", Font.BOLD, 14); } @Override public void draw() { Graphics2D g2 = (Graphics2D)doublebuf.getDrawGraphics(); ribsMan.display(g2); bricksMan.display(g2); // testE.draw(g2); enemyMgr.draw(g2); strider.draw(g2); hud.draw(g2); g2.setColor(Color.white); if(bDrawColBox){ // g2.draw(testE.getColBox());//for debug enemyMgr.drawDebug(g2); g2.draw(strider.getColBox());//for debug if(strider.getAtkRect()!=null) g2.draw(strider.getAtkRect()); } // g2.setFont(HUDFont); // g2.getFontMetrics(HUDFont); // g2.drawString("HP: "+strider.getHP(), 15, 40); doublebuf.show(); g2.dispose(); } @Override public void update() { handleInput(); if(bIsEntering) { audioMgr.playAudio("forest.wav", true); bIsEntering = false; } ribsMan.update(); bricksMan.update(); strider.update(); // testE.update(); enemyMgr.update(); } private void handleInput() { if(inputMan.isKeyDown(KeyEvent.VK_A)) { strider.moveLeft(); } else if(inputMan.isKeyDown(KeyEvent.VK_D)) { strider.moveRight(); } if(inputMan.isInitPressed(KeyEvent.VK_B)){ bDrawColBox=!bDrawColBox; } if(inputMan.isInitPressed(KeyEvent.VK_W)) { strider.jump(); } if(inputMan.isInitPressed(KeyEvent.VK_SPACE)){ strider.attack(); } if(inputMan.isInitPressed(KeyEvent.VK_G)) { if(enemiesInRange()) game.setCurrentState("geotime"); } if(inputMan.isInitPressed(KeyEvent.VK_M)) { strider.setMaxXVel(8); strider.setXAccel(1.0f); strider.setAttackVal(400); } if(inputMan.isKeyDown(KeyEvent.VK_S)) { game.setUPDATE_SPEED(game.getUPDATE_SPEED()+10); } else game.setUPDATE_SPEED(25); } private boolean enemiesInRange() { return (enemyMgr.getNumActive() > 0); } }
package core.client.game.listener.skills; import core.client.GamePanel; import core.client.game.event.DealClientGameEvent; import core.client.game.operations.skills.SuddenStrikeSkillOperation; import ui.game.interfaces.SkillUI; public class SuddenStrikeSkillDealEventListener extends AbstractActiveSkillClientEventListener<DealClientGameEvent> { public SuddenStrikeSkillDealEventListener(SkillUI skill) { super(skill); } @Override public Class<DealClientGameEvent> getEventClass() { return DealClientGameEvent.class; } @Override public void handleOnLoaded(DealClientGameEvent event, GamePanel panel) { this.skill.setActionOnActivation(() -> { panel.pushOperation(new SuddenStrikeSkillOperation(this.skill)); }); this.skill.setActivatable(true); } }
package com.fumei.bg.mapper.system; import com.fumei.bg.domain.system.SysDictType; import java.util.List; /** * @author zkh */ public interface SysDictTypeMapper { /** * 根据条件查询字典类型列表 * * @param dictType 条件 * @return 字典类型列表 */ List<SysDictType> selectDictTypeList(SysDictType dictType); /** * 保存字典类型 * * @param dictType 字典类型 * @return 执行结果 1成功 0失败 */ int insert(SysDictType dictType); /** * 修改字典类型 * @param dictType 字典类型 * @return 执行结果 1成功 0失败 */ int update(SysDictType dictType); /** * 删除字典类型 * @param dictId 字典id * @return 执行结果 1成功 0失败 */ int delete(Long dictId); /** * 根据id获取字典类型 * * @param dictId 字典id * @return 字典类型 */ SysDictType selectDictByPrimaryKey(Long dictId); }
package com.soa.repository; import com.soa.domain.hero.Elf; import com.soa.repository.def.HeroRepository; import javax.ejb.LocalBean; import javax.ejb.Stateless; import static com.soa.domain.hero.Elf.REACHEST_ELF_QUERY_NAME; @Stateless @LocalBean public class ElfRepository extends HeroRepository<Elf> { protected ElfRepository() { super(Elf.class); } @Override public Elf findReachest() { return (Elf) entityManager.createNamedQuery(REACHEST_ELF_QUERY_NAME).getResultList().get(0); } }
import java.util.ArrayList; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.StampedLock; public class Producer implements Runnable{ private Condition stackEmptyCondition; private ArrayList<String> stack; private Integer size; private ReentrantLock lock; private Condition stackFullCondition; public Producer(ArrayList<String> stack, Integer size, ReentrantLock lock,Condition stackFullCondition,Condition stackEmptyCondition){ this.size = size; this.stack= stack; this.lock = lock; this.stackFullCondition= stackFullCondition; this.stackEmptyCondition = stackEmptyCondition; } @Override public void run() { //produce messages Integer i = 0; while (true) { try { lock.lock(); while (stack.size() > size) { System.out.println("Producer stopped producing"); stackFullCondition.await(); System.out.println("Producer started producing"); } String msg = "message " + i.toString(); i++; stack.add(msg); System.out.println("Produced " + msg + " on spot: " + (stack.size()-1)); stackEmptyCondition.signalAll(); Thread.sleep(50); } catch(Exception e){ System.out.println("Catch"+e); } }}}
/* COPYRIGHT NOTICE Copyright 2017 Intellect Design Arena Limited. All rights reserved. These materials are confidential and proprietary to Intellect Design Arena Limited and no part of these materials should be reproduced, published, transmitted or distributed in any form or by any means, electronic, mechanical, photocopying, recording or otherwise, or stored in any information storage or retrieval system of any nature nor should the materials be disclosed to third parties or used in any other manner for which this is not authorized, without the prior express written authorization of Intellect Design Arena Limited. */ /******************************************************************************************* * * Module Name : PaymentsValidation * * File Name : PaymentProduct.java * * Description : ************************ * * Version Control Block * * Date Version Author Description * --------- -------- --------------- --------------------------- * 22-June-2017 0.1 Kiran Barik First version *******************************************************************************************/ package com.intellect.igtb.ipsh.api.model; import java.io.Serializable; public class PaymentProduct implements Serializable { private static final long serialVersionUID = 1L; private String paymentType = null; private String productName = null; public String getPaymentType() { return paymentType; } public void setPaymentType(String paymentType) { this.paymentType = paymentType; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } }
package com.zantong.mobilecttx.common.activity; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.webkit.WebView; import android.webkit.WebViewClient; import android.widget.TextView; import com.zantong.mobilecttx.R; import com.zantong.mobilecttx.base.activity.BaseActivity; import com.zantong.mobilecttx.common.PublicData; import com.zantong.mobilecttx.huodong.activity.HundredAgreementActivity; import com.zantong.mobilecttx.huodong.activity.HundredRuleActivity; import com.zantong.mobilecttx.interf.InterfaceForJS; import com.zantong.mobilecttx.user.activity.LoginActivity; import com.zantong.mobilecttx.utils.UiHelpers; import com.zantong.mobilecttx.utils.jumptools.Act; import com.zantong.mobilecttx.widght.ProgressWebView; import butterknife.Bind; import butterknife.OnClick; import cn.qqtheme.framework.util.ToastUtils; /** * 公用浏览器 * Created by zhengyingbing on 16/9/8. */ public class BrowserActivity extends BaseActivity { public boolean mStatusBarHeight = true; protected String strTitle; protected String strUrl; @Bind(R.id.common_browser_webview) ProgressWebView mWebView; @Bind(R.id.common_browser_title) TextView mTitle; @Bind(R.id.common_browser_back) TextView mBack; @Bind(R.id.common_finish) TextView mFinish; @Bind(R.id.common_browser_right) TextView mRightBtn; //浏览器右上角菜单的状态 0:活动说明 1:活动规则 private int mRightBtnStatus = -1; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setStatusBarSpace(); mFinish.setVisibility(View.GONE); } protected int getLayoutResId() { return R.layout.activity_browser; } @Override public void initView() { // 初始化返回按钮图片大小 UiHelpers.setTextViewIcon(this, mBack, R.mipmap.back_btn_image, R.dimen.ds_24, R.dimen.ds_51, UiHelpers.DRAWABLE_LEFT); strTitle = PublicData.getInstance().webviewTitle; strUrl = PublicData.getInstance().webviewUrl; if (!TextUtils.isEmpty(strTitle)) { mTitle.setText(strTitle); } mWebView.setWebViewClient(new MyWebViewClient()); mWebView.addJavascriptInterface(new InterfaceForJS(this), "CTTX"); } private void setStatusBarSpace() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { View statusBar = findViewById(R.id.activity_browser_title); if (mStatusBarHeight) { statusBar.setPadding(0, tintManager.getConfig().getStatusBarHeight(), 0, 0); } } } @Override public void initData() { if (!TextUtils.isEmpty(strUrl)) { mWebView.loadUrl(strUrl); } } @OnClick({R.id.common_browser_back, R.id.common_finish, R.id.common_browser_right}) @Override public void onClick(View v) { switch (v.getId()) { case R.id.common_browser_back: if (mWebView.canGoBack()) { mWebView.goBack();// 返回前一个页面 mFinish.setVisibility(View.VISIBLE); } else { finish(); } break; case R.id.common_finish: finish(); break; case R.id.common_browser_right: switch (mRightBtnStatus) { case 0: Act.getInstance().gotoIntent(this, HundredAgreementActivity.class); break; case 1: Act.getInstance().gotoIntent(this, HundredRuleActivity.class); break; } break; default: break; } } class MyWebViewClient extends WebViewClient { // 重写shouldOverrideUrlLoading方法,使点击链接后不使用其他的浏览器打开。 @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { if (url.startsWith("tel:")) { startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url))); } else if (url.startsWith("alipays:")) {//阿里支付 Intent intent = new Intent(); intent.setData(Uri.parse(url)); try { startActivity(intent); } catch (Exception e) { e.printStackTrace(); ToastUtils.toastShort("请确认手机安装支付宝app"); } } else { if (PublicData.getInstance().isCheckLogin && !PublicData.getInstance().loginFlag) { startActivity(new Intent(BrowserActivity.this, LoginActivity.class)); } else { view.loadUrl(url); } } // 如果不需要其他对点击链接事件的处理返回true,否则返回false return true; } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); if (url.contains("detail")) { mRightBtnStatus = 1; mRightBtn.setVisibility(View.VISIBLE); mRightBtn.setText("积分规则"); mTitle.setText("积分明细"); } else if (url.contains("index")) { mRightBtnStatus = 0; mRightBtn.setVisibility(View.VISIBLE); mRightBtn.setText("活动说明"); mTitle.setText("百日无违章"); } else { mRightBtn.setVisibility(View.GONE); mTitle.setText(strTitle); } } } @Override protected void onDestroy() { super.onDestroy(); mWebView.destroyWebview(); } }
package fr.sfvl.sql; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.sql.ResultSet; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import org.apache.commons.lang.StringUtils; import fr.sfvl.sql.Critere.CritereString; public class Sql { static class Into<T> { public Into(Class<T> clazz, Map<String, Method> mappingChamp) { super();; this.clazz = clazz; this.mappingChamp = mappingChamp; } private Map<String, Method> mappingChamp; private Class<T> clazz; private <O> void set(O objet, Method methodGetter, Object valeur) throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { String nomSetter; if (methodGetter.getName().startsWith("get")) { nomSetter = methodGetter.getName().replaceFirst("get", "set"); } else { nomSetter = methodGetter.getName().replaceFirst("is", "set"); } Class<?> returnType = methodGetter.getReturnType(); Method methodSetter = objet.getClass().getMethod(nomSetter, returnType); methodSetter.invoke(objet, valeur); } public T getObjet(ResultSet resultSet) { try { T objet = clazz.getConstructor().newInstance(); for (Map.Entry<String, Method> entry : mappingChamp.entrySet()) { Object valeur = resultSet.getObject(entry.getKey()); set(objet, entry.getValue(), valeur); } return objet; } catch (Exception e) { e.printStackTrace(); return null; } } } private List<String> listeChamp = new ArrayList<String>(); private String table; private String join = ""; private Critere clauseWhere; private ArrayList<Object> listeParameters = new ArrayList<Object>(); public static Sql select(String... listeChamp) { Sql sql = new Sql(); sql.listeChamp = new ArrayList<String>(Arrays.asList(listeChamp)); return sql; } public Sql from(String table) { this.table = table; return this; } public String toString() { String sql = "select " + StringUtils.join(listeChamp, ", ") + " from " + table + join; if (clauseWhere != null) { sql += " where " + clauseWhere; } return sql; } public Sql where(String clauseWhere) { return where(new CritereString(clauseWhere)); } public Sql where(Critere clauseWhere) { this.clauseWhere = clauseWhere; return this; } public List<Object> getParameters() { return clauseWhere.getParameters(); } public Sql join(String tableJoin, String champTable, String champTableJoin) { join += " inner join " + tableJoin + " on " + champTable + "=" + champTableJoin; return this; } public Object join(String tableJoin, String champTable) { return join(tableJoin, champTable, champTable); } }
package cn.edu.nju.software.service.impl; import cn.edu.nju.software.dao.RecordStatisticDao; import cn.edu.nju.software.entity.RecordStatistic; import cn.edu.nju.software.service.RecordStatisticService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.Date; /** * Created by xmc1993 on 2017/5/12. */ @Service public class RecordStatisticServiceImpl implements RecordStatisticService { @Autowired private RecordStatisticDao recordStatisticDao; @Override public void saveRecord(int userId) { RecordStatistic statistic = recordStatisticDao.getRecordStatisticByUserId(userId); // 如果没有记录过重新记录生成全新的记录 if (statistic == null) { statistic = new RecordStatistic(); statistic.setUpdateTime(new Date()); statistic.setUserId(userId); statistic.setLastRecordTime(new Date()); statistic.setCurCount(1); statistic.setCreateTime(new Date()); recordStatisticDao.saveRecordStatistic(statistic); } else { //否则更新记录 Date now = new Date(); int diff = differentDaysByMillisecond(now, statistic.getLastRecordTime()); //只有不是同一天的记录才需要更新 if (diff > 0) { if (statistic.getCurCount() > statistic.getHistoryMaxCount()) { statistic.setHistoryMaxCount(statistic.getCurCount()); } statistic.setCurCount(1); statistic.setLastRecordTime(now); statistic.setUpdateTime(now); recordStatisticDao.updateRecordStatistic(statistic); } } } @Override public int getCurCount(int userId) { RecordStatistic statistic = recordStatisticDao.getRecordStatisticByUserId(userId); if (statistic == null) { return 0; } //否则更新记录 Date now = new Date(); int diff = differentDaysByMillisecond(now, statistic.getLastRecordTime()); //只有不是同一天的记录才需要更新 if (diff > 0) { if (statistic.getCurCount() > statistic.getHistoryMaxCount()) { statistic.setHistoryMaxCount(statistic.getCurCount()); } statistic.setCurCount(0); statistic.setLastRecordTime(now); statistic.setUpdateTime(now); recordStatisticDao.updateRecordStatistic(statistic); } return statistic.getCurCount(); } @Override public int getHistoryMaxCount(int userId) { RecordStatistic statistic = recordStatisticDao.getRecordStatisticByUserId(userId); if (statistic == null) { return 0; } else { return statistic.getHistoryMaxCount() > statistic.getCurCount() ? statistic.getHistoryMaxCount() : statistic.getCurCount(); } } private static int differentDaysByMillisecond(Date date1, Date date2) { int days = (int) ((date2.getTime() - date1.getTime()) / (1000 * 3600 * 24)); return days; } }
package com.soft1841.book.dao; import cn.hutool.db.Entity; import com.soft1841.book.entity.Reader; import com.soft1841.book.utils.DAOFactory; import org.junit.Test; import java.sql.SQLException; import java.util.List; import static org.junit.Assert.*; public class ReaderDAOTest { //从工厂中获取到ReaderDAO的实例 private ReaderDAO readerDAO = DAOFactory.getReaderDAOInstance(); @Test public void selectReaders() throws SQLException { List<Reader> readerList = readerDAO.selectReaders(); readerList.forEach(entity -> System.out.println(entity)); } @Test public void deleteById() throws SQLException { readerDAO.deleteById(12); } @Test public void countByRole() throws SQLException { int count = readerDAO.countByRole("学生"); System.out.println(count); } @Test public void countByDepartment() throws SQLException { int count = readerDAO.countByDepartment("计算机与软件学院"); System.out.println(count); } @Test public void countReaders() throws SQLException { int count = readerDAO.countReaders(); System.out.println(count); } }
package com.hhdb.csadmin.plugin.sql_book; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Insets; import javax.swing.BorderFactory; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTextArea; import com.hh.frame.common.enums.DBTypeEnum; import com.hh.frame.common.log.LM; import com.hh.frame.dirobj.DirTool; import com.hh.frame.dirobj.InitTool; import com.hh.frame.dirobj.LinkTool; import com.hh.frame.dirobj.ObjTool; import com.hh.frame.dirobj.bean.DbObjBean; import com.hhdb.csadmin.common.bean.ServerBean; import com.hhdb.csadmin.common.util.HSQL_Util; import com.hhdb.csadmin.plugin.sql_book.attribute.mouse.MouseHandler; import com.hhdb.csadmin.plugin.sql_book.attribute.tree.BaseTreeCellRenderer; import com.hhdb.csadmin.plugin.sql_book.attribute.tree.BaseTreeNode; import com.hhdb.csadmin.plugin.sql_book.bean.MetaTreeNodeBean; import com.hhdb.csadmin.plugin.sql_book.service.SqlOperationService; import com.hhdb.csadmin.plugin.sql_book.ui.BaseTree; import com.hhdb.csadmin.plugin.sql_book.ui.ShortcutPanel; import com.hhdb.csadmin.plugin.sql_book.util.TreeNodeUtil; /** * sql宝典面板 * @author hhxd * */ public class BooksPanel extends JPanel{ private static final long serialVersionUID = 1L; public SqlOperationService sqls; public JScrollPane sqlDetail; public ServerBean svbean; //hsql操作类 public String prefix = "hh_"; //hsql的前缀 public InitTool initTool; public DirTool dirtool; public ObjTool objtool; public LinkTool linkTool; /*** 快捷键源文件id */ public Integer myDirId; /*** 弹出窗 */ public ShortcutPanel shp; /*** 树形图 */ private BaseTree tree; /*** 打开宝典的来源处 true:正常打开 false:从查询器打开。 */ public Boolean source = true; /*** 查询器编辑面板 */ public JTextArea jtext; /*** 查询器传递的sql */ public String sql; /** * * @param hbook * @param bool * 结构树展示功能控制标识 true:为主界面结构树。 false:快捷键地址选择结构树。 * */ public BooksPanel(HSqlBook hbook,Boolean bool) { setLayout(new GridBagLayout()); sqls = new SqlOperationService(hbook, this); svbean = sqls.getServerbean(); BaseTreeNode root = new BaseTreeNode(); init(root); tree = new BaseTree(root); tree.setCellRenderer(new BaseTreeCellRenderer()); //设置数据渲染 tree.addMouseListener(new MouseHandler(tree,this,bool)); //添加鼠标点击事件 // tree.getSelectionModel().setSelectionMode(TreeSelectionModel.DISCONTIGUOUS_TREE_SELECTION); //设置为可以多选 //分隔面板 JSplitPane jsp = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT); jsp.setDividerLocation(0.4); jsp.setBorder(BorderFactory.createEmptyBorder(1, 1, 1, 1)); JScrollPane jp = new JScrollPane(tree); jp.setPreferredSize(new Dimension(300,200)); jsp.setLeftComponent(jp); jsp.setRightComponent(sqlDetail = new JScrollPane()); add(jsp, new GridBagConstraints(0, 1, 1, 1, 1.0, 1.0,GridBagConstraints.NORTH, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); } /** * 初始化 */ public void init(BaseTreeNode root) { try { //获取HSQL的连接 initTool = new InitTool(DBTypeEnum.hsql, prefix); dirtool = new DirTool(DBTypeEnum.hsql, prefix); objtool = new ObjTool(DBTypeEnum.hsql, prefix); linkTool = new LinkTool(DBTypeEnum.hsql, prefix); //创建表 initTool.createAll(HSQL_Util.getConnection()); //初始化根节点 MetaTreeNodeBean tablemtn = new MetaTreeNodeBean(); //判断是否有根节点 DbObjBean dirbean = dirtool.get(HSQL_Util.getConnection(),0); if(null != dirbean ){ tablemtn.setName(dirbean.getName()); tablemtn.setOpenIcon("book.png"); tablemtn.setType(TreeNodeUtil.ROOT_TYPE); tablemtn.setId(dirbean.getId()); }else{ //新建根节点 int dirId = dirtool.createRoot(HSQL_Util.getConnection(),"SQL宝典"); tablemtn.setName("SQL宝典"); tablemtn.setOpenIcon("book.png"); tablemtn.setType(TreeNodeUtil.ROOT_TYPE); tablemtn.setId(dirId); } root.setMetaTreeNodeBean(tablemtn); } catch (Exception e) { LM.error(LM.Model.CS.name(), e); } } public BaseTree getTree() { return tree; } public void setTree(BaseTree tree) { this.tree = tree; } }
package com.green.review; import java.text.DecimalFormat; public class DecimalFormatSimpleDemo { static public void SimgleFormat(String pattern, double value) { DecimalFormat decimalFormat = new DecimalFormat(pattern); String output = decimalFormat.format(value); System.out.println(value + " " + pattern + " " + output); } static public void UseApplyPatternMethodFormat(String pattern, double value) { DecimalFormat decimalFormat = new DecimalFormat(); decimalFormat.applyPattern(pattern); System.out.println(value + " " + pattern + " " + decimalFormat.format(value)); } public static void main(String[] args) { //SimgleFormat SimgleFormat("###,####.##",12345.678); //1,2345.68 SimgleFormat("00000000.###kg",123456.239); //00123456.231kg SimgleFormat("00000.0000",23.3); //00023.3000 //UseApplyPatternMethodFormat UseApplyPatternMethodFormat("#.###%",0.654); //65.4% UseApplyPatternMethodFormat("###.##",1234567.231); //1234567.23 UseApplyPatternMethodFormat("0.00\u2030",0.987); //987.00‰ } }
package tal.com.orders.entities; public enum PaymentMethod { CREDIT(), CHEQUE(), CASH(), TRANSFER(); }
package com.mwe.CustomerService.Controllers; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.CrudRepository; import org.springframework.web.bind.annotation.RequestParam; import com.mwe.CustomerService.Models.Customer; public interface CustomerRepository extends CrudRepository<Customer, Integer> { @Query(value = "Select c.id, c.first_name, c.last_name, c.gender, c.drivers_license FROM Customers c WHERE c.drivers_license = :driversLicense", nativeQuery = true) public Customer findByDriversLicense(@RequestParam("driversLicense") String driversLicense); }
package com.codeclan.foodtrackerapp; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import java.util.ArrayList; public class ViewFoodItemActivity extends AppCompatActivity { public static final String FOODLIST = "foodList"; TextView itemMeal; TextView itemFood; TextView itemDay; TextView itemMonth; FoodItem foodItem; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.view_food_item); Intent intent = getIntent(); Bundle extras = intent.getExtras(); foodItem = (FoodItem)extras.getSerializable("foodItem"); String input_day = foodItem.getDay(); String input_month = foodItem.getMonth(); String input_meal = foodItem.getMeal(); String input_food = foodItem.getFood(); itemDay = (TextView)findViewById(R.id.item_day); itemDay.setText(input_day); itemMonth = (TextView)findViewById(R.id.item_month); itemMonth.setText(input_month); itemMeal = (TextView)findViewById(R.id.item_meal); itemMeal.setText(input_meal); itemFood = (TextView)findViewById(R.id.item_food); itemFood.setText(input_food); } }
package views; import java.awt.BorderLayout; import java.awt.Color; import java.awt.ScrollPane; import java.io.File; import java.util.ArrayList; import java.util.HashSet; import javax.swing.JFrame; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; import javax.swing.JTree; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import controller.Commands; import controller.Controller; import model.Node; public class MainWindow extends JFrame{ /** * */ private static final long serialVersionUID = 1L; private DefaultTreeModel treeModel; private JTree tree; public MainWindow(Controller control) { setExtendedState(MAXIMIZED_BOTH); JMenuBar menuBar = new JMenuBar(); JMenu fileChooser = new JMenu("Open"); JMenuItem file = new JMenuItem("File"); file.setActionCommand(Commands.FILE.toString()); file.addActionListener(control); fileChooser.add(file); menuBar.add(fileChooser); menuBar.setBackground(new Color(13, 0, 108)); fileChooser.setBackground(new Color(13, 0, 108)); file.setBackground(new Color(13, 0, 108)); fileChooser.setForeground(Color.WHITE); file.setForeground(Color.WHITE); add(menuBar, BorderLayout.NORTH); tree = new JTree(); tree.setModel(null); ScrollPane scroll = new ScrollPane(); scroll.add(tree); add(scroll, BorderLayout.CENTER); setDefaultCloseOperation(EXIT_ON_CLOSE); setVisible(true); } public void setData(Node root, ArrayList<String> files, HashSet<String> extensions) { DefaultMutableTreeNode father = new DefaultMutableTreeNode(root.getName()); treeModel = new DefaultTreeModel(father); tree.setModel(treeModel); treeModel.setAsksAllowsChildren(true); int i = 0; for (String extension : extensions) { DefaultMutableTreeNode childs = new DefaultMutableTreeNode(extension); DefaultMutableTreeNode max = new DefaultMutableTreeNode("Menor tamaņo"); DefaultMutableTreeNode min = new DefaultMutableTreeNode("Mayor tamaņo"); treeModel.insertNodeInto(childs, father, i); treeModel.insertNodeInto(min, childs, 0); treeModel.insertNodeInto(max , childs, 1); addFiles(childs,files,extensions, min, max); i++; } } private void addFiles(DefaultMutableTreeNode childs, ArrayList<String> files, HashSet<String> extensions, DefaultMutableTreeNode min, DefaultMutableTreeNode max) { for (String file : files) { if(childs.getUserObject().equals(getFileExtension(new File(file)))) { if(new File(file).length()>(50*1000)) { // treeModel.insertNodeInto(new DefaultMutableTreeNode(file), childs, i); max.add(new DefaultMutableTreeNode(file)); }else { min.add(new DefaultMutableTreeNode(file)); } } } } private String getFileExtension(File file) { String name = file.getName(); try { return name.substring(name.lastIndexOf(".") + 1); } catch (Exception e) { return ""; } } }
/* * @(#)Split.java 1.4 01/03/13 * * Copyright (c) 1999-2001 Sun Microsystems, Inc. All Rights Reserved. * * Sun grants you ("Licensee") a non-exclusive, royalty free, license to use, * modify and redistribute this software in source and binary code form, * provided that i) this copyright notice and license appear on all copies of * the software; and ii) Licensee does not utilize the software in a manner * which is disparaging to Sun. * * This software is provided "AS IS," without a warranty of any kind. ALL * EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES, INCLUDING ANY * IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR * NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND ITS LICENSORS SHALL NOT BE * LIABLE FOR ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING * OR DISTRIBUTING THE SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS * LICENSORS BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT, * INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES, HOWEVER * CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING OUT OF THE USE OF * OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN ADVISED OF THE * POSSIBILITY OF SUCH DAMAGES. * * This software is not designed or intended for use in on-line control of * aircraft, air traffic, aircraft navigation or aircraft communications; or in * the design, construction, operation or maintenance of any nuclear * facility. Licensee represents and warrants that it will not use or * redistribute the Software for such purposes. */ package jVideos; import java.awt.*; import java.io.File; import javax.media.*; import javax.media.control.TrackControl; import javax.media.control.QualityControl; import javax.media.Format; import javax.media.format.*; import javax.media.datasink.*; import javax.media.protocol.*; import javax.media.protocol.DataSource; import java.io.IOException; /** * A sample program to split an input media file with multiplexed * audio and video tracks into files of individual elementary track. */ public class Split { SplitDataSource splitDS[]; Object fileSync = new Object(); boolean allDone = false; static String audioExt = null; static String videoExt = null; /** * Main program */ public static void main(String [] args) { String inputURL = null; if (args.length == 0) prUsage(); // Parse the arguments. int i = 0; while (i < args.length) { if (args[i].equals("-a")) { i++; if (i >= args.length) prUsage(); audioExt = args[i]; } else if (args[i].equals("-v")) { i++; if (i >= args.length) prUsage(); videoExt = args[i]; } else { inputURL = args[i]; } i++; } if (inputURL == null) { System.err.println("No input url specified."); prUsage(); } if (audioExt == null) { audioExt = ".wav"; } if (videoExt == null) { videoExt = ".mov"; } // Generate the input media locators. MediaLocator iml; if ((iml = createMediaLocator(inputURL)) == null) { System.err.println("Cannot build media locator from: " + inputURL); System.exit(0); } // Trancode with the specified parameters. Split split = new Split(); if (!split.doIt(iml, audioExt, videoExt)) { System.err.println("Failed to split the input"); } System.exit(0); } /** * Splits the tracks from a multiplexed input. */ public boolean doIt(MediaLocator inML, String audExt, String vidExt) { Processor p; try { System.err.println("- Create processor for: " + inML); p = Manager.createProcessor(inML); } catch (Exception e) { System.err.println("Yikes! Cannot create a processor from the given url: " + e); return false; } System.err.println("- Configure the processor for: " + inML); if (!waitForState(p, p.Configured)) { System.err.println("Failed to configure the processor."); return false; } // If the input is an MPEG file, we'll first convert that to // raw audio and video. if (FileTypeDescriptor.MPEG.equals(fileExtToCD(inML.getRemainder()).getEncoding())) { transcodeMPEGToRaw(p); } System.err.println("- Realize the processor for: " + inML); if (!waitForState(p, p.Realized)) { System.err.println("Failed to realize the processor."); return false; } // Set the JPEG quality to .5. setJPEGQuality(p, 0.5f); // Get the output data streams from the first processor. // Create a SplitDataSource for each of these elementary stream. PushBufferDataSource pbds = (PushBufferDataSource)p.getDataOutput(); PushBufferStream pbs[] = pbds.getStreams(); splitDS = new SplitDataSource[pbs.length]; allDone = false; boolean atLeastOne = false; // Create a file writer for each SplitDataSource to generate // the resulting media file. for (int i = 0; i < pbs.length; i++) { splitDS[i] = new SplitDataSource(p, i); if ((new FileWriter()).write(splitDS[i])) atLeastOne = true; } if (!atLeastOne) { System.err.println("Failed to split any of the tracks."); System.exit(1); } System.err.println("- Start splitting..."); waitForFileDone(); System.err.println(" ...done splitting."); return true; } /** * Callback from the FileWriter when a DataSource is done. */ void doneFile() { synchronized (fileSync) { for (int i = 0; i < splitDS.length; i++) { if (!splitDS[i].done) { return; } } // All done. allDone = true; fileSync.notify(); } } void waitForFileDone() { System.err.print(" "); synchronized (fileSync) { while (!allDone) { try { fileSync.wait(1000); System.err.print("."); } catch (Exception e) {} } } System.err.println(""); } /** * Transcode the MPEG audio to linear and video to JPEG so * we can do the splitting. */ void transcodeMPEGToRaw(Processor p) { TrackControl tc[] = p.getTrackControls(); AudioFormat afmt; for (int i = 0; i < tc.length; i++) { if (tc[i].getFormat() instanceof VideoFormat) tc[i].setFormat(new VideoFormat(VideoFormat.JPEG)); else if (tc[i].getFormat() instanceof AudioFormat) { afmt = (AudioFormat)tc[i].getFormat(); tc[i].setFormat(new AudioFormat(AudioFormat.LINEAR, afmt.getSampleRate(), afmt.getSampleSizeInBits(), afmt.getChannels())); } } } /** * Setting the encoding quality to the specified value on the JPEG encoder. * 0.5 is a good default. */ void setJPEGQuality(Player p, float val) { Control cs[] = p.getControls(); QualityControl qc = null; VideoFormat jpegFmt = new VideoFormat(VideoFormat.JPEG); // Loop through the controls to find the Quality control for // the JPEG encoder. for (int i = 0; i < cs.length; i++) { if (cs[i] instanceof QualityControl && cs[i] instanceof Owned) { Object owner = ((Owned)cs[i]).getOwner(); // Check to see if the owner is a Codec. // Then check for the output format. if (owner instanceof Codec) { Format fmts[] = ((Codec)owner).getSupportedOutputFormats(null); for (int j = 0; j < fmts.length; j++) { if (fmts[j].matches(jpegFmt)) { qc = (QualityControl)cs[i]; qc.setQuality(val); System.err.println("- Set quality to " + val + " on " + qc); break; } } } if (qc != null) break; } } } /** * Utility class to block until a certain state had reached. */ public class StateWaiter implements ControllerListener { Processor p; boolean error = false; StateWaiter(Processor p) { this.p = p; p.addControllerListener(this); } public synchronized boolean waitForState(int state) { switch (state) { case Processor.Configured: p.configure(); break; case Processor.Realized: p.realize(); break; case Processor.Prefetched: p.prefetch(); break; case Processor.Started: p.start(); break; } while (p.getState() < state && !error) { try { wait(1000); } catch (Exception e) { } } //p.removeControllerListener(this); return !(error); } public void controllerUpdate(ControllerEvent ce) { if (ce instanceof ControllerErrorEvent) { error = true; } synchronized (this) { notifyAll(); } } } /** * Block until the given processor has transitioned to the given state. * Return false if the transition failed. */ boolean waitForState(Processor p, int state) { return (new StateWaiter(p)).waitForState(state); } /** * Convert a file name to a content type. The extension is parsed * to determine the content type. */ ContentDescriptor fileExtToCD(String name) { String ext; int p; // Extract the file extension. if ((p = name.lastIndexOf('.')) < 0) return null; ext = (name.substring(p + 1)).toLowerCase(); String type; // Use the MimeManager to get the mime type from the file extension. if ( ext.equals("mp3")) { type = FileTypeDescriptor.MPEG_AUDIO; } else { if ((type = com.sun.media.MimeManager.getMimeType(ext)) == null) return null; type = ContentDescriptor.mimeTypeToPackageName(type); } return new FileTypeDescriptor(type); } /** * Create a media locator from the given string. */ static MediaLocator createMediaLocator(String url) { MediaLocator ml; if (url.indexOf(":") > 0 && (ml = new MediaLocator(url)) != null) return ml; if (url.startsWith(File.separator)) { if ((ml = new MediaLocator("file:" + url)) != null) return ml; } else { String file = "file:" + System.getProperty("user.dir") + File.separator + url; if ((ml = new MediaLocator(file)) != null) return ml; } return null; } static void prUsage() { System.err.println("Usage: java Split <input> -a <audio ext> -v <video ext> ..."); System.err.println(" <input>: output URL or file name"); System.err.println(" <audio ext>: audio file extension. e.g .wav"); System.err.println(" <video ext>: video file extension. e.g .mov"); System.exit(0); } //////////////////////////////////////// // // Inner classes. //////////////////////////////////////// /** * The custom DataSource to split input. */ class SplitDataSource extends PushBufferDataSource { Processor p; PushBufferDataSource ds; PushBufferStream pbs[]; SplitStream streams[]; int idx; boolean done = false; public SplitDataSource(Processor p, int idx) { this.p = p; this.ds = (PushBufferDataSource)p.getDataOutput(); this.idx = idx; pbs = ds.getStreams(); streams = new SplitStream[1]; streams[0] = new SplitStream(pbs[idx]); } public void connect() throws java.io.IOException { } public PushBufferStream [] getStreams() { return streams; } public Format getStreamFormat() { return pbs[idx].getFormat(); } public void start() throws java.io.IOException { p.start(); ds.start(); } public void stop() throws java.io.IOException { } public Object getControl(String name) { // No controls return null; } public Object [] getControls() { // No controls return new Control[0]; } public Time getDuration() { return ds.getDuration(); } public void disconnect() { } public String getContentType() { return ContentDescriptor.RAW; } public MediaLocator getLocator() { return ds.getLocator(); } public void setLocator(MediaLocator ml) { System.err.println("Not interested in a media locator"); } } /** * Utility Source stream for the SplitDataSource. */ class SplitStream implements PushBufferStream, BufferTransferHandler { PushBufferStream pbs; BufferTransferHandler bth; Format format; public SplitStream(PushBufferStream pbs) { this.pbs = pbs; pbs.setTransferHandler(this); } public void read(Buffer buf) /* throws IOException */{ // This wouldn't be used. } public ContentDescriptor getContentDescriptor() { return new ContentDescriptor(ContentDescriptor.RAW); } public boolean endOfStream() { return pbs.endOfStream(); } public long getContentLength() { return LENGTH_UNKNOWN; } public Format getFormat() { return pbs.getFormat(); } public void setTransferHandler(BufferTransferHandler bth) { this.bth = bth; } public Object getControl(String name) { // No controls return null; } public Object [] getControls() { // No controls return new Control[0]; } public synchronized void transferData(PushBufferStream pbs) { if (bth != null) bth.transferData(pbs); } } // class SplitStream /** * Given a DataSource, creates a DataSink and generate a file. */ class FileWriter implements ControllerListener, DataSinkListener { Processor p; SplitDataSource ds; DataSink dsink; boolean write(SplitDataSource ds) { this.ds = ds; // Create the processor to generate the final output. try { p = Manager.createProcessor(ds); } catch (Exception e) { System.err.println("Failed to create a processor to concatenate the inputs."); return false; } p.addControllerListener(this); // Put the Processor into configured state. if (!waitForState(p, p.Configured)) { System.err.println("Failed to configure the processor."); return false; } String ext, suffix; if (ds.getStreamFormat() instanceof AudioFormat) { ext = audioExt; suffix = "-aud"; } else { ext = videoExt; suffix = "-vid"; } ContentDescriptor cd; if ((cd = fileExtToCD(ext)) == null) { System.err.println("Couldn't figure out from the file extension the type of output needed: " + ext); return false; } // Set the output content descriptor on the final processor. System.err.println("- Set output content descriptor to: " + cd); if ((p.setContentDescriptor(cd)) == null) { System.err.println("Failed to set the output content descriptor on the processor."); return false; } // We are done with programming the processor. Let's just // realize and prefetch it. if (!waitForState(p, p.Prefetched)) { System.err.println("Failed to realize the processor."); return false; } String name = "file:" + System.getProperty("user.dir") + File.separator + "split" + suffix + ds.idx + ext; MediaLocator oml; if ((oml = createMediaLocator(name)) == null) { System.err.println("Cannot build media locator from: " + name); System.exit(0); } // Now, we'll need to create a DataSink. if ((dsink = createDataSink(p, oml)) == null) { System.err.println("Failed to create a DataSink for the given output MediaLocator: " + oml); return false; } dsink.addDataSinkListener(this); // OK, we can now start the actual concatenation. try { p.start(); dsink.start(); } catch (IOException e) { System.err.println("IO error during concatenation"); return false; } return true; } /** * Controller Listener. */ public void controllerUpdate(ControllerEvent evt) { if (evt instanceof ControllerErrorEvent) { System.err.println("Failed to split the file."); System.exit(-1); } else if (evt instanceof EndOfMediaEvent) { evt.getSourceController().close(); } } /** * Event handler for the file writer. */ public void dataSinkUpdate(DataSinkEvent evt) { if (evt instanceof EndOfStreamEvent || evt instanceof DataSinkErrorEvent) { // Cleanup. try { dsink.close(); } catch (Exception e) {} p.removeControllerListener(this); ds.done = true; doneFile(); } } /** * Create the DataSink. */ DataSink createDataSink(Processor p, MediaLocator outML) { DataSource ds; if ((ds = p.getDataOutput()) == null) { System.err.println("Something is really wrong: the processor does not have an output DataSource"); return null; } DataSink dsink; try { System.err.println("- Create DataSink for: " + outML); dsink = Manager.createDataSink(ds, outML); dsink.open(); } catch (Exception e) { System.err.println("Cannot create the DataSink: " + e); return null; } return dsink; } } }
package net.sourceforge.jFuzzyLogic.ruleImplication; /** * Rule inference method: Product * Base abstract class * @author pcingola@users.sourceforge.net */ public class RuleImplicationMethodProduct extends RuleImplicationMethod { public RuleImplicationMethodProduct() { super(); name = "product"; } @Override public double imply(double degreeOfSupport, double membership) { return degreeOfSupport * membership; } /** Printable FCL version */ @Override public String toStringFCL() { return "ACT : PROD;"; } }
package com.manoharacademy.corejava.programs.arrays; import java.util.Arrays; public class BubbleSort { //https://en.wikipedia.org/wiki/Bubble_sort public static void main(String[] args) { int[] ai = {5, 3, 2, 4, 1}; System.out.println("Before Sorting : " + Arrays.toString(ai)); for (int j = 0; j <= ai.length - 2; j++) { for (int i = 0; i <= ai.length - 2 - j; i++) { if (ai[i] > ai[i + 1]) { ai[i + 1] = ai[i] + ai[i + 1] - (ai[i] = ai[i + 1]); } } System.out.println("By the end of iteration " + Arrays.toString(ai)); } } }
package com.es.core.model.phone; import java.io.Serializable; public class Color implements Serializable { private static final long serialVersionUID = -1624488028942702059L; private Long id; private String code; public Color() { } public Color( final Long id, final String code ) { this.id = id; this.code = code; } public Long getId() { return id; } public void setId( final Long id ) { this.id = id; } public String getCode() { return code; } public void setCode( final String code ) { this.code = code; } @Override public int hashCode() { int result = 17; if (id != null) { result = 31 * result + id.hashCode(); } if (code != null) { result = 31 * result + code.hashCode(); } return result; } @Override public boolean equals( final Object obj ) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof Color)) return false; final Color other = (Color) obj; boolean idEquals = (this.id == null && other.id == null) || (this.id != null && this.id.equals(other.id)); boolean codeEquals = (this.code == null && other.code == null) || (this.code != null && this.code.equals(other.code)); return idEquals && codeEquals; } }
package pt.joja; import java.util.Arrays; import java.util.Random; public class Merge { public static void main(String[] args) { int nums = 100; Random rand = new Random(47); int[] eles = new int[nums]; int[] eles2 = new int[nums]; for (int i = 0; i < nums; i++) { eles[i] = rand.nextInt(1000); } System.arraycopy(eles, 0, eles2, 0, nums); System.out.println(Arrays.toString(eles)); sort(eles); System.out.println(Arrays.toString(eles)); System.out.println("-------------------"); compCtr = 0; copyCtr = 0; System.out.println(Arrays.toString(eles2)); sortBU(eles2); System.out.println(Arrays.toString(eles2)); } public static void sortBU(int[] nums) { int len = nums.length; for (int sz = 1; sz < len; sz = sz + sz) { for (int lo = 0; lo < len - sz; lo += (sz + sz)) { merge(nums, lo, lo + sz, Math.min(len, lo + sz + sz)); } } System.out.println("[Merge.sort] compared: " + compCtr); System.out.println("[Merge.sort] copied : " + copyCtr); } public static void sort(int[] nums) { sort(nums, 0, nums.length); System.out.println("[Merge.sort] compared: " + compCtr); System.out.println("[Merge.sort] copied : " + copyCtr); } public static void sort(int[] nums, int left, int right) { if (right - left <= 1) { return; } int mid = (right + left) / 2; sort(nums, left, mid); sort(nums, mid, right); merge(nums, left, mid, right); } static int compCtr = 0; static int copyCtr = 0; public static void merge(int[] nums, int left, int mid, int right) { int[] result = new int[nums.length]; int idx = left; int i = left, j = mid; while (i < mid && j < right) { compCtr++; if (nums[i] < nums[j]) { result[idx++] = nums[i++]; } else { result[idx++] = nums[j++]; } copyCtr++; } while (i < mid) { result[idx++] = nums[i++]; copyCtr++; } while (j < right) { result[idx++] = nums[j++]; copyCtr++; } copyCtr += (right - left); System.arraycopy(result, left, nums, left, right - left); } }
package goa.server.http1.multipart; import java.io.InputStream; public abstract class NIOInputStream extends InputStream implements BinaryNIOInputSource { }
package com.jarvis1.vo; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import org.hibernate.annotations.GeneratorType; @Entity @Table(name="login") public class loginVo { @Id @GeneratedValue(strategy=GenerationType.AUTO) private String lid; @Column(name="uname1") private String uname1; @Column(name="pwd1") private String pwd1; public String getId() { return lid; } public void setId(String id) { this.lid = id; } public String getUname1() { return uname1; } public void setUname1(String uname1) { this.uname1 = uname1; } public String getPwd1() { return pwd1; } public void setPwd1(String pwd1) { this.pwd1 = pwd1; } }
package edu.mit.needlstk; // import ANTLR's runtime libraries import org.antlr.v4.runtime.*; import org.antlr.v4.runtime.tree.*; import java.util.HashSet; import java.util.HashMap; import java.util.List; import java.util.ArrayList; import java.io.PrintWriter; import java.io.IOException; public class Compiler { public static void main(String[] args) throws Exception { // create a CharStream that reads from standard input ANTLRInputStream input = new ANTLRInputStream(System.in); // create a lexer that feeds off of input CharStream PerfQueryLexer lexer = new PerfQueryLexer(input); // Add an error listener lexer.removeErrorListeners(); lexer.addErrorListener(new ThrowingErrorListener()); // create a buffer of tokens pulled from the lexer CommonTokenStream tokens = new CommonTokenStream(lexer); // create a parser that feeds off the tokens buffer PerfQueryParser parser = new PerfQueryParser(tokens); // Add an error listener parser.removeErrorListeners(); parser.addErrorListener(new ThrowingErrorListener()); // begin parsing at the prog production ParseTree tree = parser.prog(); // Create a walker for the parse tree ParseTreeWalker walker = new ParseTreeWalker(); // Create symbol table System.out.println("Creating symbol table ..."); SymbolTableCreator symbolTableCreator = new SymbolTableCreator(); walker.walk(symbolTableCreator, tree); // Expression tree creator System.out.println("Creating expression tree ..."); ExprTreeCreator exprTreeCreator = new ExprTreeCreator(PerfQueryParser.ID, symbolTableCreator.symbolTable()); walker.walk(exprTreeCreator, tree); /// Global analysis to extract locations to install queries System.out.println("Analyzing queries globally ..."); GlobalAnalyzer globalAnalyzer = new GlobalAnalyzer(new SwitchSet().getSwitches(), exprTreeCreator.getSymTree(), exprTreeCreator.getLastAssignedId(), symbolTableCreator.getAggFunAssocMap()); LocatedExprTree queryTree = globalAnalyzer.visit(tree); System.err.println(queryTree.dotOutput()); /// Check for use-before-define errors in fold function code AggFunParamExtractor afpe = new AggFunParamExtractor(); afpe.visit(tree); HashMap<String, List<String>> stateVars = afpe.getStateVars(); HashMap<String, List<String>> fieldVars = afpe.getFieldVars(); LexicalSymbolTable lst = new LexicalSymbolTable(stateVars, fieldVars); lst.visit(tree); HashMap<String, HashMap<String, AggFunVarType>> globalSymTab = lst.getGlobalSymTable(); /// Detect bounded packet history HistoryDetector hd = new HistoryDetector(stateVars, fieldVars); hd.visit(tree); HashMap<String, HashMap<String, Integer>> hists = hd.getConvergedHistory(); System.out.println(hd.reportHistory()); /// Produce code for aggregation functions System.out.println("Generating code for aggregation functions..."); IfConvertor ifc = new IfConvertor(globalSymTab); ifc.visit(tree); HashMap<String, ThreeOpCode> aggFunCode = ifc.getAggFunCode(); /// Adjust state updates which are linear-in-state System.out.println("Performing linear-in-state transformations..."); Linear linear = new Linear(aggFunCode, hists, stateVars, fieldVars, globalSymTab); linear.extractLinearUpdates(); globalSymTab = linear.getGlobalSymTab(); aggFunCode = linear.getAggFunCode(); System.out.println(aggFunCode); /// Produce code for all operators System.out.println("Generating code for all query operators..."); ConfigGen cg = new ConfigGen(aggFunCode, globalSymTab, stateVars, fieldVars); cg.visit(tree); /// Pipeline the stages PipeConstructor pc = new PipeConstructor(cg.getQueryToPipe(), exprTreeCreator.getDepTable(), exprTreeCreator.getLastAssignedId()); ArrayList<PipeStage> fullPipe = pc.stitchPipe(); /// A small P4-specific pass to only allow divisions by (constant) powers of 2. DivisorChecker dc = new DivisorChecker(fullPipe); dc.checkDivisor(); /// Print P4 fragments into a file boolean success = CodeFragmentPrinter.writeP4(pc, fullPipe); if (success) { System.out.println("P4 fragments output in output.p4");// TODO: unhardcode } boolean printed = CodeFragmentPrinter.writeDominoMonolithic(pc, fullPipe); if (printed) { System.out.println("Domino fragments output in domino-*.c"); } } }
package smarthome.agents; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.DataOutputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import smarthome.util.SystemDBAccess; import smarthome.util.logging.SHLogger; /** * Implements the base agent type in the smart home system. The base agent contains common * functionality shared by all agents within the smart home system. * @author Bryce McAnally */ public abstract class BaseAgent { private final ByteArrayOutputStream _byteStream = new ByteArrayOutputStream(); private final DataOutputStream _outputStream = new DataOutputStream(_byteStream); protected String _name, _dbHost, _dbUser, _dbPassword; public static final int FILE_SEGMENT_SIZE = 1024; /** * Default constructor. */ protected BaseAgent() {} /** * The constructor for when an agent name and database connection information is provided. * @param name The agent name. * @param dbInfo The database connection information (host, user, password). */ protected BaseAgent(String name, String[] dbInfo) { if(dbInfo.length < 3) { System.out.println("Database information was not provided (Host User Password)."); System.exit(1); } _name = name; _dbHost = dbInfo[0]; _dbUser = dbInfo[1]; _dbPassword = dbInfo[2]; SystemDBAccess.setDatabaseSystem(_name, _dbHost, _dbUser, _dbPassword); } /** * All agents must implement a run method. */ public abstract void runAgent(); /** * The default agent termination method. Most agents will override this method. */ public void terminateAgent() { SHLogger.logInfo(_name, "Agent terminated."); System.exit(0); } /** * Sends numeric data to an agent on the local machine. Should be extended to * a specified protocol later. Objects necessary for data transfer are pre-created * and saved in the agent to minimize communication latency. * @param socket The socket of the sending agent. * @param port The port of the receiving agent. * @param value The data to send. */ protected void sendData(DatagramSocket socket, int port, int value) { try { _outputStream.writeInt(value); byte[] bytes = _byteStream.toByteArray(); // Sets up the packet and sends it to the process with the specified port. DatagramPacket packet = new DatagramPacket(bytes, bytes.length, InetAddress.getLocalHost(), port); socket.send(packet); } catch(IOException ex) { SHLogger.logFatal(_name, "Error sending data.", ex.getStackTrace()); } finally { _byteStream.reset(); } } /** * Writes a file to the local file system. * @param inputStream The input stream for the file. * @param filename The full path for the file. */ protected void writeFile(InputStream inputStream, String filename) { try(BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(filename))) { byte[] bytes = new byte[FILE_SEGMENT_SIZE]; int count; // Writes the file while((count = inputStream.read(bytes)) > 0) outputStream.write(bytes, 0, count); outputStream.flush(); } catch(IOException ex) { SHLogger.logFatal(_name, "Error writing file to local file system.", ex.getStackTrace()); } } }
package com.some; /** * * 功能说明: * * @version V1.0 * @author qzq * @date 2017年11月3日 * @since JDK1.6 */ public class Some { public static void main(String[] args){ } }
package br.com.zup.kafka.consumer.typetests; import br.com.zup.kafka.consumer.TestConfigs; import br.com.zup.kafka.config.props.ConsumerProperties; import br.com.zup.kafka.config.props.OffsetReset; import br.com.zup.kafka.config.props.ProducerProperties; import br.com.zup.kafka.config.props.PropertyBuilder; import br.com.zup.kafka.consumer.ConsumerRunner; import br.com.zup.kafka.consumer.GenericConsumerHandler; import br.com.zup.kafka.producer.KafkaProducer; import br.com.zup.kafka.util.JavaTypeBuilder; import org.junit.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.*; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; public class ZupKafkaListStringTest { private static final Logger LOGGER = LoggerFactory.getLogger(ZupKafkaListStringTest.class); private static final String TOPIC = "zup_kafka_list_string_topic"; private static KafkaProducer<String, List<String>> producer; private static ExecutorService consumerExecutorService; private static GenericConsumerHandler<List<String>> listStringConsumerHandler = new GenericConsumerHandler<>(); @BeforeClass public static void beforeClass() { ProducerProperties props = PropertyBuilder.producer(TestConfigs.KAFKA_BOOTSTRAP_SERVERS); producer = new KafkaProducer<>(props); ConsumerProperties<String, List<String>> consumerProperties = PropertyBuilder .consumer(listStringConsumerHandler) .withTopics(Collections.singletonList(TOPIC)) .withServers(TestConfigs.KAFKA_BOOTSTRAP_SERVERS) .withGroupId(TestConfigs.KAFKA_DEFAULT_GROUP_ID) .withDeserializerType(JavaTypeBuilder.build(List.class, String.class)) .withAutoOffsetReset(OffsetReset.EARLIEST); consumerExecutorService = ConsumerRunner.execute(TestConfigs.KAFKA_DEFAULT_CONSUMER_POOL_SIZE, consumerProperties); } @AfterClass public static void afterClass() throws InterruptedException { producer.close(); consumerExecutorService.shutdown(); consumerExecutorService.awaitTermination(10, TimeUnit.SECONDS); } @Test public void listStringTest() throws ExecutionException, InterruptedException { listStringConsumerHandler.setCountDown(1); producer.send(TOPIC, Collections.singletonList("listStringTestMsg")).get(); Assert.assertEquals(listStringConsumerHandler.await(), true); } }
package cn.Utils; public class Utils { public static String getDeptByclssId(String cls) { if(cls.trim().startsWith("01")) { return "通信学院"; } if(cls.trim().startsWith("08")) { return "自动化学院"; } if(cls.trim().startsWith("03")) { return "计算机学院"; } if(cls.trim().startsWith("04")) { return "传媒学院"; } if(cls.trim().startsWith("05")) { return "光电学院"; } if(cls.trim().startsWith("06")) { return "外国语学院"; } return ""; } }
package com.siscom.controller.mapper; import com.siscom.controller.dto.ProdutoDto; import com.siscom.service.model.Produto; import java.util.Date; public class ProdutoMapper { public static Produto mapToModel(ProdutoDto produto) { return Produto.builder() .nome(produto.getNome()) .precoUnitario(produto.getPrecoUnitario()) .estoque(produto.getEstoque()) .estoqueMinimo(produto.getEstoqueMinimo()) .dateCad(new Date()) .build(); } }
// Test driver for the MyDoublyLinkedList class. // by Jeff Ward import java.util.*; public class TestMyDoublyLinkedList { public static void main(String[] args) { MyAbstractSequentialList<String> list = new MyDoublyLinkedList<String>(); try { list.removeFirst(); System.out.println("Test 1 failed"); System.exit(1); } catch (NoSuchElementException ex) { System.out.println("Test 1 successful"); } try { list.removeLast(); System.out.println("Test 2 failed"); System.exit(1); } catch (NoSuchElementException ex) { System.out.println("Test 2 successful"); } list.add("Alabama"); list.add("Alaska"); list.add("Arizona"); list.add("Arkansas"); // The list should now be: // [Alabama, Alaska, Arizona, Arkansas] String listToString = list.toString(); if (listToString.equals("[Alabama, Alaska, Arizona, Arkansas]")) System.out.println("Test 3 successful"); else { System.out.println("Test 3 failed"); System.out.println(listToString); System.exit(1); } list.add(4, "California"); list.add(0, "West Virginia"); list.add(2, "Wisconsin"); list.add(6, "Wyoming"); // [West Virginia, Alabama, Wisconsin, Alaska, Arizona, Arkansas, Wyoming, California] listToString = list.toString(); if (listToString.equals("[West Virginia, Alabama, Wisconsin, Alaska, Arizona, Arkansas, Wyoming, California]")) System.out.println("Test 4 successful"); else { System.out.println("Test 4 failed"); System.out.println(listToString); System.exit(1); } list.remove(list.indexOf("West Virginia")); list.remove(list.indexOf("Wisconsin")); list.remove("Wyoming"); // [Alabama, Alaska, Arizona, Arkansas, California] listToString = list.toString(); if (listToString.equals("[Alabama, Alaska, Arizona, Arkansas, California]")) System.out.println("Test 5 successful"); else { System.out.println("Test 5 failed"); System.out.println(listToString); System.exit(1); } // still [Alabama, Alaska, Arizona, Arkansas, California]")) StringBuilder iteratorToString = new StringBuilder(); for (String s : list) { iteratorToString.append(s); } if (iteratorToString.toString().equals("AlabamaAlaskaArizonaArkansasCalifornia")) System.out.println("Test 6 successful"); else { System.out.println("Test 6 failed"); System.out.println(listToString); System.out.println(iteratorToString.toString()); System.exit(1); } list.set(1, "Arkansas"); // [Alabama, Arkansas, Arizona, Arkansas, California] listToString = list.toString(); if (listToString.equals("[Alabama, Arkansas, Arizona, Arkansas, California]")) System.out.println("Test 7 successful"); else { System.out.println("Test 7 failed"); System.out.println(listToString); System.exit(1); } if (!list.contains("Arizona")) throw new RuntimeException(); if (list.contains("Alaska")) throw new RuntimeException(); if (list.get(2) != "Arizona") throw new RuntimeException(); if (list.indexOf("Arkansas") != 1) throw new RuntimeException(); if (list.lastIndexOf("Arkansas") != 3) throw new RuntimeException(); try { list.get(-1); System.out.println("Test 8 failed"); System.exit(1); } catch (IndexOutOfBoundsException ex) { System.out.println("Test 8 successful"); } try { list.get(5); System.out.println("Test 9 failed"); System.exit(1); } catch (IndexOutOfBoundsException ex) { System.out.println("Test 9 successful"); } try { list.set(-1, "Colorado"); System.out.println("Test 10 failed"); System.exit(1); } catch (IndexOutOfBoundsException ex) { System.out.println("Test 10 successful"); } try { list.set(5, "Connecticut"); System.out.println("Test 11 failed"); System.exit(1); } catch (IndexOutOfBoundsException ex) { System.out.println("Test 11 successful"); } try { list.remove(-1); System.out.println("Test 12 failed"); System.exit(1); } catch (IndexOutOfBoundsException ex) { System.out.println("Test 12 successful"); } try { list.remove(5); System.out.println("Test 13 failed"); System.exit(1); } catch (IndexOutOfBoundsException ex) { System.out.println("Test 13 successful"); } // still [Alabama, Arkansas, Arizona, Arkansas, California] iteratorToString = new StringBuilder(); ListIterator<String> listIter = list.listIterator(0); try { listIter.previous(); System.out.println("Test 14 failed"); System.exit(1); } catch (NoSuchElementException ex) { System.out.println("Test 14 successful"); } while (listIter.hasNext()) iteratorToString.append(listIter.next()); if (iteratorToString.toString().equals("AlabamaArkansasArizonaArkansasCalifornia")) System.out.println("Test 15 successful"); else { System.out.println("Test 15 failed"); System.out.println(iteratorToString.toString()); System.exit(1); } try { listIter.next(); System.out.println("Test 16 failed"); System.exit(1); } catch (NoSuchElementException ex) { System.out.println("Test 16 successful"); } iteratorToString = new StringBuilder(); while (listIter.hasPrevious()) iteratorToString.append(listIter.previous()); if (iteratorToString.toString().equals("CaliforniaArkansasArizonaArkansasAlabama")) System.out.println("Test 17 successful"); else { System.out.println("Test 17 failed"); System.out.println(iteratorToString.toString()); System.exit(1); } int counter = 2; listIter = list.listIterator(counter); while (listIter.hasNext()) { if (listIter.nextIndex() != counter) throw new RuntimeException(); if (listIter.previousIndex() != counter - 1) throw new RuntimeException(); if (listIter.next() != list.get(counter)) throw new RuntimeException(); counter++; } while (listIter.hasPrevious()) { if (listIter.nextIndex() != counter) throw new RuntimeException(); if (listIter.previousIndex() != counter - 1) throw new RuntimeException(); if (listIter.previous() != list.get(counter - 1)) throw new RuntimeException(); counter--; } System.out.println("Test 18 successful"); // still [Alabama, Arkansas, Arizona, Arkansas, California] while (listIter.hasNext()) if (listIter.next().length() == 7) listIter.remove(); while (listIter.hasNext()) listIter.next(); while (listIter.hasPrevious()) if (listIter.previous() == "California") listIter.remove(); // [Arkansas, Arkansas] listToString = list.toString(); if (listToString.equals("[Arkansas, Arkansas]")) System.out.println("Test 19 successful"); else { System.out.println("Test 19 failed"); System.out.println("listToString = " + listToString); System.exit(1); } listIter = list.listIterator(); listIter.next(); listIter.set("Indiana"); listIter.add("Kentucky"); listIter.next(); listIter.set("Ohio"); // [Indiana, Kentucky, Ohio] if (list.size() != 3) throw new RuntimeException(); if (list.getFirst() != "Indiana" || list.getLast() != "Ohio") throw new RuntimeException(); if (list.removeFirst() != "Indiana" || list.removeLast() != "Ohio") throw new RuntimeException(); System.out.println("Test 20 successful"); // [Kentucky] listToString = list.toString(); if (listToString.equals("[Kentucky]")) System.out.println("Test 21 successful"); else { System.out.println("Test 21 failed"); System.out.println("listToString = " + listToString); System.exit(1); } listIter = list.listIterator(); try { listIter.remove(); System.out.println("Test 22 failed"); System.exit(1); } catch (IllegalStateException ex) { System.out.println("Test 22 successful"); } iteratorToString = new StringBuilder(); iteratorToString.append(listIter.next()); if (iteratorToString.toString().equals("Kentucky")) System.out.println("Test 23 successful"); else { System.out.println("Test 23 failed"); System.out.println("iteratorToString = " + iteratorToString); System.exit(1); } listIter.remove(); try { listIter.remove(); System.out.println("Test 24 failed"); System.exit(1); } catch (IllegalStateException ex) { System.out.println("Test 24 successful"); } listIter.add("Michigan"); try { listIter.remove(); System.out.println("Test 25 failed"); System.exit(1); } catch (IllegalStateException ex) { System.out.println("Test 25 successful"); } list.add(1, null); // [Michigan, null] if (list.indexOf("Michigan") != 0 || list.indexOf(null) != 1) throw new RuntimeException(); System.out.println("Test 26 successful"); } }
package estructuras; import java.util.ArrayList; import java.util.Comparator; import java.util.List; public class Polinomio { private List<Termino> terminos; public Polinomio(){ this.terminos = new ArrayList<Termino>(); } public Polinomio(Polinomio p){ this.terminos = p.getTerminos(); } public List<Termino> getTerminos(){ return this.terminos; } public void setTerminos(List<Termino> terminos){ this.terminos = terminos; } public void addTermino(Termino t){ this.terminos.add(t); } public void addAllTerminos(List<Termino> terminos){ this.terminos.addAll(terminos); } public void ordenar(Comparator<Termino> orden){ terminos.sort(orden); } public Termino leadingTerm(Comparator<Termino> orden){ terminos.sort(orden); return terminos.get(0); } private List<Termino> agruparRec(int index,List<Termino> lista){ if( index == lista.size()-1 || lista.size() <= 1){ return lista; }else{ Termino nuevo,aux1,aux2; aux1 = lista.get(index); aux2 = lista.get(index+1); if( aux1.equals(aux2) ){ nuevo = new Termino(aux1.getCoeficiente()+aux2.getCoeficiente(), aux1.getMonomio()); lista.remove(index+1); lista.remove(index); if (nuevo.getCoeficiente() != 0f){ lista.add(index, nuevo); } }else if( aux1.getCoeficiente() == 0f ){ lista.remove(index); }else{ index = index+1; } return agruparRec(index,lista); } } public void agrupar(){ this.terminos = agruparRec(0,this.terminos); } public String toString(){ String aux = ""; for( Termino t : this.getTerminos() ){ aux += "+" + t; } return aux; } }
package algorithms.strings.tries.practice; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import lombok.Getter; import lombok.Setter; /** * Created by Chen Li on 2018/6/17. */ public class TernaryTrie<V> { private Node<V> root; private int count = 0; public V get(String key) { Node<V> node = getNode(root, key, 0); return node == null ? null : node.getValue(); } private Node<V> getNode(Node<V> node, String key, int i) { if (node == null) { return null; } char ch = key.charAt(i); int compare = ch - node.character; if (compare == 0) { if (i == key.length() - 1) { return node; } else { return getNode(node.equal, key, i + 1); } } else if (compare < 0) { return getNode(node.less, key, i); } else { return getNode(node.greater, key, i); } } public void put(String key, V value) { root = putNode(root, key, value, 0); } private Node<V> putNode(Node<V> node, String key, V value, int i) { char ch = key.charAt(i); if (node == null) { node = new Node<>(); node.character = ch; } int compare = ch - node.character; if (compare == 0) { if (i == key.length() - 1) { if (node.value == null) { count++; } node.value = value; } else { Node equal = putNode(node.equal, key, value, i + 1); node.equal = equal; } } else if (compare < 0) { Node less = putNode(node.less, key, value, i); node.less = less; } else { Node greater = putNode(node.greater, key, value, i); node.greater = greater; } return node; } public void delete(String key) { root = deleteNode(root, key, 0); } public void clear() { this.root = null; } private Node<V> deleteNode(Node<V> node, String key, int i) { if (node == null) { return null; } char ch = key.charAt(i); int compare = ch - node.character; if (compare == 0) { if (i == key.length() - 1) { if (node.value != null) { count--; } node.value = null; } else { Node equal = deleteNode(node.equal, key, i + 1); node.equal = equal; } } else if (compare < 0) { Node less = deleteNode(node.less, key, i); node.less = less; } else { Node greater = deleteNode(node.greater, key, i); node.greater = greater; } if (node.value == null && node.equal == null && node.less == null && node.greater == null) { node = null; } return node; } public Collection<String> keysWithPrefix(String prefix) { if (isEmpty()) { return Collections.emptyList(); } Collection<String> keys = new ArrayList<>(); Node fromNode = getNode(root, prefix, 0); collect(fromNode, prefix.substring(0, prefix.length() - 1), keys); return keys; } private void collect(Node node, String prefix, Collection<String> keys) { if (node == null) { return; } if (node.value != null) { keys.add(prefix + node.character); } if (node.less != null) { collect(node.less, prefix, keys); } if (node.greater != null) { collect(node.greater, prefix, keys); } if (node.getEqual() != null) { collect(node.equal, prefix + node.character, keys); } } public String longestPrefixOf(String key) { if (root == null) { return null; } int max = 0; Node current = root; int i = 0; while (i < key.length() && current != null) { char currentChar = key.charAt(i); int compare = currentChar - current.character; if (compare == 0) { if (current.value != null) { max = i; } current = current.equal; i++; } else if (compare < 0) { current = current.less; } else { current = current.greater; } } return max > 0 ? key.substring(0, max + 1) : null; } public boolean isEmpty() { return root == null; } public int size() { return count; } @Getter @Setter private class Node<V> { private Node<V> less; private Node<V> equal; private Node<V> greater; private V value; private char character; } }
package com.Hackerrank.algos.graphtheory; import java.io.*; import java.util.*; public class BreadthFirstSearch { public static void main(String[] args) { /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */ Scanner sc=new Scanner(System.in); int t=sc.nextInt(); int verCount,edCount; int ver,ed,start; for(int i=0;i<t;i++){ verCount=sc.nextInt(); edCount=sc.nextInt(); @SuppressWarnings("unchecked") List<Integer>[] edgeList=new LinkedList[verCount]; for(int j=0;j<edCount;j++){ ver=sc.nextInt()-1; ed=sc.nextInt()-1; if(edgeList[ver]==null){ edgeList[ver]=new LinkedList<Integer>(); edgeList[ver].add(ed); }else{ edgeList[ver].add(ed); } if(edgeList[ed]==null){ edgeList[ed]=new LinkedList<Integer>(); edgeList[ed].add(ver); }else{ edgeList[ed].add(ver); } } start=sc.nextInt()-1; bFS(edgeList,start,verCount); System.out.println(); } } private static void bFS(List<Integer>[] edgeList,int start,int verCount){ int[] d=new int[verCount]; for(int i=0;i<verCount;i++){ d[i]=-1; } d[start]=0; Queue<Integer> queue=new LinkedList<Integer>(); queue.add(start); int current; while(!queue.isEmpty()){ current=queue.poll(); for(int next:edgeList[current]){ if(d[next]==-1){ d[next]=d[current]+6; queue.add(next); } } } for(int i=0;i<verCount;i++){ if(i!=start){ System.out.print(d[i]+" "); } } } }
package com.latmod.warp_pads.block; import com.feed_the_beast.ftbl.lib.block.EnumHorizontalOffset; import com.feed_the_beast.ftbl.lib.tile.TileBase; import com.latmod.warp_pads.item.WarpPadsItems; /** * Created by LatvianModder on 20.02.2017. */ public abstract class TileWarpPadBase extends TileBase { public boolean checkUpdates = true; public abstract EnumHorizontalOffset getPart(); @Override public void onNeighborChange() { if(checkUpdates && !WarpPadsItems.WARP_PAD.canExist(world, pos)) { world.setBlockToAir(pos); } else { super.onNeighborChange(); } } }