text
stringlengths
10
2.72M
package com.wangyuelin.easybuglog.log; import java.util.List; public interface ILog { /** * 当方法进入的的处理 * @param args * @param methodName * @param belongClass */ void methodEnter(List<Object> args, String methodName, String belongClass); /** * 当方法退出的处理 * @param args * @param methodName * @param belongClass */ void methodExit(List<Object> args, String methodName, String belongClass); }
package org.globsframework.sqlstreams.drivers.mongodb; import com.mongodb.client.MongoCollection; import org.bson.Document; import org.globsframework.metamodel.Field; import org.globsframework.sqlstreams.BulkDbRequest; import org.globsframework.sqlstreams.exceptions.SqlException; import org.globsframework.sqlstreams.utils.ThreadUtils; import org.globsframework.streams.accessors.Accessor; import org.globsframework.utils.collections.Pair; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.Future; class MongoCreateSqlRequestParallele implements BulkDbRequest { public static final int BATCH_SIZE = Integer.getInteger("mongo.create.batch.size", 500); private static Logger LOGGER = LoggerFactory.getLogger(MongoCreateSqlRequestParallele.class); private MongoCollection<Document> collection; private final Pair<MongoDbService.UpdateAdapter, Accessor> fieldsValues[]; private MongoDbService sqlService; private boolean bulk; private List<Document> docs; private int count = 0; private CompletionService<Boolean> completionService; ThreadUtils.Limiter limiter = ThreadUtils.createLimiter(10); public MongoCreateSqlRequestParallele(MongoCollection<Document> collection, Map<Field, Accessor> fieldsValues, MongoDbService sqlService, boolean bulk) { this.collection = collection; this.fieldsValues = fieldsValues.entrySet().stream() .map(e -> Pair.makePair(sqlService.getAdapter(e.getKey()), e.getValue())) .toArray(Pair[]::new); this.sqlService = sqlService; this.bulk = bulk; completionService = new ExecutorCompletionService<>(sqlService.getExecutor()); } public void run() throws SqlException { Document doc = new Document(); for (Pair<MongoDbService.UpdateAdapter, Accessor> fieldAccessorEntry : fieldsValues) { Object objectValue = fieldAccessorEntry.getSecond().getObjectValue(); MongoDbService.UpdateAdapter first = fieldAccessorEntry.getFirst(); if (objectValue != null) { first.create(objectValue, doc, sqlService); } } LOGGER.debug("create {}", doc); if (++count <= 2 && !bulk) { collection.insertOne(doc); } else { if (docs == null) { docs = new ArrayList<>(BATCH_SIZE); } docs.add(doc); if (docs.size() == BATCH_SIZE) { limiter.limitParallelConnection(); final List<Document> toInsert = docs; docs = null; completionService.submit(() -> { try { collection.insertMany(toInsert); } finally { limiter.notifyDown(); } return true; }); } } } public void close() { flushAll(); LOGGER.info(count + " doc inserted"); } private void flushAll() { if (docs != null && !docs.isEmpty()) { collection.insertMany(docs); } docs = null; limiter.waitAllDone(); readAllComplete(); } private void readAllComplete() { try { while (true) { Future<Boolean> poll = completionService.poll(); if (poll != null) { poll.get(); } else { return; } } } catch (Exception e) { throw new RuntimeException(e); } } public void flush() { flushAll(); } }
package com.example.passin.domain.password; import com.example.base.mapper.ReferenceMapper; import org.mapstruct.Mapper; @Mapper(componentModel = "spring", uses = {ReferenceMapper.class}) public interface PasswordMapper { }
package com.tencent.mm.plugin.emoji.sync; public interface e { void j(String str, int i, boolean z); void zI(String str); }
package com.kdp.wanandroidclient.ui.home; import com.kdp.wanandroidclient.R; import com.kdp.wanandroidclient.application.AppContext; import com.kdp.wanandroidclient.bean.Article; import com.kdp.wanandroidclient.bean.Banner; import com.kdp.wanandroidclient.bean.BaseBean; import com.kdp.wanandroidclient.bean.HomeData; import com.kdp.wanandroidclient.bean.PageListData; import com.kdp.wanandroidclient.net.callback.RxObserver; import com.kdp.wanandroidclient.net.callback.RxPageListObserver; import com.kdp.wanandroidclient.net.callback.RxZipObserver; import com.kdp.wanandroidclient.ui.core.model.impl.HomeModel; import com.kdp.wanandroidclient.ui.core.presenter.BasePresenter; import java.util.List; import io.reactivex.functions.Function3; /** * Home Presenter * author: 康栋普 * date: 2018/2/11 */ public class HomePresenter extends BasePresenter<HomeContract.IHomeView> implements HomeContract.IHomePresenter { private HomeModel homeModel; private HomeContract.IHomeView homeView; HomePresenter() { this.homeModel = new HomeModel(); } /** * 获取首页Banner、置顶文章、列表文章 */ @Override public void getHomeData() { homeView = getView(); Function3<BaseBean<List<Banner>>, BaseBean<List<Article>>, BaseBean<PageListData<Article>>, HomeData> function3 = new Function3<BaseBean<List<Banner>>, BaseBean<List<Article>>, BaseBean<PageListData<Article>>, HomeData>() { @Override public HomeData apply(BaseBean<List<Banner>> banner, BaseBean<List<Article>> homeTop, BaseBean<PageListData<Article>> home) throws Exception { HomeData homeData = new HomeData(); homeData.setBanner(banner); for (Article bean : homeTop.data){ //置顶 bean.setTop(true); } homeData.setHomeTop(homeTop); homeData.setHome(home); return homeData; } }; RxZipObserver<HomeData> rxZipObserver = new RxZipObserver<HomeData>(this) { @Override public void onNext(HomeData homeData) { homeView.setBannerData(homeData.getBanner().data); List<Article> list = homeData.getHome().data.getDatas(); list.addAll(0,homeData.getHomeTop().data); homeView.clearListData(); homeView.autoLoadMore(); homeView.setData(list); if (homeView.getData().size() == 0) { homeView.showEmpty(); }else { homeView.showContent(); } } }; homeModel.getHomeData(homeView.getPage(),function3, rxZipObserver); addDisposable(rxZipObserver); } /** * 加载更多,获取更多文章 */ @Override public void getMoreArticleList() { homeView = getView(); RxPageListObserver<Article> rxPageListObserver = new RxPageListObserver<Article>(this) { @Override public void onSuccess(List<Article> homeList) { homeView.getData().addAll(homeList); homeView.showContent(); } @Override public void onFail(int errorCode, String errorMsg) { homeView.showFail(errorMsg); } }; homeModel.getMoreArticleList(homeView.getPage(),rxPageListObserver); addDisposable(rxPageListObserver); } /** * 收藏 */ @Override public void collectArticle() { RxObserver<String> mCollectRxObserver = new RxObserver<String>(this) { @Override protected void onStart() { } @Override protected void onSuccess(String data) { homeView.collect(true, AppContext.getContext().getString(R.string.collect_success)); } @Override protected void onFail(int errorCode, String errorMsg) { view.showFail(errorMsg); } }; homeModel.collectArticle(homeView.getArticleId(), mCollectRxObserver); addDisposable(mCollectRxObserver); } /** * 取消收藏 */ @Override public void unCollectArticle() { RxObserver<String> unCollectRxObserver = new RxObserver<String>(this) { @Override protected void onStart() { } @Override protected void onSuccess(String data) { homeView.collect(false, AppContext.getContext().getString(R.string.uncollect_success)); } @Override protected void onFail(int errorCode, String errorMsg) { view.showFail(errorMsg); } }; homeModel.unCollectArticle(homeView.getArticleId(), unCollectRxObserver); addDisposable(unCollectRxObserver); } }
package io.muic.ooc.Commands; import io.muic.ooc.Items.Item; import io.muic.ooc.Map.Room; import io.muic.ooc.Player; /** * Created by karn806 on 2/3/17. */ public class UseCommand implements Command{ @Override public void apply(Player player, String args) { if (args.equals("Potion")){ if (player.getBag().size()!=0){ Item potion = player.getBag().get(0); int playerHp = player.getHp(); player.setHp(playerHp+potion.getHealPoint()); System.out.println("Your HP: "+player.getHp()); player.getBag().remove(0); } else { System.out.println("There is no more Potion! :("); } } else { System.out.println(" There is no such command. Please insert (item) after command 'use' "); System.out.println(" Hint: use Potion"); } } }
package com.shubhendu.javaworld.datastructures.tree; import java.util.LinkedList; import java.util.Queue; import com.shubhendu.javaworld.datastructures.tree.InrderSuccessor.TreeNode; public class MinDepth { static class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public int minDepth(TreeNode root) { int min = 0; if (root == null) { return min; } Queue<TreeNode> q = new LinkedList<TreeNode>(); q.add(root); int count = 0; while (!q.isEmpty()) { count = q.size(); int i = 0; min++; while (i < count) { TreeNode node = q.poll(); if (node.left == null && node.right == null) { return min; } if (node.left != null) { q.add(node.left); } if (node.right != null) { q.add(node.right); } i++; } } return min; } public int minDepth2(TreeNode root) { if (root == null) return 0; int left = minDepth(root.left); int right = minDepth(root.right); return (left == 0 || right == 0) ? left + right + 1 : Math.min(left, right) + 1; } public static void main(String[] args) { // TODO Auto-generated method stub } }
package com.basic.view.add; import com.basic.dao.impl.GrpDao; import com.basic.db.FGrp; import com.basic.entity.Grp; import com.basic.lang.LGrp; import com.basic.lang.LUsr; import com.global.App; import com.global.DataUser; import com.global.Focus; import com.global.util.Validate; import com.jgoodies.forms.layout.FormLayout; import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; import org.basic.comp.abst.AddPanelAbs; import org.basic.comp.abst.FormBuilder; import org.basic.comp.base.TextArea; import org.basic.comp.base.TextField; import java.util.Date; public class JenisPekerjaanDN extends AddPanelAbs { protected TextField code; protected TextField name; protected TextArea note; @Override public void actionReset() { code.setText("Auto"); name.setText(""); note.setText(""); requestDefaultFocus(); } @Override public void requestDefaultFocus() { name.requestFocus(); } public void init() { super.init(); code = new TextField(); name = new TextField(); note = new TextArea(); } @Override public void build(ODatabaseDocumentTx db) { StringBuilder col=new StringBuilder(); StringBuilder row=new StringBuilder(); col.append("30px,"); col.append("r:p,10px,f:400px:g,"); col.append("30px,"); row.append("15dlu,"); row.append("p,3dlu,"); row.append("p,3dlu,"); row.append("f:40dlu:g,15dlu,"); FormLayout l = new FormLayout(col.toString(),row.toString()); //l.setColumnGroups(new int[][] { { 4, 8 } }); FormBuilder b = new FormBuilder(l); //append(String i8n, Component c, int x, int y, int w) b.append(LGrp.CODE, code, 2, 2, 1); b.append(LGrp.NAME, name, 2, 4, 1); b.append(LGrp.NOTE, snote, 2, 6, 1); panelForm=b.getPanel(); Focus.enter(code, name); Focus.enter(name, note); Focus.enter(note, save); Focus.enter(save, code); super.build(db); } @Override public void save(ODatabaseDocumentTx db) { GrpDao d=App.getGrpDao(); Grp g=new Grp(); g.setCode(code.getText()); g.setName(name.getText()); g.setNote(note.getText()); g.setCreateAt(new Date()); g.setCreateBy(DataUser.getUsr()); d.save(db, g.getDoc()); } @Override public boolean validate(ODatabaseDocumentTx db) { GrpDao d=App.getGrpDao(); if (!Validate.validateStringEmpty(code, LUsr.CODE)) { return false; } if (!Validate.validateStringEmpty(name, LUsr.NAMA)) { return false; } if (!Validate.validateUnique(db, d, code, LGrp.CODE, FGrp.CODE)) { return false; } if (!Validate.validateUnique(db, d, code, LGrp.NAME, FGrp.NAME)) { return false; } return true; } }
package com.xiaoxiao.service.backend.impl; import com.xiaoxiao.mapper.ImgMapper; import com.xiaoxiao.pojo.XiaoxiaoImg; import com.xiaoxiao.service.backend.TinyImgService; import com.xiaoxiao.utils.IDUtils; import com.xiaoxiao.utils.Result; import com.xiaoxiao.utils.StatusCode; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; /** * _ooOoo_ * o8888888o * 88" . "88 * (| -_- |) * O\ = /O * ____/`---'\____ * .' \\| |// `. * / \\||| : |||// \ * / _||||| -:- |||||- \ * | | \\\ - /// | | * | \_| ''\---/'' | | * \ .-\__ `-` ___/-. / * ___`. .' /--.--\ `. . __ * ."" '< `.___\_<|>_/___.' >'"". * | | : `- \`.;`\ _ /`;.`/ - ` : | | * \ \ `-. \_ __\ /__ _/ .-` / / * ======`-.____`-.___\_____/___.-`____.-'====== * `=---=' * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ * 佛祖保佑 永无BUG * 佛曰: * 写字楼里写字间,写字间里程序员; * 程序人员写程序,又拿程序换酒钱。 * 酒醒只在网上坐,酒醉还来网下眠; * 酒醉酒醒日复日,网上网下年复年。 * 但愿老死电脑间,不愿鞠躬老板前; * 奔驰宝马贵者趣,公交自行程序员。 * 别人笑我忒疯癫,我笑自己命太贱; * 不见满街漂亮妹,哪个归得程序员? * * @project_name:xiaoxiao_final_blogs * @date:2019/12/1:17:58 * @author:shinelon * @Describe: */ @Service public class TinyImgServiceImpl implements TinyImgService { @Autowired private ImgMapper imgMapper; @Value("${MARKED_WORDS_SUCCESS}") private String MARKED_WORDS_SUCCESS; @Value("${MARKED_WORDS_FAULT}") private String MARKED_WORDS_FAULT; /** * 插入 * @param img * @return */ @Override public Result insert(XiaoxiaoImg img) { img.setImgId(IDUtils.getUUID()); if (imgMapper.insert(img) > 0) { return Result.ok(StatusCode.OK, MARKED_WORDS_SUCCESS); } return Result.error(StatusCode.ERROR, this.MARKED_WORDS_FAULT); } /** * 修改 * @param img * @return */ @Override public Result update(XiaoxiaoImg img) { return null; } /** * 删除 * @param imgId * @return */ @Override public Result delete(String imgId) { return null; } /** * 查找一个的 * @param imgId * @return */ @Override public Result findImgById(String imgId) { return null; } /** * 查找全部 * @param page * @param rows * @return */ @Override public Result findAll(Integer page, Integer rows) { return null; } }
package prj.betfair.api.betting.datatypes; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import prj.betfair.api.betting.datatypes.MarketBook; import prj.betfair.api.betting.datatypes.Runner; import java.util.List; import java.util.Date; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; /*** * The dynamic data in a market */ @JsonDeserialize(builder = MarketBook.Builder.class) @JsonIgnoreProperties(ignoreUnknown = true) public class MarketBook { private final String status; private final boolean isMarketDataDelayed; private final int numberOfRunners; private final boolean complete; private final Boolean bspReconciled; private final boolean runnersVoidable; private final int betDelay; private final String marketId; private final boolean crossMatching; private final double totalMatched; private final long version; private final Date lastMatchTime; private final int numberOfWinners; private final boolean inplay; private final int numberOfActiveRunners; private final double totalAvailable; private final List<Runner> runners; public MarketBook(Builder builder) { this.status = builder.status; this.isMarketDataDelayed = builder.isMarketDataDelayed; this.numberOfRunners = builder.numberOfRunners; this.complete = builder.complete; this.bspReconciled = builder.bspReconciled; this.runnersVoidable = builder.runnersVoidable; this.betDelay = builder.betDelay; this.marketId = builder.marketId; this.crossMatching = builder.crossMatching; this.totalMatched = builder.totalMatched; this.version = builder.version; this.lastMatchTime = builder.lastMatchTime; this.numberOfWinners = builder.numberOfWinners; this.inplay = builder.inplay; this.numberOfActiveRunners = builder.numberOfActiveRunners; this.totalAvailable = builder.totalAvailable; this.runners = builder.runners; } /** * @return marketId The unique identifier for the market */ public String getMarketId() { return this.marketId; } /** * @return isMarketDataDelayed True if the data returned by listMarketBook will be delayed. The * data may be delayed because you are not logged in with a funded account or you are * using an Application Key that does not allow up to date data. */ public boolean getIsMarketDataDelayed() { return this.isMarketDataDelayed; } /** * @return status The status of the market, for example ACTIVE, SUSPENDED, SETTLED, etc. */ public String getStatus() { return this.status; } /** * @return betDelay The number of seconds an order is held until it is submitted into the market. * Orders are usually delayed when the market is in-play */ public int getBetDelay() { return this.betDelay; } /** * @return bspReconciled True if the market starting price has been reconciled */ public boolean getBspReconciled() { return this.bspReconciled; } /** * @return complete */ public boolean getComplete() { return this.complete; } /** * @return inplay True if the market is currently in play */ public boolean getInplay() { return this.inplay; } /** * @return numberOfWinners The number of selections that could be settled as winners */ public int getNumberOfWinners() { return this.numberOfWinners; } /** * @return numberOfRunners The number of runners in the market */ public int getNumberOfRunners() { return this.numberOfRunners; } /** * @return numberOfActiveRunners The number of runners that are currently active. An active runner * is a selection available for betting */ public int getNumberOfActiveRunners() { return this.numberOfActiveRunners; } /** * @return lastMatchTime The most recent time an order was executed */ public Date getLastMatchTime() { return this.lastMatchTime; } /** * @return totalMatched The total amount matched. This value is truncated at 2dp. */ public double getTotalMatched() { return this.totalMatched; } /** * @return totalAvailable The total amount of orders that remain unmatched. This value is * truncated at 2dp. */ public double getTotalAvailable() { return this.totalAvailable; } /** * @return crossMatching True if cross matching is enabled for this market. */ public boolean getCrossMatching() { return this.crossMatching; } /** * @return runnersVoidable True if runners in the market can be voided */ public boolean getRunnersVoidable() { return this.runnersVoidable; } /** * @return version The version of the market. The version increments whenever the market status * changes, for example, turning in-play, or suspended when a goal score. */ public long getVersion() { return this.version; } /** * @return runners Information about the runners (selections) in the market. */ public List<Runner> getRunners() { return this.runners; } @JsonIgnoreProperties(ignoreUnknown = true) public static class Builder { private String status; private boolean isMarketDataDelayed; private int numberOfRunners; private boolean complete; private Boolean bspReconciled; private boolean runnersVoidable; private int betDelay; private String marketId; private boolean crossMatching; private double totalMatched; private long version; private Date lastMatchTime; private int numberOfWinners; private boolean inplay; private int numberOfActiveRunners; private double totalAvailable; private List<Runner> runners; /** * @param isMarketDataDelayed : True if the data returned by listMarketBook will be delayed. The * data may be delayed because you are not logged in with a funded account or you are * using an Application Key that does not allow up to date data. * @param marketId : The unique identifier for the market */ public Builder(@JsonProperty("isMarketDataDelayed") boolean isMarketDataDelayed, @JsonProperty("marketId") String marketId) { this.isMarketDataDelayed = isMarketDataDelayed; this.marketId = marketId; } /** * Use this function to set status * * @param status The status of the market, for example ACTIVE, SUSPENDED, SETTLED, etc. * @return Builder */ public Builder withStatus(String status) { this.status = status; return this; } /** * Use this function to set betDelay * * @param betDelay The number of seconds an order is held until it is submitted into the market. * Orders are usually delayed when the market is in-play * @return Builder */ public Builder withBetDelay(int betDelay) { this.betDelay = betDelay; return this; } /** * Use this function to set bspReconciled * * @param bspReconciled True if the market starting price has been reconciled * @return Builder */ public Builder withBspReconciled(boolean bspReconciled) { this.bspReconciled = bspReconciled; return this; } /** * Use this function to set complete * * @param complete * @return Builder */ public Builder withComplete(boolean complete) { this.complete = complete; return this; } /** * Use this function to set inplay * * @param inplay True if the market is currently in play * @return Builder */ public Builder withInplay(boolean inplay) { this.inplay = inplay; return this; } /** * Use this function to set numberOfWinners * * @param numberOfWinners The number of selections that could be settled as winners * @return Builder */ public Builder withNumberOfWinners(int numberOfWinners) { this.numberOfWinners = numberOfWinners; return this; } /** * Use this function to set numberOfRunners * * @param numberOfRunners The number of runners in the market * @return Builder */ public Builder withNumberOfRunners(int numberOfRunners) { this.numberOfRunners = numberOfRunners; return this; } /** * Use this function to set numberOfActiveRunners * * @param numberOfActiveRunners The number of runners that are currently active. An active * runner is a selection available for betting * @return Builder */ public Builder withNumberOfActiveRunners(int numberOfActiveRunners) { this.numberOfActiveRunners = numberOfActiveRunners; return this; } /** * Use this function to set lastMatchTime * * @param lastMatchTime The most recent time an order was executed * @return Builder */ public Builder withLastMatchTime(Date lastMatchTime) { this.lastMatchTime = lastMatchTime; return this; } /** * Use this function to set totalMatched * * @param totalMatched The total amount matched. This value is truncated at 2dp. * @return Builder */ public Builder withTotalMatched(double totalMatched) { this.totalMatched = totalMatched; return this; } /** * Use this function to set totalAvailable * * @param totalAvailable The total amount of orders that remain unmatched. This value is * truncated at 2dp. * @return Builder */ public Builder withTotalAvailable(double totalAvailable) { this.totalAvailable = totalAvailable; return this; } /** * Use this function to set crossMatching * * @param crossMatching True if cross matching is enabled for this market. * @return Builder */ public Builder withCrossMatching(boolean crossMatching) { this.crossMatching = crossMatching; return this; } /** * Use this function to set runnersVoidable * * @param runnersVoidable True if runners in the market can be voided * @return Builder */ public Builder withRunnersVoidable(boolean runnersVoidable) { this.runnersVoidable = runnersVoidable; return this; } /** * Use this function to set version * * @param version The version of the market. The version increments whenever the market status * changes, for example, turning in-play, or suspended when a goal score. * @return Builder */ public Builder withVersion(long version) { this.version = version; return this; } /** * Use this function to set runners * * @param runners Information about the runners (selections) in the market. * @return Builder */ public Builder withRunners(List<Runner> runners) { this.runners = runners; return this; } public MarketBook build() { return new MarketBook(this); } } }
package practica6; import java.awt.Dimension; import java.awt.Graphics; import java.awt.image.BufferedImage; import javax.swing.JPanel; /* * 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. */ /** * * @author Cristian */ public class VisualizadorFoto extends JPanel{ static BufferedImage imagen; public VisualizadorFoto(){ } public void setImagen(BufferedImage imagen) { this.imagen = imagen; setPreferredSize(new Dimension(imagen.getWidth(), imagen.getHeight())); revalidate(); } @Override public void paintComponent(Graphics g){ super.paintComponent(g); g.drawImage(imagen, 0, 0, null); } }
public class ASCII_2 { public static void main (String[]args) { System.out.println(" _"); System.out.println("( \\"); System.out.println(" ) )"); System.out.println("( ( .-****-. A.-.A"); System.out.println("\\ \\/ \\/ , , \\"); System.out.println(" \\ \\ =; t /="); System.out.println(" \\ |****. ' ,--."); System.out.println(" / / / | | |"); System.out.println(" / _ ,) ) | _,) )"); } }
public class aresta { private int peso; private vertices origem; private vertices destino; public aresta(vertices v1, vertices v2) { this.peso = 1; this.origem = v1; this.destino = v2; v1.getArestas().add(this); } public void setPeso(int novoPeso) { this.peso = novoPeso; } public int getPeso() { return peso; } public void setDestino(vertices destino) { this.destino = destino; } public vertices getDestino() { return destino; } public void setOrigem(vertices origem) { this.origem = origem; } public vertices getOrigem() { return origem; } }
package notaria; import java.sql.Connection; import java.sql.Statement; /** * PROG11_Tarea: * @see resources.Especificaciones.pdf * @Author Luis Calvo Martín * Elimina las tablas */ public class EliminaTabla { @SuppressWarnings("ConvertToTryWithResources") public void borrar () { ConexionMysql mysql = new ConexionMysql(); Connection conn = mysql.Conectar(); try { Statement s = conn.createStatement (); //sentencias para elminar las tablas de la base de datos s.executeUpdate("DROP TABLE escCli"); s.executeUpdate("DROP TABLE clientes"); s.executeUpdate("DROP TABLE escrituras"); s.close (); System.out.println ("\n *** Tablas eliminadas ***"); }catch (Exception e) { System.err.println ("Error al intentar borrar las tablas. "); } finally { if (conn != null) try { conn.close (); }catch (Exception e) { /* sin mensajes de error */ } } } }
package com.bowlong.third.netty3; import java.io.IOException; import org.jboss.netty.buffer.ChannelBuffer; import com.bowlong.bio2.B2Type; import com.bowlong.util.NewList; import com.bowlong.util.NewMap; @SuppressWarnings({ "rawtypes", "unchecked" }) public class N3B2InputStream { public static final int readInt(ChannelBuffer is) throws IOException { byte tag = (byte) is.readByte(); switch (tag) { case B2Type.INT_N1: return -1; case B2Type.INT_0: return 0; case B2Type.INT_1: return 1; case B2Type.INT_2: return 2; case B2Type.INT_3: return 3; case B2Type.INT_4: return 4; case B2Type.INT_5: return 5; case B2Type.INT_6: return 6; case B2Type.INT_7: return 7; case B2Type.INT_8: return 8; case B2Type.INT_9: return 9; case B2Type.INT_10: return 10; case B2Type.INT_11: return 11; case B2Type.INT_12: return 12; case B2Type.INT_13: return 13; case B2Type.INT_14: return 14; case B2Type.INT_15: return 15; case B2Type.INT_16: return 16; case B2Type.INT_17: return 17; case B2Type.INT_18: return 18; case B2Type.INT_19: return 19; case B2Type.INT_20: return 20; case B2Type.INT_21: return 21; case B2Type.INT_22: return 22; case B2Type.INT_23: return 23; case B2Type.INT_24: return 24; case B2Type.INT_25: return 25; case B2Type.INT_26: return 26; case B2Type.INT_27: return 27; case B2Type.INT_28: return 28; case B2Type.INT_29: return 29; case B2Type.INT_30: return 30; case B2Type.INT_31: return 31; case B2Type.INT_32: return 32; case B2Type.INT_8B: { byte v = (byte) is.readByte(); return v; } case B2Type.INT_16B: { short v = (short) (((is.readByte() & 0xff) << 8) + ((is.readByte() & 0xff) << 0)); return v; } case B2Type.INT_32B: { int value1 = is.readByte(); int value2 = is.readByte(); int value3 = is.readByte(); int value4 = is.readByte(); int v = ((value1 & 0xff) << 24) + ((value2 & 0xff) << 16) + ((value3 & 0xff) << 8) + ((value4 & 0xff) << 0); return v; } default: throw new IOException("read int tag error:" + tag); } } private static final int[] readIntArray(ChannelBuffer is, int len) throws Exception { int[] ret = new int[len]; for (int i = 0; i < len; i++) { int v = readInt(is); ret[i] = v; } return ret; } private static final int[][] readInt2DArray(ChannelBuffer is, int len) throws Exception { int[][] ret = new int[len][]; for (int i = 0; i < len; i++) { Object o = readObject(is); int[] v = (int[]) o; ret[i] = v; } return ret; } private static final NewList readList(ChannelBuffer is, int len) throws Exception { NewList ret = new NewList(); for (int i = 0; i < len; i++) { Object o = readObject(is); // ret.addElement(o); ret.add(o); } return ret; } private static final NewMap readMap(ChannelBuffer is, int len) throws Exception { NewMap ret = new NewMap(); for (int i = 0; i < len; i++) { Object key = readObject(is); Object var = readObject(is); ret.put(key, var); } return ret; } public static final Object readObject(ChannelBuffer is) throws Exception { byte tag = (byte) is.readByte(); switch (tag) { case B2Type.NULL: { return null; } case B2Type.HASHTABLE_0: { return new NewMap(); } case B2Type.HASHTABLE_1: { return readMap(is, 1); } case B2Type.HASHTABLE_2: { return readMap(is, 2); } case B2Type.HASHTABLE_3: { return readMap(is, 3); } case B2Type.HASHTABLE_4: { return readMap(is, 4); } case B2Type.HASHTABLE_5: { return readMap(is, 5); } case B2Type.HASHTABLE_6: { return readMap(is, 6); } case B2Type.HASHTABLE_7: { return readMap(is, 7); } case B2Type.HASHTABLE_8: { return readMap(is, 8); } case B2Type.HASHTABLE_9: { return readMap(is, 9); } case B2Type.HASHTABLE_10: { return readMap(is, 10); } case B2Type.HASHTABLE_11: { return readMap(is, 11); } case B2Type.HASHTABLE_12: { return readMap(is, 12); } case B2Type.HASHTABLE_13: { return readMap(is, 13); } case B2Type.HASHTABLE_14: { return readMap(is, 14); } case B2Type.HASHTABLE_15: { return readMap(is, 15); } case B2Type.HASHTABLE: { int len = readInt(is); return readMap(is, len); } case B2Type.INT_N1: { return new Integer(-1); } case B2Type.INT_0: { return new Integer(0); } case B2Type.INT_1: { return new Integer(1); } case B2Type.INT_2: { return new Integer(2); } case B2Type.INT_3: { return new Integer(3); } case B2Type.INT_4: { return new Integer(4); } case B2Type.INT_5: { return new Integer(5); } case B2Type.INT_6: { return new Integer(6); } case B2Type.INT_7: { return new Integer(7); } case B2Type.INT_8: { return new Integer(8); } case B2Type.INT_9: { return new Integer(9); } case B2Type.INT_10: { return new Integer(10); } case B2Type.INT_11: { return new Integer(11); } case B2Type.INT_12: { return new Integer(12); } case B2Type.INT_13: { return new Integer(13); } case B2Type.INT_14: { return new Integer(14); } case B2Type.INT_15: { return new Integer(15); } case B2Type.INT_16: { return new Integer(16); } case B2Type.INT_17: { return new Integer(17); } case B2Type.INT_18: { return new Integer(18); } case B2Type.INT_19: { return new Integer(19); } case B2Type.INT_20: { return new Integer(20); } case B2Type.INT_21: { return new Integer(21); } case B2Type.INT_22: { return new Integer(22); } case B2Type.INT_23: { return new Integer(23); } case B2Type.INT_24: { return new Integer(24); } case B2Type.INT_25: { return new Integer(25); } case B2Type.INT_26: { return new Integer(26); } case B2Type.INT_27: { return new Integer(27); } case B2Type.INT_28: { return new Integer(28); } case B2Type.INT_29: { return new Integer(29); } case B2Type.INT_30: { return new Integer(30); } case B2Type.INT_31: { return new Integer(31); } case B2Type.INT_32: { return new Integer(32); } case B2Type.INT_8B: { byte v = (byte) is.readByte(); return new Integer(v); } case B2Type.INT_16B: { short v = (short) (((is.readByte() & 0xff) << 8) + ((is.readByte() & 0xff) << 0)); return new Integer(v); } case B2Type.INT_32B: { int v1 = is.readByte(); int v2 = is.readByte(); int v3 = is.readByte(); int v4 = is.readByte(); int v = ((v1 & 0xff) << 24) + ((v2 & 0xff) << 16) + ((v3 & 0xff) << 8) + ((v4 & 0xff) << 0); return new Integer(v); } case B2Type.STR_0: { return ""; } case B2Type.STR_1: { return readStringImpl(is, 1); } case B2Type.STR_2: { return readStringImpl(is, 2); } case B2Type.STR_3: { return readStringImpl(is, 3); } case B2Type.STR_4: { return readStringImpl(is, 4); } case B2Type.STR_5: { return readStringImpl(is, 5); } case B2Type.STR_6: { return readStringImpl(is, 6); } case B2Type.STR_7: { return readStringImpl(is, 7); } case B2Type.STR_8: { return readStringImpl(is, 8); } case B2Type.STR_9: { return readStringImpl(is, 9); } case B2Type.STR_10: { return readStringImpl(is, 10); } case B2Type.STR_11: { return readStringImpl(is, 11); } case B2Type.STR_12: { return readStringImpl(is, 12); } case B2Type.STR_13: { return readStringImpl(is, 13); } case B2Type.STR_14: { return readStringImpl(is, 14); } case B2Type.STR_15: { return readStringImpl(is, 15); } case B2Type.STR_16: { return readStringImpl(is, 16); } case B2Type.STR_17: { return readStringImpl(is, 17); } case B2Type.STR_18: { return readStringImpl(is, 18); } case B2Type.STR_19: { return readStringImpl(is, 19); } case B2Type.STR_20: { return readStringImpl(is, 20); } case B2Type.STR_21: { return readStringImpl(is, 21); } case B2Type.STR_22: { return readStringImpl(is, 22); } case B2Type.STR_23: { return readStringImpl(is, 23); } case B2Type.STR_24: { return readStringImpl(is, 24); } case B2Type.STR_25: { return readStringImpl(is, 25); } case B2Type.STR_26: { return readStringImpl(is, 26); } case B2Type.STR: { int len = readInt(is); return readStringImpl(is, len); } case B2Type.BOOLEAN_TRUE: { return new Boolean(true); } case B2Type.BOOLEAN_FALSE: { return new Boolean(false); } case B2Type.BYTE_0: { byte v = 0; return new Byte(v); } case B2Type.BYTE: { byte v = (byte) is.readByte(); return new Byte(v); } case B2Type.BYTES_0: { return new byte[0]; } case B2Type.BYTES: { int len = readInt(is); return is.readBytes(len); } case B2Type.VECTOR_0: { return new NewList(); } case B2Type.VECTOR_1: { return readList(is, 1); } case B2Type.VECTOR_2: { return readList(is, 2); } case B2Type.VECTOR_3: { return readList(is, 3); } case B2Type.VECTOR_4: { return readList(is, 4); } case B2Type.VECTOR_5: { return readList(is, 5); } case B2Type.VECTOR_6: { return readList(is, 6); } case B2Type.VECTOR_7: { return readList(is, 7); } case B2Type.VECTOR_8: { return readList(is, 8); } case B2Type.VECTOR_9: { return readList(is, 9); } case B2Type.VECTOR_10: { return readList(is, 10); } case B2Type.VECTOR_11: { return readList(is, 11); } case B2Type.VECTOR_12: { return readList(is, 12); } case B2Type.VECTOR_13: { return readList(is, 13); } case B2Type.VECTOR_14: { return readList(is, 14); } case B2Type.VECTOR_15: { return readList(is, 15); } case B2Type.VECTOR_16: { return readList(is, 16); } case B2Type.VECTOR_17: { return readList(is, 17); } case B2Type.VECTOR_18: { return readList(is, 18); } case B2Type.VECTOR_19: { return readList(is, 19); } case B2Type.VECTOR_20: { return readList(is, 20); } case B2Type.VECTOR_21: { return readList(is, 21); } case B2Type.VECTOR_22: { return readList(is, 22); } case B2Type.VECTOR_23: { return readList(is, 23); } case B2Type.VECTOR_24: { return readList(is, 24); } case B2Type.VECTOR: { int len = readInt(is); return readList(is, len); } case B2Type.SHORT_0: { short v = 0; return new Short(v); } case B2Type.SHORT_8B: { short v = (short) is.readByte(); return new Short(v); } case B2Type.SHORT_16B: { short v = (short) (((is.readByte() & 0xff) << 8) + ((is.readByte() & 0xff) << 0)); return new Short(v); } case B2Type.LONG_0: { int v = 0; return new Long(v); } case B2Type.LONG_8B: { int v = is.readByte(); return new Long(v); } case B2Type.LONG_16B: { int v = (((is.readByte() & 0xff) << 8) + ((is.readByte() & 0xff) << 0)); return new Long(v); } case B2Type.LONG_32B: { int v1 = is.readByte(); int v2 = is.readByte(); int v3 = is.readByte(); int v4 = is.readByte(); int v = ((v1 & 0xff) << 24) + ((v2 & 0xff) << 16) + ((v3 & 0xff) << 8) + ((v4 & 0xff) << 0); return new Long(v); } case B2Type.LONG_64B: { byte[] b = new byte[8]; for (int i = 0; i < 8; i++) { b[i] = (byte) is.readByte(); } long high = ((b[0] & 0xff) << 24) + ((b[1] & 0xff) << 16) + ((b[2] & 0xff) << 8) + ((b[3] & 0xff) << 0); long low = ((b[4] & 0xff) << 24) + ((b[5] & 0xff) << 16) + ((b[6] & 0xff) << 8) + ((b[7] & 0xff) << 0); long v = (high << 32) + (0xffffffffL & low); return new Long(v); } case B2Type.JAVA_DATE: { byte[] b = new byte[8]; for (int i = 0; i < 8; i++) { b[i] = (byte) is.readByte(); } long high = ((b[0] & 0xff) << 24) + ((b[1] & 0xff) << 16) + ((b[2] & 0xff) << 8) + ((b[3] & 0xff) << 0); long low = ((b[4] & 0xff) << 24) + ((b[5] & 0xff) << 16) + ((b[6] & 0xff) << 8) + ((b[7] & 0xff) << 0); long v = (high << 32) + (0xffffffffL & low); return new java.util.Date(v); } case B2Type.DOUBLE_0: { // int v = 0; // double ret = Double.longBitsToDouble(v); return new Double(0); // }case B2Type.DOUBLE_8B: { // int v = is.readByte(); // double ret = Double.longBitsToDouble(v); // return new Double(ret); // }case B2Type.DOUBLE_16B: { // int v = (((is.readByte() & 0xff) << 8) + ((is.readByte() & 0xff) // << 0)); // double ret = Double.longBitsToDouble(v); // return new Double(ret); // }case B2Type.DOUBLE_32B: { // int v1 = is.readByte(); // int v2 = is.readByte(); // int v3 = is.readByte(); // int v4 = is.readByte(); // // int v = ((v1 & 0xff) << 24) + ((v2 & 0xff) << 16) // + ((v3 & 0xff) << 8) + ((v4 & 0xff) << 0); // double ret = Double.longBitsToDouble(v); // return new Double(ret); } case B2Type.DOUBLE_64B: { byte[] b = new byte[8]; for (int i = 0; i < 8; i++) { b[i] = (byte) is.readByte(); } long high = ((b[0] & 0xff) << 24) + ((b[1] & 0xff) << 16) + ((b[2] & 0xff) << 8) + ((b[3] & 0xff) << 0); long low = ((b[4] & 0xff) << 24) + ((b[5] & 0xff) << 16) + ((b[6] & 0xff) << 8) + ((b[7] & 0xff) << 0); long v = (high << 32) + (0xffffffffL & low); double ret = Double.longBitsToDouble(v); return new Double(ret); } case B2Type.INT_ARRAY_0: { return new int[0]; } case B2Type.INT_ARRAY_1: { return readIntArray(is, 1); } case B2Type.INT_ARRAY_2: { return readIntArray(is, 2); } case B2Type.INT_ARRAY_3: { return readIntArray(is, 3); } case B2Type.INT_ARRAY_4: { return readIntArray(is, 4); } case B2Type.INT_ARRAY_5: { return readIntArray(is, 5); } case B2Type.INT_ARRAY_6: { return readIntArray(is, 6); } case B2Type.INT_ARRAY_7: { return readIntArray(is, 7); } case B2Type.INT_ARRAY_8: { return readIntArray(is, 8); } case B2Type.INT_ARRAY_9: { return readIntArray(is, 9); } case B2Type.INT_ARRAY_10: { return readIntArray(is, 10); } case B2Type.INT_ARRAY_11: { return readIntArray(is, 11); } case B2Type.INT_ARRAY_12: { return readIntArray(is, 12); } case B2Type.INT_ARRAY_13: { return readIntArray(is, 13); } case B2Type.INT_ARRAY_14: { return readIntArray(is, 14); } case B2Type.INT_ARRAY_15: { return readIntArray(is, 15); } case B2Type.INT_ARRAY_16: { return readIntArray(is, 16); } case B2Type.INT_ARRAY: { int len = readInt(is); return readIntArray(is, len); } case B2Type.INT_2D_ARRAY_0: { return new int[0][0]; } case B2Type.INT_2D_ARRAY: { int len = readInt(is); return readInt2DArray(is, len); } default: throw new IOException("unknow tag error:" + tag); } } // ////////////////////////////////// private static final String readStringImpl(ChannelBuffer is, int length) throws IOException { if (length <= 0) return ""; byte[] b = new byte[length]; is.readBytes(b); return new String(b, B2Type.UTF8); } // private static final String readStringImpl(ChannelBuffer is, int length) // throws IOException { // StringBuffer sb = new StringBuffer(); // // for (int i = 0; i < length; i++) { // int ch = is.readByte(); // // if (ch < 0x80) // sb.append((char) ch); // else if ((ch & 0xe0) == 0xc0) { // int ch1 = is.readByte(); // int v = ((ch & 0x1f) << 6) + (ch1 & 0x3f); // // sb.append((char) v); // } else if ((ch & 0xf0) == 0xe0) { // int ch1 = is.readByte(); // int ch2 = is.readByte(); // int v = ((ch & 0x0f) << 12) + ((ch1 & 0x3f) << 6) // + (ch2 & 0x3f); // // sb.append((char) v); // } else // throw new IOException("bad utf-8 encoding"); // } // // return sb.toString(); // } public static NewMap readNewMap(ChannelBuffer is) throws Exception { byte tag = (byte) is.readByte(); switch (tag) { case B2Type.NULL: { return null; } case B2Type.HASHTABLE_0: { return new NewMap(); } case B2Type.HASHTABLE_1: { return readNewMap(is, 1); } case B2Type.HASHTABLE_2: { return readNewMap(is, 2); } case B2Type.HASHTABLE_3: { return readNewMap(is, 3); } case B2Type.HASHTABLE_4: { return readNewMap(is, 4); } case B2Type.HASHTABLE_5: { return readNewMap(is, 5); } case B2Type.HASHTABLE_6: { return readNewMap(is, 6); } case B2Type.HASHTABLE_7: { return readNewMap(is, 7); } case B2Type.HASHTABLE_8: { return readNewMap(is, 8); } case B2Type.HASHTABLE_9: { return readNewMap(is, 9); } case B2Type.HASHTABLE_10: { return readNewMap(is, 10); } case B2Type.HASHTABLE_11: { return readNewMap(is, 11); } case B2Type.HASHTABLE_12: { return readNewMap(is, 12); } case B2Type.HASHTABLE_13: { return readNewMap(is, 13); } case B2Type.HASHTABLE_14: { return readNewMap(is, 14); } case B2Type.HASHTABLE_15: { return readNewMap(is, 15); } case B2Type.HASHTABLE: { int len = readInt(is); return readNewMap(is, len); } default: throw new IOException("unknow tag error:" + tag + " readerIndex:" + is.readerIndex()); } } private static NewMap readNewMap(ChannelBuffer is, int len) throws Exception { NewMap ret = new NewMap(); for (int i = 0; i < len; i++) { Object key = readObject(is); Object var = readObject(is); ret.put(key, var); } return ret; } }
public class Variables { public static void main(String[] args) { // CHANGE THESE: int dividend = 3; int divisor = 2; double quotient = (double)dividend / divisor * 1.0; System.out.println(quotient); } }
package com.tencent.mm.storage; public final class av { public static final av tbm = new av("timeline"); public static final av tbn = new av("album_friend"); public static final av tbo = new av("album_self"); public static final av tbp = new av("album_stranger"); public static final av tbq = new av("profile_friend"); public static final av tbr = new av("profile_stranger"); public static final av tbs = new av("comment"); public static final av tbt = new av("comment_detail"); public static final av tbu = new av("other"); public static final av tbv = new av("snssight"); public static final av tbw = new av("fts"); public String tag = ""; public int time = 0; public static av clT() { return new av("timeline"); } public static av clU() { return new av("album_friend"); } public static av clV() { return new av("album_self"); } public static av clW() { return new av("album_stranger"); } public static av clX() { return new av("comment_detail"); } public static av clY() { return new av("snssight"); } public av(String str) { this.tag = str; } public final av Dm(int i) { this.time = i; return this; } public static av a(av avVar, int i) { av avVar2 = new av(avVar.tag); avVar2.time = i; return avVar2; } public final boolean equals(Object obj) { if (obj instanceof av) { return ((av) obj).tag.equals(this.tag); } return super.equals(obj); } public final String toString() { return this.tag + "@" + this.time; } }
package de.zarncke.lib.io.store; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import de.zarncke.lib.data.HasData; /** * Something which can possibly be read and written streamwise. * * @author Gunnar Zarncke */ public interface Accessible extends HasData { /** * Returned by {@link #getSize()} when the size is unknown. ={@value #UNKNOWN_SIZE}. */ long UNKNOWN_SIZE = -1; long getSize(); boolean canRead(); InputStream getInputStream() throws IOException; boolean canWrite(); OutputStream getOutputStream(boolean append) throws IOException; }
/*import java.util.Scanner;*/ class IntOps { public static void main(String[] args) { /* Scanner s = new Scanner(System.in); int a = s.nextInt(); int b = s.nextInt(); System.out.println(a + " * " + b + " = " + (a * b)); System.out.println(a + " / " + b + " = " + (a / b)); System.out.println(a + " % " + b + " = " + (a % b)); double aD = a; double d = aD / b; System.out.println(d); }*/ System.out.println("Kerek ket egesz szamot!"); int a = Integer.parseInt(System.console().readLine()); int b = Integer.parseInt(System.console().readLine()); System.out.println(a + " * " + b + " = " + a * b); if (b != 0) { System.out.println(a + " / " + b + " = " + a / b); System.out.println(a + " % " + b + " = " + a % b); System.out.println(a + " = " + b + " * " + a / b + " + " + a % b); } }
package banco; import com.mysql.jdbc.jdbc2.optional.MysqlDataSource; import java.sql.Connection; import java.sql.SQLException; //Criando conexão com banco de dados public class ConexaoBanco { private Connection con = null; private final String BANCO = "imobiliaria"; private final String LOGIN = "root"; private final String SENHA = ""; private final String HOST = "localhost"; public Connection getConnection() { //instaciando o try catch try { MysqlDataSource mds = new MysqlDataSource(); mds.setServerName(HOST); mds.setDatabaseName(BANCO); mds.setUser(LOGIN); mds.setPassword(SENHA); mds.setConnectTimeout(2000); con = mds.getConnection(); System.out.println("Conectado ao Banco de Dados!"); return con; } catch (SQLException ex) { System.out.println("Falha de conexão" + ex.getMessage()); return null; } } }
/* * 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 ventanapruebatiempo; import java.awt.Container; import java.awt.FlowLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JTextField; /** * * @author Julia Ramos Lopez */ public class Ventanapruebatiempo extends JFrame { private Tiempo tiempo; private JLabel horaEtiqueta,minutoEtiqueta,segundoEtiqueta; private JTextField horaCampo,minutoCampo,segundoCampo,pantallaCampo; private JButton salirBoton; public Ventanapruebatiempo(){ super("Demostración de clase interna"); tiempo=new Tiempo(); Container contenedor =getContentPane(); contenedor.setLayout (new FlowLayout()); horaEtiqueta=new JLabel("Ajuste hora"); horaCampo=new JTextField(10); contenedor.add(horaEtiqueta); contenedor.add(horaCampo); minutoEtiqueta=new JLabel("Ajuste minuto"); minutoCampo=new JTextField(10); contenedor.add(minutoEtiqueta); contenedor.add(minutoCampo); segundoEtiqueta=new JLabel("Ajuste segundo"); segundoCampo=new JTextField(10); contenedor.add(segundoEtiqueta); contenedor.add(segundoCampo); pantallaCampo=new JTextField(30); pantallaCampo.setEditable(false); contenedor.add(pantallaCampo); salirBoton=new JButton("Salir"); contenedor.add(salirBoton); ActionEventHandler manejador=new ActionEventHandler(); horaCampo.addActionListener(manejador); minutoCampo.addActionListener(manejador); segundoCampo.addActionListener(manejador); salirBoton.addActionListener(manejador); } public void mostrarTiempo(){ pantallaCampo.setText("La hora es:"+tiempo); } public static void main(String[] args) { Ventanapruebatiempo ventana=new Ventanapruebatiempo(); ventana.setSize(400,140); ventana.setVisible(true); } private class ActionEventHandler implements ActionListener{ public void actionPerformed(ActionEvent evento){ if(evento.getSource()==salirBoton){ System.exit(0); } else if(evento.getSource()==horaCampo){ tiempo.establecerHora(Integer.parseInt( evento.getActionCommand())); horaCampo.setText(""); } else if(evento.getSource()== minutoCampo){ tiempo.establecerMinuto(Integer.parseInt( evento.getActionCommand())); minutoCampo.setText(""); } else if(evento.getSource()==segundoCampo){ tiempo.establecerSegundo(Integer.parseInt( evento.getActionCommand())); segundoCampo.setText(""); } mostrarTiempo(); } } }
// ______________________________________________________ // Generated by sql2java - http://sql2java.sourceforge.net/ // jdbc driver used at code generation time: com.mysql.jdbc.Driver // // Please help us improve this tool by reporting: // - problems and suggestions to // http://sourceforge.net/tracker/?group_id=54687 // - feedbacks and ideas on // http://sourceforge.net/forum/forum.php?forum_id=182208 // ______________________________________________________ package legaltime.model; import legaltime.model.exception.DAOException; /** * Listener that is notified of labor_invoice_item table changes. * @author sql2java */ public interface LaborInvoiceItemListener { /** * Invoked just before inserting a LaborInvoiceItemBean record into the database. * * @param bean the LaborInvoiceItemBean that is about to be inserted */ public void beforeInsert(LaborInvoiceItemBean bean) throws DAOException; /** * Invoked just after a LaborInvoiceItemBean record is inserted in the database. * * @param bean the LaborInvoiceItemBean that was just inserted */ public void afterInsert(LaborInvoiceItemBean bean) throws DAOException; /** * Invoked just before updating a LaborInvoiceItemBean record in the database. * * @param bean the LaborInvoiceItemBean that is about to be updated */ public void beforeUpdate(LaborInvoiceItemBean bean) throws DAOException; /** * Invoked just after updating a LaborInvoiceItemBean record in the database. * * @param bean the LaborInvoiceItemBean that was just updated */ public void afterUpdate(LaborInvoiceItemBean bean) throws DAOException; /** * Invoked just before deleting a LaborInvoiceItemBean record in the database. * * @param bean the LaborInvoiceItemBean that is about to be deleted */ public void beforeDelete(LaborInvoiceItemBean bean) throws DAOException; /** * Invoked just after deleting a LaborInvoiceItemBean record in the database. * * @param bean the LaborInvoiceItemBean that was just deleted */ public void afterDelete(LaborInvoiceItemBean bean) throws DAOException; }
package com.hastemd.demo.aop.model.vo; import lombok.Data; import java.io.Serializable; /** * 描述:运单表实体类 * @author lijie * @date Tue Feb 16 14:40:43 CST 2021 */ @Data public class Test implements Serializable { private Integer id; private String name; private Integer age; }
package com.example.testhub.repository; import com.example.testhub.domain.Test; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface TestRepository extends JpaRepository<Test, Long> { List<Test> findAll(); }
package com.mrice.txl.appthree.view.dialog; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import com.mrice.txl.appthree.R; /** * Created by wangchao on 14/11/30. */ public class ThreeRowDialog extends BaseDialog { private View me; private FrameLayout top, middle, bottom; private int topVisibility = -1; public void setTopVisibility(int topVisibility) { this.topVisibility = topVisibility; if(top != null){ top.setVisibility(topVisibility); } } @Override View customView() { if (me != null){ return me; } me = View.inflate(getActivity(), R.layout.ui_threerow_dialog, null); top = (FrameLayout) me.findViewById(R.id.top_container); middle = (FrameLayout) me.findViewById(R.id.middle_container); bottom = (FrameLayout) me.findViewById(R.id.bottom_container); if (background() != 0){ me.setBackgroundResource(background()); } if (topView() != null){ top.setVisibility(View.VISIBLE); if (top.getChildCount() != 0){ top.removeAllViews(); } top.addView(topView()); } else { top.setVisibility(View.VISIBLE); } if(topVisibility != -1){ top.setVisibility(topVisibility); } if (middleView() != null){ middle.setVisibility(View.VISIBLE); if (middle.getChildCount() != 0){ middle.removeAllViews(); } middle.addView(middleView()); } else { middle.setVisibility(View.GONE); } if (bottomView() != null){ bottom.setVisibility(View.VISIBLE); if (bottom.getChildCount() != 0){ bottom.removeAllViews(); } bottom.addView(bottomView()); bottom.addView(divider()); } else { bottom.setVisibility(View.GONE); } return me; } private View divider(){ View view = new View(getActivity()); view.setBackgroundColor(getResources().getColor(R.color.gray)); view.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,1)); return view; } @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Dialog dialog = new Dialog(getActivity(),getTheme()){ @Override public void setContentView(View view) { double width = getActivity().getWindowManager().getDefaultDisplay().getWidth() * 0.95; ViewGroup.LayoutParams params = new ViewGroup.LayoutParams((int)width, ViewGroup.LayoutParams .WRAP_CONTENT); super.setContentView(view,params); } }; dialog.setOnKeyListener(new DialogInterface.OnKeyListener() { @Override public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) { return dialogDelegate != null && dialogDelegate.onKeyEvent(dialog, keyCode, event); } }); dialog.setOnShowListener(new DialogInterface.OnShowListener() { @Override public void onShow(DialogInterface dialog) { if (dialogDelegate != null){ dialogDelegate.onShow(dialog); } } }); return dialog; } @Override public void onActivityCreated(Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); top.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(dialogDelegate != null && dialogDelegate instanceof ThreeRowDialogDelegate){ ((ThreeRowDialogDelegate) dialogDelegate).onTopClick(v); } } }); middle.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(dialogDelegate != null && dialogDelegate instanceof ThreeRowDialogDelegate){ ((ThreeRowDialogDelegate) dialogDelegate).onMiddleClick(v); } } }); bottom.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(dialogDelegate != null && dialogDelegate instanceof ThreeRowDialogDelegate){ ((ThreeRowDialogDelegate) dialogDelegate).onBottomClick(v); } } }); } /** * background * * @return image id */ int background(){ return 0; } /** * top view * * @return view */ View topView(){ return null; } /** * middle view * * @return view */ View middleView(){ return null; } /** * bottom view * * @return view */ View bottomView(){ return null; } //Three row dialog delegate public static class ThreeRowDialogDelegate extends BaseDialogDelegate { /** * This method will be invoked when the top view clicked * * @param view click view */ public void onTopClick(View view){} /** * This method will be invoked when the middle view clicked * * @param view click view */ public void onMiddleClick(View view){} /** * This method will be invoked when the bottom view clicked * * @param view click view */ public void onBottomClick(View view){} } }
package com.goldgov.dygl.module.partymemberrated.ratedresult.web; import java.text.SimpleDateFormat; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.RequestMapping; import com.goldgov.dygl.module.partymemberrated.ratedresult.service.IRatedResultService; import com.goldgov.dygl.module.partymemberrated.ratedresult.service.RatedResult; import com.goldgov.dygl.module.partymemberrated.ratedresult.service.RatedResultQuery; import com.goldgov.gtiles.core.web.GoTo; import com.goldgov.gtiles.core.web.annotation.ModelQuery; import com.goldgov.gtiles.core.web.json.JsonObject; @Controller("ratedResultController") @RequestMapping("/module/partymemberrated/ratedresult") public class RatedResultController { public static final String PAGE_BASE_PATH = "partymemberrated/ratedresult/web/pages/"; @Autowired @Qualifier("ratedResultService") private IRatedResultService ratedResultService; @InitBinder private void initBinder(WebDataBinder binder){ SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); } @RequestMapping("addInfo") public String addInfo(RatedResult ratedResult, HttpServletRequest request, Model model){ ratedResultService.addInfo(ratedResult); return new GoTo(this).sendRedirect("findInfoListByPage"); } @RequestMapping("preAdd") public String preAdd(HttpServletRequest request, Model model){ return new GoTo(this).sendPage("ratedResultForm.ftl"); } @RequestMapping("deleteInfo") public String deleteInfo(String[] ids, HttpServletRequest request, Model model){ ratedResultService.deleteInfo(ids); return new GoTo(this).sendRedirect("findInfoListByPage"); } @RequestMapping("updateInfo") public String updateInfo(RatedResult ratedResult, HttpServletRequest request, Model model){ ratedResultService.updateInfo(ratedResult); return new GoTo(this).sendRedirect("findInfoListByPage"); } @RequestMapping("preUpdate") public String preUpdate(HttpServletRequest request, Model model){ String resultId = request.getParameter("resultId"); RatedResult ratedResult = ratedResultService.findInfo(resultId); model.addAttribute("ratedResult", ratedResult); return new GoTo(this).sendPage("ratedResultForm.ftl"); } @RequestMapping("findInfo") public String findInfo(HttpServletRequest request, Model model){ String resultId = request.getParameter("resultId"); RatedResult ratedResult = ratedResultService.findInfo(resultId); model.addAttribute("ratedResult", ratedResult); return new GoTo(this).sendPage("ratedResultDetail.ftl"); } @RequestMapping("findInfoListByPage") public String findInfoListByPage(@ModelQuery("ratedResultQuery") RatedResultQuery ratedResultQuery, HttpServletRequest request, Model model){ List<RatedResult> list = ratedResultService.findInfoListByPage(ratedResultQuery); ratedResultQuery.setResultList(list); return new GoTo(this).sendPage("ratedResultList.ftl"); } @RequestMapping("updateInfoStatus") public JsonObject updateInfoStatus(String ids,Integer status,HttpServletRequest request, Model model){ JsonObject result = new JsonObject(); if(ids!=""){ ratedResultService.updateInfoStatus((ids.substring(0,ids.length()-1)).split(","), status); result.setSuccess(true); } return result; } }
/** * ファイル名 : VSM040201SearchDTO.java * 作成者 : hung.pd * 作成日時 : 2018/5/31 * Copyright © 2017-2018 TAU Corporation. All Rights Reserved. */ package jp.co.tau.web7.admin.supplier.dto.search; import java.time.LocalDateTime; import lombok.Getter; import lombok.Setter; /** * <p>クラス名 : VSM040201SearchDTO</p> * <p>説明 : VSM040201 search DTO</p> * @author hung.pd * @since 2018/5/31 */ @Setter @Getter public class VSM040201SearchDTO extends BaseSearchDTO { /**ストックNO*/ private String stkNo; /**車台番号*/ private String chassisNo; /**仕入先管理番号*/ private String supplierMngNo; /**仕入先備考*/ private String supplierRmk; /**メーカーコード*/ private String mkCd; /**メーカー*/ private String mkNm; /**モデルコード*/ private String mdCd; /**モデル*/ private String mdNm; /**オークション種別コード*/ private String aucTypeCd; /**オークション期間FROM*/ private LocalDateTime aucPeriodTimeForm; /**オークション期間TO*/ private LocalDateTime aucPeriodTimeTo; /**ユーザID*/ private String userId; /** * オークション番号 */ private String tauAucStat; }
package inheritance; import java.util.ArrayList; import java.util.List; public class Business { public String name; private int price; public List<Review> reviews = new ArrayList<>(); private double stars; public Business() { } public Business(String name) { this.name = name; } public Business(String name, int price) { this.name = name; this.price = price; } public void setPrice(int price) { if(price < 6 && price > 0) { this.price = price; } else { throw new IllegalArgumentException("The price must be between 1-5"); } } private void calculateStars() { double sum = 0; for(int i = 0; i < reviews.toArray().length; i++) { sum += ((Review)reviews.toArray()[i]).getStars(); } stars = (sum/reviews.toArray().length * 100) / 100; } public double getRating() { return stars; } public StringBuilder getPrice() { StringBuilder money = new StringBuilder(); for(int i = 0; i < price; i++) { money.append("$"); } return money; } public void addReview(Review review) { if(review instanceof MovieReview && !(this instanceof Theater)) { System.out.println("Cannot add a movie review to a theater"); } else { if (!reviews.contains(review)) { reviews.add(review); calculateStars(); reviews.get(reviews.size() - 1).businessName = this.name; } } } }
package commandline.argument.validator; import org.junit.Test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class ArgumentValidatorTest { @Test public void testValidate() throws Exception { MockStringArgumentValidator validator; validator = new MockStringArgumentValidator(); validator.validate("test-value"); } @Test public void testGetSupportedClass() throws Exception { MockStringArgumentValidator validator; validator = new MockStringArgumentValidator(); assertEquals(String.class, validator.getSupportedClass()); } @Test public void testIsCompatible() throws Exception { MockStringArgumentValidator validator; validator = new MockStringArgumentValidator(); assertTrue(validator.isCompatible(String.class)); } }
package c.t.m.g; import java.util.concurrent.Executors; import java.util.concurrent.ThreadPoolExecutor; public final class y { public ThreadPoolExecutor a; private y() { this.a = (ThreadPoolExecutor) Executors.newCachedThreadPool(new o("HalleyBusiTaskPoolHolder")); } /* synthetic */ y(byte b) { this(); } }
package com.itbank.food; import java.sql.ResultSet; import java.sql.SQLException; import org.springframework.jdbc.core.RowMapper; public class StoryRowMapper implements RowMapper<StoryDTO> { @Override public StoryDTO mapRow(ResultSet rs, int rowNum) throws SQLException { StoryDTO dto = new StoryDTO(); dto.setStrNo(rs.getInt("strNo")); dto.setStrTitle(rs.getString("strTitle")); dto.setStrContent(rs.getString("strContent")); dto.setStrDate(rs.getDate("strDate")); dto.setStrHit(rs.getInt("strHit")); dto.setStrMaterial(rs.getString("strMaterial")); return dto; } }
package com.bw.movie.IView; import com.bw.movie.mvp.model.bean.ComingMovie; public interface IComingView extends IBaseView { void Sueecss(ComingMovie comingMovie); void Error(String msg); }
public class CharAt_AND_SetChatAt_Method { public static void main(String args[]) { StringBuffer str =new StringBuffer("Java Programming"); System.out.println("String is "+str); System.out.println("Character at index 2 is "+str.charAt(2)); // char charAt(int index) str.setCharAt(2,'f'); // void setCharAt(int index,char ch) System.out.println("Now after using setCharAt() method String is "+str); } }
package assemAssist.model.scheduler; import org.junit.runner.RunWith; import org.junit.runners.Suite; import org.junit.runners.Suite.SuiteClasses; import assemAssist.model.scheduler.comparators.BatchComparatorTest; import assemAssist.model.scheduler.comparators.OrderedDateComparatorTest; import assemAssist.model.scheduler.comparators.STODeadLineComparatorTest; @RunWith(Suite.class) @SuiteClasses({ AlgorithmPriorityTest.class, SchedulerTest.class, AlgorithmBatchTest.class, VisitorPatternsTest.class, BatchComparatorTest.class, OrderedDateComparatorTest.class, STODeadLineComparatorTest.class }) public class SchedulerTestSuite { }
package dynamicProgramming; public class UnboundedKnapsack { public static void main(String[] args) { int N = 2, W = 3; int val[] = { 1, 1 }; int wt[] = { 2, 1 }; System.out.println(unboundedKnapsack(N, W, val, wt)); } static int unboundedKnapsack(int n, int w, int value[], int weight[]) { int t[][] = new int[n + 1][w + 1]; // No need of initialization because default value of array is zero // 0 0 0 0 0 0 // 0 X X X X X // 0 X X X X X // 0 X X X X X for (int i = 1; i <= n; i++) { for (int j = 1; j <= w; j++) { if (weight[i - 1] <= j) { // Here we are taking the choice of picking an element as much as we want // t[i][j - weight[i - 1]] t[i][j] = Math.max((value[i - 1] + t[i][j - weight[i - 1]]), t[i - 1][j]); } else { t[i][j] = t[i - 1][j]; } } } return t[n][w]; } }
package com.faith.newinstance; /** * @Auther: yangguoqiang01 * @Date: 2019-05-20 * @Description: 实现类1 * @version: 1.0 */ public class JavaCourse implements ICourse{ public void learn() { System.out.println("学习java"); } }
package com.mes.old.meta; // Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final import java.math.BigDecimal; /** * KvWarehousevelocitylastmonth generated by hbm2java */ public class KvWarehousevelocitylastmonth implements java.io.Serializable { private BigDecimal warehousevelocitylastmontth; public KvWarehousevelocitylastmonth() { } public KvWarehousevelocitylastmonth(BigDecimal warehousevelocitylastmontth) { this.warehousevelocitylastmontth = warehousevelocitylastmontth; } public BigDecimal getWarehousevelocitylastmontth() { return this.warehousevelocitylastmontth; } public void setWarehousevelocitylastmontth(BigDecimal warehousevelocitylastmontth) { this.warehousevelocitylastmontth = warehousevelocitylastmontth; } }
package com.revature.util; import java.io.FileReader; import java.io.IOException; import java.sql.Connection; // This is JDBC import java.sql.DriverManager; import java.sql.SQLException; import java.util.Properties; import org.apache.log4j.Logger; // Singleton design pattern instantiates an object ONCE /** * Singleton design pattern * * -- private constructors * -- static field of an instance of the class to be returned * -- leverage a public static getInstance() (our getInstance ) * @author ron * */ public class ConnectionUtil { private static Logger log = Logger.getLogger(ConnectionUtil.class); private static Connection conn = null; // we want to make the constructor private private ConnectionUtil() { super(); } // in a singleton design pattern you create a static "getInstance() public static Connection getConnection() { try { if (conn != null && !conn.isClosed() ) { return conn; } } catch (SQLException e) { // Implement an error log here return null; } Properties prop = new Properties(); // access the properties in the application.properties file String url = ""; String username = ""; String password = ""; try { prop.load(new FileReader("/home/ron/Documents/Revature/revature-notes/JDBCdemo/src/main/resources/application.properties")); url = prop.getProperty("url"); username = prop.getProperty("username"); password = prop.getProperty("password"); conn = DriverManager.getConnection(url, username, password); System.out.println("Connection successful!"); } catch (IOException e) { // TODO add some logging e.printStackTrace(); } catch (SQLException e) { // TODO add some logging return null; } return conn; } }
package com.yixin.web.anocation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @description: * @date: 2018-10-08 14:20 */ @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) public @interface MethodMonitor { /** * 关键参数 * <p> * applyNo::0_data_field 第0个参数的字段data下的字段field,参数的名字是applyNo * * @return */ String[] keyParam() default {}; }
package com.wzy.init; /** * @author wzy * @title: Test * @description: TODO * @date 2019/8/19 10:58 */ public class Test { public static void main(String[] args) { MySpringApplication.run(); } }
package com.gideas; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; public class Tested extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { if (AppInfo.nightModeState) setTheme(R.style.NightAppTheme); else setTheme(R.style.AppTheme); super.onCreate(savedInstanceState); setContentView(R.layout.activity_tested); } }
package com.tencent.mm.plugin.sns.ui; import com.tencent.mm.plugin.sns.ui.SnsCommentFooter.c; import com.tencent.mm.sdk.platformtools.x; class SnsStrangerCommentDetailUI$3 implements c { final /* synthetic */ SnsStrangerCommentDetailUI obC; SnsStrangerCommentDetailUI$3(SnsStrangerCommentDetailUI snsStrangerCommentDetailUI) { this.obC = snsStrangerCommentDetailUI; } public final void NJ(String str) { x.v("MicroMsg.SnsStrangerCommentDetailUI", "comment send requested"); SnsStrangerCommentDetailUI.a(this.obC, true); SnsStrangerCommentDetailUI.a(this.obC, SnsStrangerCommentDetailUI.k(this.obC), str); } }
package br.com.giorgetti.games.squareplatform.gameobjects.interaction.action.question; import br.com.giorgetti.games.squareplatform.gameobjects.interaction.action.InteractiveSprite; import br.com.giorgetti.games.squareplatform.gameobjects.interaction.auto.Coin; import br.com.giorgetti.games.squareplatform.gamestate.GameState; import br.com.giorgetti.games.squareplatform.main.GamePanel; import br.com.giorgetti.games.squareplatform.tiles.TileMap; import java.awt.*; import java.awt.event.KeyEvent; import java.util.LinkedHashMap; import java.util.Map; /** * Draws a dialog and request player to answer correctly. When correct answer is * given, a coin is created in the map. * * Created by fgiorgetti on 08/07/17. */ public abstract class Question extends InteractiveSprite implements GameState { private final int HEIGHT = 10; private final int WIDTH = 10; private boolean askQuestion = false; private boolean answered = false; private boolean correct = false; private boolean showResult = false; private long timestamp; public abstract String correctChoice(); public abstract String question(); public abstract LinkedHashMap<String, String> choicesAndAnswers(); public Question() { this.width = WIDTH; this.height = HEIGHT; } @Override public void executeInteraction() { showResult = false; askQuestion = true; GamePanel.gsm.addTemporaryState(this); } @Override public void update(TileMap map) { } @Override public void update() { } @Override public void draw(Graphics2D g) { g.setColor(Color.black); Font oldFont = g.getFont(); g.setFont(new Font("TimeRoman", Font.BOLD, 16)); g.drawString("?",getX() - map.getX() - 1, GamePanel.HEIGHT - getY() + map.getY() + 11); g.setColor(!answered? Color.magenta:correct? Color.green:Color.red); g.drawString("?",getX() - map.getX(), GamePanel.HEIGHT - getY() + map.getY() + 10); g.setFont(oldFont); if ( askQuestion ) { drawQuestion(g); } } private void drawQuestion(Graphics2D g) { g.setColor(Color.white); g.fillRoundRect(GamePanel.WIDTH/5-15, GamePanel.HEIGHT/5-5, (GamePanel.WIDTH/5)*3+30, (GamePanel.HEIGHT/5)*3+10, 5, 5); g.setColor(Color.black); g.fillRoundRect(GamePanel.WIDTH/5-10, GamePanel.HEIGHT/5, (GamePanel.WIDTH/5)*3+20, (GamePanel.HEIGHT/5)*3, 5, 5); int lineY = GamePanel.HEIGHT/5; int linesOffset = 15; int linesPrinted = 0; g.setColor(Color.white); g.drawString("-------- QUESTION --------", GamePanel.WIDTH/5 + 5, lineY + (linesOffset * ++linesPrinted)); g.drawString(question(), GamePanel.WIDTH/5 + 5, lineY + (linesOffset * ++linesPrinted)); linesPrinted++; int choiceIdx = 0; for ( Map.Entry<String, String> choice : choicesAndAnswers().entrySet() ) { g.drawString(String.format("%2s - %s", choice.getKey(), choice.getValue()), GamePanel.WIDTH/4 + 5, lineY + (linesOffset * ++linesPrinted)); } if ( showResult ) { linesPrinted++; g.drawString(correct? "Correct: " + correctChoice()+"! Nice job.":"Incorrect. Right answer was: " + correctChoice() + ".", GamePanel.WIDTH/4 + 5, lineY + (linesOffset * ++linesPrinted)); if ( System.currentTimeMillis() - timestamp > 2000 ) { askQuestion = false; showResult = false; if ( !answered && correct ) { Coin c = new Coin(getX(), getY()+40); map.addSpriteInGame(c); } answered = true; GamePanel.gsm.cleanTemporaryState(); } } } @Override public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { if ( !askQuestion ) { return; } if ( !answered ) { boolean valid = false; for (String choice : choicesAndAnswers().keySet()) { if (choice.equalsIgnoreCase(String.valueOf(e.getKeyChar()))) { valid = true; break; } } if (!valid) { return; } if (correctChoice().equalsIgnoreCase(String.valueOf(e.getKeyChar()))) { correct = true; } else { correct = false; } } showResult = true; timestamp = System.currentTimeMillis(); } @Override public void notifySwitchedOff() { } @Override public void notifySwitchedOn() { } }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2013.09.14 at 01:52:08 PM MESZ // package petko.osm.model.impl.xml; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import petko.osm.model.facade.OsmRelation; import petko.osm.model.facade.OsmRelationMember; /** * <p> * Java s for relation complex type. * * <p> * The following schema fragment spec s the expected content contained within * this class. * * <pre> * &lt;complexType name="relation"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="member" type="{}member" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="tag" type="{}tag" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;attribute name="id" use="required" type="{http://www.w3.org/2001/XMLSchema}unsignedLong" /> * &lt;attribute name="timestamp" type="{http://www.w3.org/2001/XMLSchema}dateTime" /> * &lt;attribute name="uid" type="{http://www.w3.org/2001/XMLSchema}unsignedLong" /> * &lt;attribute name="user" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="visible" type="{http://www.w3.org/2001/XMLSchema}boolean" /> * &lt;attribute name="version" type="{http://www.w3.org/2001/XMLSchema}unsignedLong" /> * &lt;attribute name="changeset" type="{http://www.w3.org/2001/XMLSchema}unsignedLong" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "relation") @XmlRootElement(name = "relation") public class OsmRelationXml extends OsmObjectXml implements OsmRelation { @XmlElement(name = "member", type = OsmRelationMemberXml.class) private List<OsmRelationMember> members = new ArrayList<>(); @Override public List<OsmRelationMember> getMembers() { return members; } }
import java.awt.Color; import java.awt.Font; import java.awt.event.WindowEvent; import java.sql.ResultSet; import java.sql.SQLException; import javax.swing.JPanel; import org.eclipse.swt.graphics.Image; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.annotations.XYTextAnnotation; import org.jfree.chart.axis.DateAxis; import org.jfree.chart.axis.NumberAxis; import org.jfree.chart.plot.CombinedRangeXYPlot; import org.jfree.chart.plot.DatasetRenderingOrder; import org.jfree.chart.plot.XYPlot; import org.jfree.chart.renderer.xy.StandardXYItemRenderer; import org.jfree.chart.renderer.xy.XYAreaRenderer; import org.jfree.chart.renderer.xy.XYBarRenderer; import org.jfree.chart.renderer.xy.XYItemRenderer; import org.jfree.data.time.Month; import org.jfree.data.time.TimeSeries; import org.jfree.data.time.TimeSeriesCollection; import org.jfree.data.time.Year; import org.jfree.ui.ApplicationFrame; import org.jfree.ui.RefineryUtilities; /** * A demo showing a combined time series chart where one of the subplots is an * overlaid chart. */ public class graphYear extends ApplicationFrame { /** * */ private static final long serialVersionUID = 1L; private static ResultSet rs; static XYPlot plot1; static XYPlot plot2; static double x; static XYTextAnnotation annotation; static XYTextAnnotation annotation2; static double x2; /** * Creates a new demo application. * * @param title * the frame title. */ public graphYear(String title) { super(title); setContentPane(createDemoPanel()); } public void windowClosing(final WindowEvent evt) { if (evt.getWindow() == this) { dispose(); } } /** * Creates a panel for the demo (used by SuperDemo.java). * * @return A panel. */ public static JPanel createDemoPanel() { // create the first dataset... rs = RSet .openRS("select distinct year (datum)godina,SUM(iznos)sumaIznos from racuni where YEAR(datum) between 2000 and 2050 group by YEAR(datum)"); TimeSeries series1 = new TimeSeries("Godišnji prikaz", Year.class); try { while (rs.next()) { series1.add(new Year(rs.getInt("godina")), rs.getDouble("sumaIznos")); } rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); logger.loggErr("graphYear " + e.getMessage() + " (" + e.getErrorCode() + ")"); } TimeSeriesCollection dataset1 = new TimeSeriesCollection(series1); dataset1.setDomainIsPointsInTime(false); rs = RSet .openRS("select SUM(iznos)as sumaIznos,Year(datum)god, Month(datum)mj from racuni where Datum between '2010/1/1' and '2050/12/31' GROUP BY Year(datum), Month(datum) order by god,mj"); TimeSeries series2A = new TimeSeries("Mjesečni prikaz 2010-2012", Month.class); try { while (rs.next()) { series2A.add(new Month(rs.getInt("mj"), rs.getInt("god")), rs.getDouble("sumaIznos")); } rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); logger.loggErr("graphYear " + e.getMessage() + " (" + e.getErrorCode() + ")"); } TimeSeriesCollection dataset2 = new TimeSeriesCollection(); dataset2.addSeries(series2A); XYItemRenderer renderer = new XYBarRenderer(0.20); plot1 = new XYPlot(dataset1, new DateAxis("Godine"), null, renderer); plot1.setBackgroundPaint(Color.WHITE); renderer = plot1.getRenderer(); renderer.setSeriesPaint(0, Color.RED); XYItemRenderer renderer2 = new XYAreaRenderer(); plot2 = new XYPlot(dataset2, new DateAxis("Mjeseci"), null, renderer2); renderer2 = plot2.getRenderer(); renderer2.setSeriesPaint(0, Color.GREEN); popuniPodatke(); StandardXYItemRenderer renderer3 = new StandardXYItemRenderer( StandardXYItemRenderer.SHAPES_AND_LINES); renderer3.setShapesFilled(true); // plot2.setDataset(1, dataset3); plot2.setRenderer(1, renderer3); plot2.setDatasetRenderingOrder(DatasetRenderingOrder.FORWARD); NumberAxis rangeAxis = new NumberAxis("Vrijednost (kn)"); rangeAxis.setAutoRangeIncludesZero(false); CombinedRangeXYPlot combinedPlot = new CombinedRangeXYPlot(rangeAxis); combinedPlot.add(plot1, 1); combinedPlot.add(plot2, 4); // create the chart... JFreeChart chart = new JFreeChart("", new Font("Tahoma", Font.PLAIN, 9), combinedPlot, true); // add the chart to a panel... ChartPanel chartPanel = new ChartPanel(chart); chartPanel.setPreferredSize(new java.awt.Dimension(500, 270)); return chartPanel; } /** * Starting point for the demonstration application. * * @param args * ignored. */ public static void main(String[] args) { graphYear demo = new graphYear("Ukupni pregled mjesec/godina"); demo.pack(); RefineryUtilities.centerFrameOnScreen(demo); demo.setVisible(true); } private static void popuniPodatke() { // godine rs = RSet .openRS(" select distinct year(datum)godina,SUM(iznos)sumaIznos from racuni where YEAR(datum) between 2000 and 2050 group by YEAR(datum)"); try { while (rs.next()) { x = new Year(rs.getInt("godina")).getMiddleMillisecond(); annotation = new XYTextAnnotation(DEF.FormatCur(Double .toString(rs.getDouble("sumaIznos"))) + "kn", x, (rs.getInt("sumaIznos") + 150)); annotation.setFont(new Font("Arial", Font.PLAIN, 8)); plot1.addAnnotation(annotation); } rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); logger.loggErr("graphYear " + e.getMessage() + " (" + e.getErrorCode() + ")"); } // mjeseci rs = RSet .openRS("select SUM(iznos)as sumaIznos,Year(datum)god, Month(datum)mj from racuni where Datum between '2010/1/1' and '2050/12/31' GROUP BY Year(datum), Month(datum) order by god,mj"); try { while (rs.next()) { x2 = new Month(rs.getInt("mj"), rs.getInt("god")) .getMiddleMillisecond(); annotation2 = new XYTextAnnotation(DEF.FormatCur(Double .toString(rs.getDouble("sumaIznos"))) + "kn", x2, (rs.getInt("sumaIznos") + 150)); annotation2.setFont(new Font("Arial", Font.PLAIN, 8)); plot2.addAnnotation(annotation2); } rs.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); logger.loggErr("graphYear " + e.getMessage() + " (" + e.getErrorCode() + ")"); } } }
package camera; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; import com.github.sarxos.webcam.Webcam; public class CameraAppTest { public void takePicture() throws IOException { Webcam webcam = null; // webcam = Webcam.getDefault(); webcam = Webcam.getWebcams().get(1); if (webcam != null) { System.out.println("Webcam : " + webcam.getName()); webcam.open(); BufferedImage image = webcam.getImage(); File f = new File("pictures" + File.separator + "webcam-capture.png"); ImageIO.write(image, "PNG", f); } else { System.out.println("Failed: Webcam Not Found Error"); } } public static void main(String[] args) { try { new CameraAppTest().takePicture(); } catch (IOException e) { // TODO 自動生成された catch ブロック e.printStackTrace(); } } }
package com.duoying.test.nacos; /** * @author gezhiwei */ public class NacosConfig { }
//DictionaryTest.java //Jack Liu //dliu34 //CMPS12B //pa3 //9FEB2018 //This file test exceptions. public class DictionaryTest { public static void main(String[] args) { Dictionary A = new Dictionary(); A.insert("1", "a"); A.insert("2", "b"); A.insert("3", "c"); A.insert("4", "e"); A.insert("4", "d"); System.out.println(A); System.out.println(A.lookup("3")); System.out.println(A.lookup("5")); A.delete("1"); A.delete("3"); System.out.println(A); A.makeEmpty(); System.out.println(A.isEmpty()); System.out.println(A); } }
package org.tyaa.java.springboot.gae.simplespa.JavaSpringBootGaeSimpleSpa.model; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonInclude; import com.google.gson.annotations.Expose; import com.googlecode.objectify.annotation.Entity; import com.googlecode.objectify.annotation.Id; import com.googlecode.objectify.annotation.Index; import lombok.*; @Data @Builder(toBuilder = true) @NoArgsConstructor @AllArgsConstructor @JsonIgnoreProperties(ignoreUnknown = true) @JsonInclude(JsonInclude.Include.NON_NULL) @Entity(name = "Users") public class UserModel { @Id @Expose(serialize = false, deserialize = false) private Long id; @Index @Expose (serialize = false, deserialize = false) private String googleId; @Index @Expose private String name; @Expose private String email; @Expose private String pictureUrl; @Index @Expose (serialize = false, deserialize = false) private Long userTypeId; }
package CollectionsDemo; import java.util.Comparator; import java.util.TreeSet; /** * An interface 'Comparator', is used to manipulate the order in collections. * * The 'compareTo()' method, is used to compare strings. * * @author Bohdan Skrypnyk */ class Cities1 { private String cityName; private String state; private double debt; // constructor with parameters public Cities1(String cityName, String state, double debt) { this.cityName = cityName; this.state = state; this.debt = debt; } // the overloaded constructor with no parameters public Cities1() { this.cityName = ""; this.state = ""; this.debt = -1; } // getters public String getCityName() { return cityName; } public String getState() { return state; } public double getDebt() { return debt; } void show() { System.out.println("City name : " + getCityName() + ", located in the State : " + getState() + ", has debit : " + getDebt() + " billion USD."); } } public class ComparatorDemo2 { public static void main(String args[]) { // create the objects of the type 'Cities1' Cities1 ct1 = new Cities1("Eufaula", "Alabama", 54.44); Cities1 ct2 = new Cities1("Homer", "Alaska", 250.60); Cities1 ct3 = new Cities1("New York", "City in New York State", 119.44); Cities1 ct4 = new Cities1("Scottsdale", "Arizona", 25.44); Cities1 ct5 = new Cities1("Forrest City", "Arkansas", 11.4); Cities1 ct6 = new Cities1("Bakersfield", "California", 7.5); // lambda expression for the comparator with the type // 'City' which will sort in ascending order. Comparator<Cities1> comp = (name1, name2) -> name1.getCityName().compareTo(name2.getCityName()); // initialization of the 'TreeSet' with the type 'Cities' TreeSet<Cities1> st = new TreeSet(comp); // add the objects to the 'TreeSet' st.add(ct1); st.add(ct2); st.add(ct3); st.add(ct4); st.add(ct5); st.add(ct6); // to display 'TreeSet' for (Cities1 ci : st) { ci.show(); } } }
/** * @project : Argmagetron * @file : Location.java * @author(s) : Thomas Lechaire * @date : 11.05.2017 * * @brief : Class Location use to set Starting location to player */ package server; import java.awt.*; import java.util.ArrayList; /** * @class Location */ public class Location { /** * ArrayList of fixed position for the start of the 4 players */ private final static ArrayList<Point> arrayList = new ArrayList<Point>(){{ add(new Point(5,5)); add(new Point(75,75)); add(new Point(5,75)); add(new Point(75,5)); }}; /** * Direction given to the for player at start point. */ private final static short UP = 0; private final static short LEFT = 1; private final static short DOWN = 2; private final static short RIGHT = 3; private static short index = Player.UP; private short direction; private Point position; /** * Constructor */ Location() { //Setting the direction switch (index){ case 0: this.direction = DOWN; break; case 1: this.direction = UP; break; case 2: this.direction = LEFT; break; case 3: this.direction = RIGHT; break; } //setting the positions this.position = arrayList.get(index); if(index == 3){ index = 0; }else{ index++; } } /** * @fn short getDirection() * * @brief Get the direction * * @author Thomas Lechaire * * @return short of the direction */ short getDirection() { return direction; } /** * @fn Point getPosition() * * @brief Get the position of the player * * @author Thomas Lechaire * * @return Point The position of the player */ Point getPosition() { return position; } }
package com.benz.event.receiver.exceptions; import lombok.Data; /* (non-Javadoc) * @see java.lang.Throwable#toString() */ @Data public class ReceiverServiceException extends RuntimeException { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; /** * Instantiates a new receiver service validation exception. * * @param message the message */ public ReceiverServiceException(String message) { super(message); } }
package com.ecomerce.web.webservice.utils.Enums; public enum TipoOperacion { PAGO("pago"), REINTEGRO("reintegro"), COMPRA("compra"); public String tipo; TipoOperacion(String tipo){ this.tipo = tipo; } public boolean isCompra(){ if(TipoOperacion.COMPRA.tipo.equalsIgnoreCase(this.tipo)){ return true; }else { return false; } } public String getTipo() { return tipo; } }
package backjoon.math; import java.io.*; import java.util.StringTokenizer; public class Backjoon4153 { private static final BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); private static final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out)); public static void main(String[] args) throws IOException { StringTokenizer st; int a, b, c; while(true){ st = new StringTokenizer(br.readLine(), " "); a = Integer.parseInt(st.nextToken()); b = Integer.parseInt(st.nextToken()); c = Integer.parseInt(st.nextToken()); if(a == 0 && b == 0 && c == 0) break; checkRectangle(a, b, c); } br.close(); bw.close(); } private static void checkRectangle(int a, int b, int c) throws IOException { if(a > b && a > c){ if(a * a == b * b + c * c) bw.write("right" + "\n"); else bw.write("wrong" + "\n"); }else if(b > a && b > c){ if(b * b == a * a + c * c) bw.write("right" + "\n"); else bw.write("wrong" + "\n"); }else if(c > a && c > b){ if(c * c == a * a + b * b) bw.write("right" + "\n"); else bw.write("wrong" + "\n"); }else{ bw.write("wrong" + "\n"); } } }
package com.forthorn.projecting.api; import com.forthorn.projecting.baserx.BaseResponse; import com.forthorn.projecting.entity.IMAccount; import com.forthorn.projecting.entity.TaskList; import com.forthorn.projecting.entity.TaskRes; import com.forthorn.projecting.entity.UserList; import java.io.File; import java.util.Map; import okhttp3.MultipartBody; import okhttp3.RequestBody; import retrofit2.Call; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.GET; import retrofit2.http.Header; import retrofit2.http.Multipart; import retrofit2.http.POST; import retrofit2.http.Part; import retrofit2.http.PartMap; import retrofit2.http.Query; import rx.Observable; /** * des:ApiService */ public interface ApiService { /** * 获取联系人列表 */ @GET("/v1/users/") Call<UserList> getContactList( @Header("Cache-Control") String cacheControl, @Header("Authorization") String auth, @Query("start") String start, @Query("count") String count ); /** * 统一更新信息 */ @FormUrlEncoded @POST("/api/v1/android/ad/update_ad_status") Call<BaseResponse> updateStatus( @Header("Cache-Control") String cacheControl, @Field("equipment_id") int equipmentId, @Field("is_sleep") int isSleep, @Field("volume") int volume ); /** * 获取天气 */ @FormUrlEncoded @POST("/api/v1/android/weather/weather") Observable<BaseResponse> getWeather( @Header("Cache-Control") String cacheControl, @Field("equipment_id") String equipmentId, @Field("equipment_code") String equipmentCode ); /** * 获取整个时段的广告 */ @FormUrlEncoded @POST("/api/v1/android/ad/ad_time") Call<TaskRes> getTaskList( @Header("Cache-Control") String cacheControl, @Field("equipment_id") String equipmentId, @Field("date") String date ); /** * 获取账户密码 */ @FormUrlEncoded @POST("/api/v1/android/weather/im") Call<IMAccount> getIMAccount( @Header("Cache-Control") String cacheControl, @Field("code") String equipmentCode ); /** * 设置音量 */ @FormUrlEncoded @POST("/api/v1/android/ad/volume") Call<BaseResponse> setVolume( @Header("Cache-Control") String cacheControl, @Field("equipment_id") String equipment_id, @Field("equipment_code") String equipment_code, @Field("volume") String volume ); /** * 休眠 */ @FormUrlEncoded @POST("/api/v1/android/ad/sleep") Call<BaseResponse> setSleep( @Header("Cache-Control") String cacheControl, @Field("equipment_id") String equipment_id, @Field("equipment_code") String equipment_code ); /** * 唤醒 */ @FormUrlEncoded @POST("/api/v1/android/ad/wake_up") Call<BaseResponse> setWakeUp( @Header("Cache-Control") String cacheControl, @Field("equipment_id") String equipment_id, @Field("equipment_code") String equipment_code ); /** * 上传截图 */ @Multipart @POST("/api/v1/android/ad/upload_z") Call<BaseResponse> uploadSnapshoot( @Header("Cache-Control") String cacheControl, @Part("capture_time") RequestBody capture_time, @Part("equipment_id") RequestBody equipment_id, @Part MultipartBody.Part attachment); // MultipartBody.Part avatarPt = MultipartBody.Part.createFormData("file", // Md5Security.getMD5(avatarPath) + ".jpeg", avatarRB); }
package com.weixin.tool.common; /** * Emoji表情工具类 * Emoji表情有很多种版本,包括Unified、DoCoMo、KDDI、Softbank和Google,而且不同版本的表情代码也不一样, * 不同的手机操作系统、甚至是同一操作系统的不同版本所支持的emoji表情又不一样。 * QQ表情编码:http://blog.csdn.net/lyq8479/article/details/9229631 * Unified表情编码:http://blog.csdn.net/lyq8479/article/details/9229637 * SoftankB表情编码:http://blog.csdn.net/lyq8479/article/details/9393097 * Created by White on 2017/2/21. */ public class EmojiUtil { /** * Unified表情 * emoji表情转换(hex -> utf-16) * @param hexEmoji * @return */ public static String unifiedEmoji(int hexEmoji) { return String.valueOf(Character.toChars(hexEmoji)); } }
package com.cmdi.client; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.cmdi.hbase.UsingHBase; import com.cmdi.redis.RedisClientTemplate; /** * 该类的作用:初始化spring,得到需要用到的客户端 * */ public class Global { public static ClassPathXmlApplicationContext context; public static UsingHBase hbaseclient; public static RedisClientTemplate redisClient; public static SqlSessionTemplate sqlSession; static { context = new ClassPathXmlApplicationContext("spring-application.xml"); //System.out.println(context); //hbase client try { hbaseclient = context.getBean("usinghbase", UsingHBase.class); } catch (Exception e) { e.printStackTrace(); System.err.println("error generate UsingHBase instance"); } //redis client try { redisClient = context.getBean("redisClient", RedisClientTemplate.class); } catch (Exception e) { e.printStackTrace(); System.err.println("error generate RedisClientTemplate instance"); } //mybatis client try { sqlSession = context.getBean("sqlSessionTemplate", SqlSessionTemplate.class); } catch (Exception e) { e.printStackTrace(); System.err.println("error generate SqlSessionTemplate instance"); } } /** * 关闭context * */ public static void closeContext() { if(context != null) context.close(); System.out.println("close context success"); } }
package com.design.pattern; public class MySingleton implements Runnable { @Override public void run() { getObject(); } static MySingleton mySingleton = null; // t1 private static MySingleton getObject() { System.out.println("start Excec " + Thread.currentThread().getName()); // t1 t2 synchronized (MySingleton.class) { if (mySingleton == null) { // t1 sleep if (mySingleton == null) { mySingleton = new MySingleton(); } } else { mySingleton = mySingleton; } } System.out.println("end Excec " + Thread.currentThread().getName()); return mySingleton; } public static void main(String[] args) { System.out.println(MySingleton.getObject().hashCode()); System.out.println(MySingleton.getObject().hashCode()); System.out.println(MySingleton.getObject().hashCode()); System.out.println(MySingleton.getObject().hashCode()); System.out.println(MySingleton.getObject().hashCode()); } }
/** * */ package org.rebioma.client.bean; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; /** * @author Mika * */ @XmlRootElement(name="results") @XmlAccessorType (XmlAccessType.FIELD) public class PaginationResponse<M> { public PaginationResponse() { super(); } private int pageNum; private int pageSize; private int nbTotal; @XmlElement(name="items") private List<M> items; public PaginationResponse(int pageNum, int pageSize, int nbTotal, List<M> items) { super(); this.pageNum = pageNum; this.pageSize = pageSize; this.nbTotal = nbTotal; this.items = items; } public int getNbTotal() { return nbTotal; } public void setNbTotal(int nbTotal) { this.nbTotal = nbTotal; } public int getPageNum() { return pageNum; } public void setPageNum(int pageNum) { this.pageNum = pageNum; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public List<M> getItems() { return items; } public void setItems(List<M> items) { this.items = items; } }
package Controlador; import java.awt.SystemColor; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import javax.swing.AbstractAction; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JOptionPane; import javax.swing.JTextField; import Modelo.ConectarSQL; import Modelo.datosPregunta; import Vista.CodigoPruebaFRM; public class controladorCodigoPrueba { private ConectarSQL conexion; CodigoPruebaFRM ventana; public controladorCodigoPrueba() { conexion = new ConectarSQL(); ventana = new CodigoPruebaFRM(); ventana.rutTF.getVerifyInputWhenFocusTarget(); ventana.rutTF.addFocusListener(new FocusAdapter() { public void focusGained(FocusEvent e) { JTextField source = (JTextField)e.getComponent(); ventana.rutTF.setText(""); ventana.rutTF.setForeground(SystemColor.black); source.removeFocusListener(this); } }); AbstractAction onEnter_codigo = new AbstractAction() { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { ventana.btnBuscar.doClick(); } }; ventana.codigoTextField.addActionListener(onEnter_codigo); ventana.btnBuscar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { if(verificarRut()) { if(conexion.Buscar("pruebas","codigo",ventana.codigoTextField.getText())) { Icon icono = new ImageIcon(getClass().getResource("/imagenes/success-icon.png")); JOptionPane.showMessageDialog(null, "Examen encontrado","Mensaje",JOptionPane.PLAIN_MESSAGE,icono); crearPreguntas(); }else { Icon icono = new ImageIcon(getClass().getResource("/imagenes/Exclamation-mark-icon.png")); JOptionPane.showMessageDialog(null, "Examen no encontrado","Mensaje",JOptionPane.PLAIN_MESSAGE,icono); } }else { Icon icono = new ImageIcon(getClass().getResource("/imagenes/Exclamation-mark-icon.png")); JOptionPane.showMessageDialog(null, "Rut invalido","Mensaje",JOptionPane.PLAIN_MESSAGE,icono); } } }); ventana.btnVolver.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { ventana.setVisible(false); controladorSeleccion nuevaVentana = new controladorSeleccion(); } }); } private boolean verificarRut() { if(ventana.rutTF.getText().charAt(0) == '0') { return false; } if(ventana.rutTF.getText().matches("[0-9]{1,2}[.][1-9][0-9]{2}[.][1-9][0-9]{2}[-]([1-9]|(k|K))")) { return true; } return false; } private void crearPreguntas() { String codigo = ventana.codigoTextField.getText(); preguntasPrueba[] preguntas = new preguntasPrueba[conexion.getDatoInt("pruebas","codigo",codigo,"cantidadPreguntas")]; for(int i = 0;i<preguntas.length;i++) { datosPregunta paquete = conexion.getDatosPregunta("preguntas_"+codigo,i+1); if(paquete.tipoPreg.equalsIgnoreCase("alternativas")) { String[] respuestas = new String[4]; respuestas[0] = paquete.alternativa1;respuestas[1] = paquete.alternativa2; respuestas[2] = paquete.alternativa3;respuestas[3] = paquete.alternativa4; preguntas[i] = new controladorPreguntaAltrP(paquete.enunciado,paquete.nPreg,paquete.respCorrecta,respuestas,paquete.puntaje); preguntas[i].tipoPregunta = "alternativas"; } if(paquete.tipoPreg.equalsIgnoreCase("respcorta")) { preguntas[i] = new controladorPreguntaRespCortP(paquete.enunciado,paquete.nPreg,paquete.respCorrecta,paquete.puntaje); preguntas[i].tipoPregunta = "respcorta"; } if(paquete.tipoPreg.equalsIgnoreCase("vof")) { preguntas[i] = new controladorPreguntaVoFP(paquete.enunciado,paquete.nPreg,paquete.respCorrecta,paquete.puntaje); preguntas[i].tipoPregunta = "vof"; } } controladorExamen nuevaVentana = new controladorExamen(preguntas,conexion.getDatoInt("pruebas","codigo", codigo,"duracionprueba"),codigo,ventana.rutTF.getText()); ventana.setVisible(false); } }
package rhtn_homework; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.LinkedList; import java.util.Queue; import java.util.StringTokenizer; public class BOJ_1012_유기농_배추 { private static StringBuilder sb = new StringBuilder(); private static int M,N,K,cnt; private static int[][] map; private static int[][] dir = {{-1,0},{1,0},{0,-1},{0,1}}; private static boolean[][] visited; public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; int TC = Integer.parseInt(br.readLine()); for (int t = 0; t < TC; t++) { st = new StringTokenizer(br.readLine()); // 가로 , 세로, 배추 M = Integer.parseInt(st.nextToken()); N = Integer.parseInt(st.nextToken()); K = Integer.parseInt(st.nextToken()); map = new int[N][M]; visited = new boolean[N][M]; for (int i = 0; i < K; i++) { st = new StringTokenizer(br.readLine()); int b = Integer.parseInt(st.nextToken()); int a = Integer.parseInt(st.nextToken()); map[a][b]=1; } int cnt=0; for (int r = 0; r < N; r++) { for (int c = 0; c < M; c++) { if(!visited[r][c] && map[r][c]==1) { bfs(r,c); ++cnt; } } } sb.append(cnt).append("\n"); } System.out.println(sb); } private static void bfs(int r, int c) { Queue<Pair> queue = new LinkedList<>(); queue.offer(new Pair(r,c)); visited[r][c] = true; while(!queue.isEmpty()) { Pair p = queue.poll(); for (int i = 0; i < dir.length; i++) { int px = dir[i][0] + p.x; int py = dir[i][1] + p.y; if(isIn(px,py) && !visited[px][py] && map[px][py]==1) { queue.offer(new Pair(px,py)); visited[px][py] = true; } } } } public static class Pair{ int x,y; public Pair(int x, int y) { super(); this.x = x; this.y = y; } } private static boolean isIn(int r, int c) { return r>=0 && c>=0 && r<N && c<M; } }
package com.tencent.mm.plugin.exdevice.model; import android.os.Looper; import com.tencent.mm.g.a.ei; import com.tencent.mm.plugin.exdevice.model.e.b; import com.tencent.mm.plugin.exdevice.model.h.a; import com.tencent.mm.sdk.platformtools.x; import java.util.LinkedList; import java.util.List; class e$40 implements a { final /* synthetic */ e iup; e$40(e eVar) { this.iup = eVar; } public final void a(long j, int i, int i2, int i3, long j2) { List<b> linkedList; x.d("MicroMsg.exdevice.ExdeviceEventManager", "mac=%d, oldState=%d, newState=%d, errCode=%d, profileType=%d", new Object[]{Long.valueOf(j), Integer.valueOf(i), Integer.valueOf(i2), Integer.valueOf(i3), Long.valueOf(j2)}); e eVar = this.iup; String cY = com.tencent.mm.plugin.exdevice.j.b.cY(j); synchronized (eVar.itw) { linkedList = new LinkedList(eVar.itw); } for (b d : linkedList) { d.d(cY, i2, j2); } linkedList.clear(); for (b d2 : eVar.itx.values()) { d2.d(cY, i2, j2); } ei eiVar = new ei(); eiVar.bMj.mac = cY; eiVar.bMj.bLv = i2; eiVar.bMj.bMg = j2; com.tencent.mm.sdk.b.a.sFg.a(eiVar, Looper.getMainLooper()); } }
package com.foodie.homeslice.dto; import java.util.List; public class ItemsResponseDto { private Integer statusCode; private String message; public List<ItemDetails> itemDetails; public Integer getStatusCode() { return statusCode; } public void setStatusCode(Integer statusCode) { this.statusCode = statusCode; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public List<ItemDetails> getItemDetails() { return itemDetails; } public void setItemDetails(List<ItemDetails> itemDetails) { this.itemDetails = itemDetails; } }
package ru.otus.l151.front; import ru.otus.l151.dataset.UserDataSet; import ru.otus.l151.messageSystem.Addressee; import ru.otus.l151.messageSystem.ControlBlock; import ru.otus.l151.messageSystem.Message; public interface FrontendService extends Addressee { void init(); void handleRequest(Message message); void deliverString(ControlBlock control, String text); void deliverUserDataSet(ControlBlock control, UserDataSet user); } /* vim: syntax=java:fileencoding=utf-8:fileformat=unix:tw=78:ts=4:sw=4:sts=4:et */ //EOF
package com.redbus.tests; import org.testng.annotations.Test; import org.testng.AssertJUnit; import org.testng.annotations.Test; import org.testng.AssertJUnit; import org.testng.annotations.Test; import org.testng.AssertJUnit; import static org.testng.Assert.assertEquals; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Set; import org.apache.log4j.Logger; import org.testng.AssertJUnit; import org.testng.annotations.Test; import com.redbus.pages.LoginPage; import com.redbus.testUtils.CommonAssertions; import com.redbus.utils.CommonUtils; import com.redbus.utils.ExtentReport; import com.relevantcodes.extentreports.LogStatus; public class LoginTest extends ExtentReport { public static final Logger log = Logger.getLogger(LoginTest.class); private String sheetName = "LoginData"; @Test public void invalid_login_PhoneNumber() throws InterruptedException { log.info("Valid Test: When User login by entering the wrong phonenumber"); extentTest = extent.startTest("Invalid scenario: When User login by entering the wrong phonenumber "); LoginPage login = new LoginPage(driver); String testName = "Invalid Scenario- Wrong phone number"; login.click_loginIcon(); log.info("Login Icon Clicked sucessfully!!"); extentTest.log(LogStatus.INFO, "Login Icon Clicked sucessfully!!"); login.click_signIn(); log.info("SignIn Clicked sucessfully!!"); extentTest.log(LogStatus.INFO, "SignIn Clicked sucessfully!!"); driver.switchTo().activeElement(); driver.switchTo().frame(login.iframe_1); HashMap<String, String> testData = new HashMap<String, String>(); testData = reader.getRowTestData(sheetName, testName); log.info(testData); String executionRequired = testData.get("Execution Required").toLowerCase(); String ph_no = testData.get("Phone Number"); CommonUtils.toCheckExecutionRequired(executionRequired); getImplicitlyWait(); login.enter_MobileNumber(ph_no); log.info("Error msg occured"); extentTest.log(LogStatus.INFO, "Error msg occured"); getImplicitlyWait(); String expectedTitle2 = login.Error_Msg(); AssertJUnit.assertEquals("Please enter valid mobile number", expectedTitle2); log.info("Assertion Passes, " + " Actual: " + "Please enter valid mobile number" + ",Expected: " + expectedTitle2); extentTest.log(LogStatus.INFO, "Assertion Passes, " + " Actual: " + "Please enter valid mobile number" + ",Expected: " + expectedTitle2); extentTest.log(LogStatus.INFO, "Test Case Passes -When User login by entering the wrong phonenumber"); } }
package ex1; import java.io.*; import java.util.*; public class WGraph_Algo implements weighted_graph_algorithms { private weighted_graph wg; /** * Init the graph on which this set of algorithms operates on. * * @param g */ @Override public void init(weighted_graph g) { wg=g; } /** * Return the underlying graph of which this class works. * * @return */ @Override public weighted_graph getGraph() { return wg; } /** * Compute a deep copy of this weighted graph. * Uses the WGraph_DS deep copy method in order to do so. * @return */ @Override public weighted_graph copy() { weighted_graph copy_graph = new WGraph_DS(wg); // make the designated copied graph return copy_graph; } /** * Returns true if and only if (iff) there is a valid path from EVREY node to each * other node. NOTE: assume ubdirectional graph. * * The algorithm goes over each node using BFS, marks it and then goes over its neighbours. * by the end of the algorithm all nodes should have been visited if the graph is connected. * Otherwise we return false as some nodes cannot be reached. * * @return */ @Override public boolean isConnected() { if (wg.nodeSize() == 0 || wg.nodeSize() == 1) // if our graph contains 0/1 nodes its connected. return true; for (node_info n : wg.getV()) { // set the distance to max for all nodes from the source node. n.setInfo("blue"); // lets mark all nodes as blue for unvisited. } Queue<node_info> queue = new LinkedList<>(); // we define a queue to save all nodes. queue.add(wg.getV().iterator().next());//add the first none null node to the queue. int count=0;//we mark the amount of nodes visited. while (!queue.isEmpty()) { //bfs node_info curr = queue.poll(); //pull the 1st node from the queue. for (node_info adjacent : wg.getV(curr.getKey())) {//iterate all of currs neibours. if (adjacent.getInfo()=="blue") {//if we haven't seen the neibour we put it in the queue. adjacent.setInfo("red"); count++; queue.add(adjacent); } } } if (count == wg.nodeSize()) { //we've implemented BFS meaning seen contains all nodes in the graph so their size must be equal. return true; } return false; } /** * returns the length of the shortest path between src to dest * Note: if no such path --> returns -1 * * Here we use Dijkstra's algorithm to traverse the graph: * * https://www.youtube.com/watch?v=pVfj6mxhdMw&ab_channel=ComputerScience * https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm#Using_a_priority_queue * * I used a priority queue to draw the node with the minimal distance each time(using comparator). * Each time you reach a node you store the distance from the source node to that node if the new distance is smaller. * * * @param src - start node * @param dest - end (target) node * @return */ @Override public double shortestPathDist(int src, int dest) { if (wg.getNode(src) == null || wg.getNode(dest) == null) // if our graph can't reach either of them. return -1; if (src == dest)// in case we get the same node. return 0; wg.getNode(src).setTag(0); PriorityQueue<node_info> queue = new PriorityQueue<>(11, new Comparator<node_info>() {//we define a comparator. @Override public int compare(node_info o1, node_info o2) { if(o1.getTag()<o2.getTag()) return -1; if(o1.getTag()>o2.getTag()) return 1; else return 0; } }); for (node_info n : wg.getV()) { // set the distance to max for all nodes from the source node. if(n.getKey()!=src) n.setTag(Integer.MAX_VALUE);// this will be the distance from src node. n.setInfo("blue"); // lets mark all nodes as blue for unvisited. } queue.add(wg.getNode(src));//we add the src node to the queue. while (!queue.isEmpty()) { node_info curr = queue.remove();//pull the first from the queue. curr.setInfo("red"); for (node_info adjacent : wg.getV(curr.getKey())) {//iterate all of currs neibours. if (adjacent.getInfo() == "blue") { // lets check all unvisited children if(adjacent.getTag()>(curr.getTag() + wg.getEdge(adjacent.getKey(), curr.getKey()))) {//if new distance is smaller, update the it. adjacent.setTag(curr.getTag() + wg.getEdge(adjacent.getKey(), curr.getKey()));//set the tag of the node to be the previous Weight + new Weight. queue.add(adjacent); } } } } return wg.getNode(dest).getTag(); //if we haven't found it return -1. } /** * returns the the shortest path between src to dest - as an ordered List of nodes: * src--> n1-->n2-->...dest * see: https://en.wikipedia.org/wiki/Shortest_path_problem * Note if no such path --> returns null; * * Here we use our previous algorithm shortestPathDist to calculate the distance to each node. * once done, all we left is to backtrack our way by choosing a neighbour that has a distance equal to our current node's - the weight of the edge between them. * * * @param src - start node * @param dest - end (target) node * @return */ @Override public List<node_info> shortestPath(int src, int dest) { if(wg.getNode(src)==null || wg.getNode(dest)==null)//if either of them doesn't exist we return null. return null; shortestPathDist(src,dest);//lets mark the distance between all nodes and the src. Queue<node_info> queue = new LinkedList<>(); // we define a queue to save all nodes. List<node_info> path = new LinkedList<>();//a list to return the path. path.add(wg.getNode(dest));//add the last to the list. if(src==dest) return path; queue.add(wg.getNode(dest)); //add the last to the queue. while (!queue.isEmpty()) { //commence bfs. node_info curr = queue.poll();//pull the first from the queue. for (node_info adjacent : wg.getV(curr.getKey())) {//iterate all of currs neibours. if (curr.getTag() == adjacent.getTag() + wg.getEdge(curr.getKey(),adjacent.getKey())) { //only move if the distance is one less. path.add(adjacent);//add it to the list. queue.add(adjacent);//add the node to the queue. if (adjacent.getKey() == src) {// if we reached the source we stop. Collections.reverse(path); return path; } break; //we can stop iterating the neighbours. } } } return path; } /** * Saves this weighted (undirected) graph to the given * file name * * @param file - the file name (may include a relative path). * @return true - iff the file was successfully saved */ @Override public boolean save(String file) { try { FileOutputStream fileOstrm=new FileOutputStream(file); ObjectOutputStream out= new ObjectOutputStream(fileOstrm); out.writeObject(wg); out.close(); fileOstrm.close(); return true; } catch (IOException ex) { return false; } } /** * This method load a graph to this graph algorithm. * if the file was successfully loaded - the underlying graph * of this class will be changed (to the loaded one), in case the * graph was not loaded the original graph should remain "as is". * * @param file - file name * @return true - iff the graph was successfully loaded. */ @Override public boolean load(String file) { weighted_graph wg1=null;//create the graph to be loaded into. try { FileInputStream fileIstrm = new FileInputStream(file); ObjectInputStream in=new ObjectInputStream(fileIstrm); wg1=(weighted_graph)in.readObject(); in.close(); fileIstrm.close(); wg=wg1; return true; } catch (IOException | ClassNotFoundException ex){ return false; } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.magapinv.www.reportes; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import net.sf.jasperreports.engine.JRException; import net.sf.jasperreports.engine.JasperFillManager; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.engine.JasperReport; import net.sf.jasperreports.engine.util.JRLoader; import net.sf.jasperreports.view.JasperViewer; /** * * @author mario */ public class Estado_Articulo { private Connection conexion; public final static String URL="jdbc:postgresql://192.168.185.2:5434/inventariobd"; public final static String DRIVER="org.postgresql.Driver"; public final static String USER="postgres"; public final static String PASS="Po$tgre$123"; public Estado_Articulo(){ try { Class.forName(DRIVER); conexion=DriverManager.getConnection(URL,USER,PASS); } catch (Exception ex) { } } public void ejecutarReporte_Estado_Articulo(String codigo_equipo) { try { String master = "C:\\reportes\\reporte_Estado_articulo.jasper"; String sub = "C:\\reportes\\reporte_Estado_articulo_count.jasper"; System.out.println("master " + master); if (master == null) { System.out.println("No encuentro el reporte"); System.exit(2); } JasperReport masterReport = null; JasperReport subReport = null; try { masterReport = (JasperReport) JRLoader.loadObject(master); subReport = (JasperReport) JRLoader.loadObject(sub); } catch (JRException ex) { Logger.getLogger(Stock_Articulos.class.getName()).log(Level.SEVERE, null, ex); } Map<String,Object> parametro = new HashMap<String,Object>(); parametro.put("estado_articulo", codigo_equipo); JasperPrint jasperPrint = JasperFillManager.fillReport(masterReport, parametro, conexion); JasperViewer jviewer = new JasperViewer(jasperPrint,false); jviewer.setVisible(true); } catch (JRException ex) { Logger.getLogger(Stock_Articulos.class.getName()).log(Level.SEVERE, null, ex); } } public void ejecutarReporte_Estado_Articulo_Grafico() { try { String master="C:\\reportes\\reporte_estados_articulo.jasper"; System.out.println("master " + master); if (master == null) { System.out.println("No encuentro el reporte"); System.exit(2); } JasperReport masterReport = null; try { masterReport = (JasperReport) JRLoader.loadObject(master); } catch (JRException ex) { Logger.getLogger(Stock_Articulos.class.getName()).log(Level.SEVERE, null, ex); } Map parametro = new HashMap(); JasperPrint jasperPrint = JasperFillManager.fillReport(masterReport, parametro, conexion); JasperViewer jviewer = new JasperViewer(jasperPrint,false); jviewer.setVisible(true); } catch (JRException ex) { Logger.getLogger(Stock_Articulos.class.getName()).log(Level.SEVERE, null, ex); } } public void cerrar() { try { conexion.close(); } catch (SQLException ex) { ex.printStackTrace(); } } }
package com.tencent.adasdemo.activity; import android.app.Activity; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Path; import android.graphics.RectF; import android.graphics.SurfaceTexture; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.ToneGenerator; import android.os.Bundle; import android.os.Handler; import android.os.SystemClock; import android.util.Log; import android.view.Surface; import android.view.TextureView; import android.view.Window; import android.view.WindowManager; import android.widget.RelativeLayout; import com.tencent.adas.ADASWrapper; import com.tencent.adas.CarDistance; import com.tencent.adas.Lane; import com.tencent.adasdemo.Constants; import com.tencent.adasdemo.CoverView; import com.tencent.adasdemo.R; import java.util.ArrayList; import java.util.Arrays; /** * 用于本地视频的演示 */ public class AdasActivity extends Activity implements TextureView.SurfaceTextureListener { private Handler mHandler = new Handler(); private ADASWrapper mADAS; private MediaPlayer mMediaPlayer; private TextureView mTextureView; int viewWidth = Constants.ADAS_WIDTH; int viewHeight = Constants.ADAS_HEIGHT; float widthRatio = 1920.0f / viewWidth; float heightRatio = 1080.0f / viewHeight; private RelativeLayout.LayoutParams layoutParams; CoverView coverView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); setContentView(R.layout.activity_adas); init(); } private void init() { layoutParams = new RelativeLayout.LayoutParams(viewWidth, viewHeight); layoutParams.leftMargin = 0; layoutParams.topMargin = 0; if (mADAS == null) { mADAS = new ADASWrapper(); mADAS.init(Constants.ADAS_WIDTH, Constants.ADAS_HEIGHT); } coverView = (CoverView) findViewById(R.id.coverView); coverView.setLayoutParams(layoutParams); mTextureView = (TextureView) findViewById(R.id.textureView); // SurfaceTexture is available only after the TextureView // is attached to a window and onAttachedToWindow() has been invoked. // We need to use SurfaceTextureListener to be notified when the SurfaceTexture // becomes available. mTextureView.setSurfaceTextureListener(this); } @Override protected void onDestroy() { super.onDestroy(); if (mHandler != null) { mHandler.removeCallbacks(frameWorker); } if (mMediaPlayer != null) { mMediaPlayer.stop(); mMediaPlayer.release(); mMediaPlayer = null; } if (mADAS != null) { mADAS.uninit(); } } @Override public void onSurfaceTextureAvailable(SurfaceTexture surfaceTexture, int width, int height) { Surface surface = new Surface(surfaceTexture); String path = getIntent().getStringExtra("path"); try { mMediaPlayer = new MediaPlayer(); mMediaPlayer.setDataSource(path); mMediaPlayer.setSurface(surface); mMediaPlayer.setLooping(true); // don't forget to call MediaPlayer.prepareAsync() method when you use constructor for // creating MediaPlayer mMediaPlayer.prepareAsync(); // Play video when the media source is ready for playback. mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mediaPlayer) { mediaPlayer.start(); if (Constants.ADAS_WIDTH == mTextureView.getWidth()) { widthRatio = Constants.ADAS_WIDTH / mTextureView.getWidth(); } else { widthRatio = Constants.ADAS_WIDTH * 1.0f / mTextureView.getWidth(); } if (Constants.ADAS_HEIGHT == mTextureView.getHeight()) { heightRatio = Constants.ADAS_HEIGHT / mTextureView.getHeight(); } else { heightRatio = Constants.ADAS_HEIGHT * 1.0f / mTextureView.getHeight(); } mHandler.postDelayed(frameWorker, 100); } }); } catch (Exception e) { e.printStackTrace(); } } @Override public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) { } @Override public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) { return true; } @Override public void onSurfaceTextureUpdated(SurfaceTexture surface) { } private byte[] getNV21(int inputWidth, int inputHeight, Bitmap scaled) { int[] argb = new int[inputWidth * inputHeight]; scaled.getPixels(argb, 0, inputWidth, 0, 0, inputWidth, inputHeight); byte[] yuv = new byte[inputWidth * inputHeight * 3 / 2]; encodeYUV420SP(yuv, argb, inputWidth, inputHeight); return yuv; } private void encodeYUV420SP(byte[] yuv420sp, int[] argb, int width, int height) { final int frameSize = width * height; int yIndex = 0; int uvIndex = frameSize; int a, R, G, B, Y, U, V; int index = 0; for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { a = (argb[index] & 0xff000000) >> 24; // a is not used obviously R = (argb[index] & 0xff0000) >> 16; G = (argb[index] & 0xff00) >> 8; B = (argb[index] & 0xff) & 0xff; // well known RGB to YUV algorithm Y = ((66 * R + 129 * G + 25 * B + 128) >> 8) + 16; U = ((-38 * R - 74 * G + 112 * B + 128) >> 8) + 128; V = ((112 * R - 94 * G - 18 * B + 128) >> 8) + 128; // NV21 has a plane of Y and interleaved planes of VU each sampled by a factor of 2 // meaning for every 4 Y pixels there are 1 V and 1 U. Note the sampling is every other // pixel AND every other scanline. yuv420sp[yIndex++] = (byte) ((Y < 0) ? 0 : ((Y > 255) ? 255 : Y)); if (j % 2 == 0 && index % 2 == 0) { yuv420sp[uvIndex++] = (byte) ((V < 0) ? 0 : ((V > 255) ? 255 : V)); yuv420sp[uvIndex++] = (byte) ((U < 0) ? 0 : ((U > 255) ? 255 : U)); } index++; } } } private void carDetect(byte[] source, CoverView coverView) { long curTime = 0; float time = 0; curTime = SystemClock.elapsedRealtimeNanos(); CarDistance distance[] = null; distance = mADAS.carDetect(curTime, source); time = (SystemClock.elapsedRealtimeNanos() - curTime) / 1000000000.0f; if (distance != null && distance.length > 0) { boolean debug_Gotconstance = false; for (CarDistance item : distance) { Log.d("ADAS_CAR", item.toString() + " time: " + time + "s"); RectF rect = new RectF(item.x / widthRatio, item.y / widthRatio, (item.x + item.width) / widthRatio, (item.y + item.height) / heightRatio); coverView.addRect(rect, Integer.toString(item.distance) + "m"); // TODO: 16/6/9 remove debug code float maxH = item.y + item.height; if (!debug_Gotconstance && maxH > 0 && maxH <= Constants.ADAS_WIDTH) { debug_Gotconstance = true; } } if (debug_Gotconstance) { tone(); } } } private void tone() { int volume = 50; AudioManager am = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE); if (am != null) { int maxVol = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC); int curVol = am.getStreamVolume(AudioManager.STREAM_MUSIC); volume = 100 * curVol / maxVol; } ToneGenerator toneG = new ToneGenerator(AudioManager.STREAM_ALARM, volume); toneG.startTone(ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD, 200); } private void laneDetect(byte[] frame, CoverView coverView) { long curTime = 0; float time = 0; curTime = SystemClock.elapsedRealtimeNanos(); Lane lane[] = mADAS.LaneDetect(frame, frame.length); time = (SystemClock.elapsedRealtimeNanos() - curTime) / 1000000000.0f; if (lane != null && lane.length == 2) { ArrayList<Path> paths = new ArrayList<>(); Path path = new Path(); Log.d("Jeff","drawing the lines"); /*path.moveTo(lane[0].x1 / widthRatio, lane[0].y1 / heightRatio); path.lineTo(lane[0].x2 / widthRatio, lane[0].y2 / heightRatio); path.lineTo(lane[1].x2 / widthRatio, lane[1].y2 / heightRatio); path.lineTo(lane[1].x1 / widthRatio, lane[1].y1 / heightRatio); path.lineTo(lane[0].x1 / widthRatio, lane[0].y1 / heightRatio); paths.add(path);*/ float daltX1 = (lane[0].x2 - lane[0].x1) / 5; float daltY1 = (lane[0].y2 - lane[0].y1) / 5; float daltX2 = (lane[1].x2 - lane[1].x1) / 5; float daltY2 = (lane[1].y2 - lane[1].y1) / 5; for (int i = 0; i < 5; i++) { Path p = new Path(); p.moveTo((lane[0].x1 + daltX1 * (i + 1)) / widthRatio, (lane[0].y1 + daltY1 * (i + 1)) / heightRatio); p.lineTo((lane[1].x1 + daltX2 * (i + 1)) / widthRatio, (lane[1].y1 + daltY2 * (i + 1)) / heightRatio); paths.add(p); } coverView.addPath(paths); } } Runnable frameWorker = new Runnable() { @Override public void run() { new Thread() { @Override public void run() { Bitmap source = null; if (mTextureView != null) { source = mTextureView.getBitmap(Constants.ADAS_WIDTH, Constants.ADAS_HEIGHT); } if (source != null) { // 获取 NV21 的数据 byte[] data = getNV21(Constants.ADAS_WIDTH, Constants.ADAS_HEIGHT, source); data = Arrays.copyOf(data, Constants.ADAS_WIDTH * Constants.ADAS_HEIGHT); coverView.clear(); carDetect(data, coverView); laneDetect(data, coverView); } mHandler.post(new Runnable() { @Override public void run() { coverView.invalidate(); } }); mHandler.post(frameWorker); } }.start(); } }; }
package com.tencent.mm.plugin.appbrand.appusage; import android.os.Parcel; import com.tencent.mm.ipcinvoker.i; import com.tencent.mm.ipcinvoker.type.IPCInteger; import com.tencent.mm.plugin.appbrand.app.e; final class h$a implements i<IPCInteger, Parcel> { private h$a() { } private static Parcel a(IPCInteger iPCInteger) { Parcel obtain = Parcel.obtain(); try { obtain.writeTypedList(((g) e.x(g.class)).B(iPCInteger.value, false)); return obtain; } catch (Exception e) { obtain.setDataPosition(0); obtain.writeTypedList(null); return obtain; } } }
package istic.pr.socket.tcp.echo; import java.io.*; import java.net.*; public class ClientTCP { public static void main(String[] args) { // Port et adresse du seveur int portServeur = 9999; String adresseServeur = "localhost"; try (Socket socketVersLeServeur = new Socket(adresseServeur, portServeur)) { //créer reader et writer liés au socket BufferedReader reader = creerReader(socketVersLeServeur); PrintWriter printer = creerPrinter(socketVersLeServeur); // String contenant le message reçu String mot = recevoirMessage(reader); System.out.println(mot); // String lisant le message lui au clavier String motLu = lireMessageAuClavier(); // Tant que la chaîne de caractères n'est pas "fin", on lit // l'entrée clavier while (!motLu.equals("fin")) { // On envoit le message au serveur envoyerMessage(printer, motLu); // On reçoit et affiche le message reçu du serveur en réponse mot = recevoirMessage(reader); System.out.println(mot); motLu = lireMessageAuClavier(); } // On ferme le socket socketVersLeServeur.close(); } catch (IOException e) { System.out.println("Erreur ->" + e.getMessage()); } } public static String lireMessageAuClavier() throws IOException { // Lit un message saisit au clavier InputStreamReader reader = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(reader); return in.readLine(); } public static BufferedReader creerReader(Socket socketVersUnClient) throws IOException { BufferedReader readerIn = new BufferedReader(new InputStreamReader(socketVersUnClient.getInputStream())); return readerIn; } public static PrintWriter creerPrinter(Socket socketVersUnClient) throws IOException { PrintWriter printerOut = new PrintWriter(new OutputStreamWriter(socketVersUnClient.getOutputStream())); return printerOut; } public static String recevoirMessage(BufferedReader reader) throws IOException { // On récupère la ligne courante String currentLine = reader.readLine(); // Si elle est vide if(currentLine.equals("")) return "Ligne vide"; // Sinon on la retourne return currentLine; } public static void envoyerMessage(PrintWriter p, String message) throws IOException { // On envoit le message au client p.println(message); p.flush(); } }
package com.infogen.self_description.annotation; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Repeatable; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * 方法入参的描述 * * @author larry/larrylv@outlook.com/创建时间 2015年4月2日 下午12:18:07 * @since 1.0 * @version 1.0 */ @Repeatable(InParameters.class) @Target({ ElementType.METHOD, ElementType.TYPE, ElementType.LOCAL_VARIABLE }) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface InParam { public String name(); public String describe(); }
package com.tencent.mm.g.a; import com.tencent.mm.sdk.b.b; public final class ef extends b { public a bMc; public ef() { this((byte) 0); } private ef(byte b) { this.bMc = new a(); this.sFm = false; this.bJX = null; } }
package com.zzx.test.mergeTest; import java.util.*; public class MergeTest { @org.junit.Test public void mergeTest() { long time = new Date().getTime(); LinkedList<PackageInfo> list = new LinkedList<>(); Random r = new Random(); for (int i = 0; i < 1000; i++) { PackageInfo packageInfo = new PackageInfo(); packageInfo.setId(i); packageInfo.setGoodsId(r.nextInt(500)); packageInfo.setGoodsNumber(r.nextInt(100)); list.add(packageInfo); } // System.out.println(list); list.sort(Comparator.comparing(PackageInfo::getGoodsId)); // System.out.println(list); List<PackageInfo> removeIndexs = new LinkedList<>(); for (int i = 0; i < list.size(); i++) { if (i == list.size() - 1) break; PackageInfo currentPackageInfo = list.get(i); PackageInfo nextPackageInfo = list.get(i + 1); int currentGoodsId = currentPackageInfo.getGoodsId(); if (currentPackageInfo.getGoodsNumber() == 0) { removeIndexs.add(currentPackageInfo); // 清除随机到数量为 0 的数据 continue; } if (currentGoodsId != nextPackageInfo.getGoodsId()) continue; int goodsMax = 100;// 暂定加入背包的这个物品读取的上限是100(待读配置) mergeAlgorithm(currentPackageInfo, nextPackageInfo, goodsMax, i, removeIndexs, list); } System.out.println(list); System.out.println(new Date().getTime() - time); } /** * 如果相同的物品id,则找到该物品的最后一个, * 从最后面的两个物品向前累加 * @param currentPackageInfo 当前的物品对象 * @param nextPackageInfo 下一个的物品对象 * @param goodsMax 物品格子上限 * @param index 当前物品对象的索引位置 * @param removeIndexs 要移除的list * @param list 要整理的物品对象(背包或仓库)列表 */ private void mergeAlgorithm(PackageInfo currentPackageInfo, PackageInfo nextPackageInfo, int goodsMax, int index, List<PackageInfo> removeIndexs, List<PackageInfo> list) { if (index + 2 < list.size() - 1) { if (nextPackageInfo.getGoodsId() == list.get(index + 2).getGoodsId()) { mergeAlgorithm(nextPackageInfo,list.get(index + 2), goodsMax, index + 1, removeIndexs, list); } } int currentGoodsNumber = currentPackageInfo.getGoodsNumber(); int nextGoodsNumber = nextPackageInfo.getGoodsNumber(); if (currentGoodsNumber + nextGoodsNumber > goodsMax) { currentPackageInfo.setGoodsNumber(goodsMax); nextPackageInfo.setGoodsNumber(currentGoodsNumber + nextGoodsNumber - goodsMax); } else { if (nextPackageInfo.getGoodsNumber() > 0) { currentPackageInfo.setGoodsNumber(currentGoodsNumber + nextGoodsNumber); nextPackageInfo.setGoodsNumber(0); removeIndexs.add(nextPackageInfo); } } } }
package cn.canlnac.onlinecourse.presentation.mapper; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import cn.canlnac.onlinecourse.domain.Reply; import cn.canlnac.onlinecourse.domain.SimpleUser; import cn.canlnac.onlinecourse.presentation.internal.di.PerActivity; import cn.canlnac.onlinecourse.presentation.model.ReplyModel; @PerActivity public class ReplyModelDataMapper { private final SimpleUserModelDataMapper simpleUserModelDataMapper; @Inject public ReplyModelDataMapper(SimpleUserModelDataMapper simpleUserModelDataMapper) { this.simpleUserModelDataMapper = simpleUserModelDataMapper; } public ReplyModel transform(Reply reply) { if (reply == null) { throw new IllegalArgumentException("Cannot transform a null value"); } ReplyModel replyModel = new ReplyModel(); replyModel.setId(reply.getId()); replyModel.setDate(reply.getDate()); if (reply.getAuthor() == null) { reply.setAuthor(new SimpleUser()); } replyModel.setAuthor(simpleUserModelDataMapper.transform(reply.getAuthor())); replyModel.setContent(reply.getContent()); if (reply.getToUser() == null) { reply.setToUser(new SimpleUser()); } replyModel.setToUser(simpleUserModelDataMapper.transform(reply.getToUser())); return replyModel; } public List<ReplyModel> transform(List<Reply> replyList) { List<ReplyModel> replyModelList = new ArrayList<>(replyList.size()); ReplyModel replyModel; for (Reply reply : replyList) { replyModel = transform(reply); if (reply != null) { replyModelList.add(replyModel); } } return replyModelList; } }
package developer.arish.org.sharing; import android.app.ActivityOptions; import android.content.Intent; import android.graphics.Paint; import android.graphics.drawable.ShapeDrawable; import android.graphics.drawable.shapes.OvalShape; import android.os.Bundle; import android.support.v7.app.ActionBar; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.Spinner; import android.widget.TextView; import com.facebook.CallbackManager; import com.facebook.FacebookCallback; import com.facebook.FacebookException; import com.facebook.FacebookSdk; import com.facebook.Profile; import com.facebook.ProfileTracker; import com.facebook.appevents.AppEventsLogger; import com.facebook.login.LoginManager; import com.facebook.login.LoginResult; import com.facebook.login.widget.LoginButton; import com.facebook.login.widget.ProfilePictureView; import com.parse.FindCallback; import com.parse.ParseException; import com.parse.ParseObject; import com.parse.ParseQuery; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class MainActivity extends BaseActivity { protected static final int SPINNER_ITEM_HEADER = 0; protected static final int SPINNER_ITEM_SUBHEADER = 1; protected static final int SPINNER_ITEM_FEEDS = 2; protected static final int SPINNER_ITEM_GROUP_FEEDS = 3; protected static final int SPINNER_ITEM_PAGE_FEEDS = 4; protected static final int SPINNER_SEPARATOR = 5; private static final int[] SPINNER_TITLE_RES_ID = new int[]{ R.string.what_new }; private List<String> permissions = new ArrayList<>(); private ArrayList<Integer> mSpinnerItems = new ArrayList<Integer>(); // views that correspond to each navdrawer item, null if not yet created private View[] mSpinnerItemViews = null; private LinearLayout fabLayout; private RecyclerView mRecyclerView; private RecyclerView.Adapter mAdapter; private RecyclerView.LayoutManager mLayoutManager; private List<ParseData> data; private static final String KEY_ID = "ViewTransitionValues:id"; private static final int MODE_EXPLORE = 0; private int mMode = MODE_EXPLORE; private boolean mSpinnerConfigured = false; private String TAG = "Spinner"; private ExploreSpinnerAdapter mTopLevelSpinnerAdapter = new ExploreSpinnerAdapter(true); private int pos; private CallbackManager callbackManager; private ProfileTracker profileTracker; private ProfilePictureView profilePictureView; private LoginButton loginBtn; private TextView nameTextView; private TextView emailTextView; @Override protected int getSelfNavDrawerItem() { return NAVDRAWER_ITEM_FEEDS; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FacebookSdk.sdkInitialize(this.getApplicationContext()); callbackManager = CallbackManager.Factory.create(); LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { updateUI(); } @Override public void onCancel() { } @Override public void onError(FacebookException exception) { } }); setContentView(R.layout.activity_main); loginBtn = (LoginButton)findViewById(R.id.loginButton); permissions.add("user_friends"); permissions.add("email"); loginBtn.setReadPermissions(Arrays.asList("user_friends", "email")); loginBtn.registerCallback(callbackManager, new FacebookCallback<LoginResult>() { @Override public void onSuccess(LoginResult loginResult) { // App code } @Override public void onCancel() { // App code } @Override public void onError(FacebookException exception) { // App code } }); profileTracker = new ProfileTracker() { @Override protected void onCurrentProfileChanged(Profile oldProfile, Profile currentProfile) { updateUI(); // It's possible that we were waiting for Profile to be populated in order to // post a status update. } }; Toolbar toolbar = getActionBarToolbar(); fabLayout = (LinearLayout) findViewById(R.id.fab_layout); fabLayout.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(MainActivity.this, Post.class); i.putExtra(KEY_ID, v.getTransitionName()); ActivityOptions activityOptions = ActivityOptions.makeSceneTransitionAnimation(MainActivity.this, v, "hero"); startActivity(i, activityOptions.toBundle()); } }); mRecyclerView = (RecyclerView) findViewById(R.id.my_recycler_view); mRecyclerView.setHasFixedSize(true); mAdapter = new MyAdapter(this, getData()); mRecyclerView.setAdapter(mAdapter); mLayoutManager = new LinearLayoutManager(this); mRecyclerView.setLayoutManager(mLayoutManager); trySetUpActionBarSpinner(); } /** private void setRef(){ adapter = new ViewPagerAdapter(getSupportFragmentManager(), Titles, numOfTabs); pager = (ViewPager) findViewById(R.id.pager); pager.setAdapter(adapter); tabs =(SlidingTabLayout)findViewById(R.id.tabs); tabs.setDistributeEvenly(true); tabs.setCustomTabColorizer(new SlidingTabLayout.TabColorizer() { @Override public int getIndicatorColor(int position) { return getResources().getColor(R.color.accent); } }); tabs.setViewPager(pager); } */ private List<ParseData> getData() { data = new ArrayList<ParseData>(); ParseQuery<ParseObject> query = ParseQuery.getQuery("PostCompose"); query.fromLocalDatastore(); query.findInBackground(new FindCallback<ParseObject>() { public void done(List<ParseObject> list, ParseException e) { for (int i = 0; i < list.size(); i++) { ParseData current = new ParseData(); current.title = list.get(list.size() - 1 - i).getString("title"); current.description = list.get(list.size() - 1 - i).getString("description"); // current.imageData = list.get(list.size() - 1).getBytes("imagePosted"); data.add(current); } Log.d("Loading", "The data is fully loaded!"); } }); return data; } public void openDetails(int position) { ParseQuery<ParseObject> query = ParseQuery.getQuery("PostCompose"); query.fromLocalDatastore(); pos = position; query.findInBackground(new FindCallback<ParseObject>() { @Override public void done(List<ParseObject> list, ParseException e) { String tit = list.get(pos).getString("title"); String des = list.get(pos).getString("description"); start(tit, des); } }); } private void start(String tit, String des) { startActivity(new Intent(getBaseContext(), FeedDetails.class)); } private void trySetUpActionBarSpinner() { Toolbar toolbar = getActionBarToolbar(); if (mMode != MODE_EXPLORE || mSpinnerConfigured || toolbar == null) { // already done it, or not ready yet, or don't need to do Log.d("Spinner", "Not configuring Action Bar spinner."); return; } Log.d(TAG, "Configuring Action Bar spinner."); mSpinnerConfigured = true; mTopLevelSpinnerAdapter.clear(); mTopLevelSpinnerAdapter.addItem(getString(R.string.home), false, 0); mTopLevelSpinnerAdapter.addHeader(getString(R.string.types)); int tagColor = getResources().getColor(R.color.default_session_color); mTopLevelSpinnerAdapter.addItem(getString(R.string.group), false, tagColor); mTopLevelSpinnerAdapter.addItem(getString(R.string.navdrawer_item_notifications), false, tagColor); mTopLevelSpinnerAdapter.addItem(getString(R.string.communities), false, tagColor); mTopLevelSpinnerAdapter.addItem(getString(R.string.collections), false, tagColor); String categoryTitle = getString(R.string.spinner_sub_header); mTopLevelSpinnerAdapter.addHeader(categoryTitle); int i; for (i = 0; i < SPINNER_TITLE_RES_ID.length; i++) { String category = getString(SPINNER_TITLE_RES_ID[i]); mTopLevelSpinnerAdapter.addItem(category, true, tagColor); } View spinnerContainer = LayoutInflater.from(this).inflate(R.layout.actionbar_spinner, toolbar, false); ActionBar.LayoutParams lp = new ActionBar.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); toolbar.addView(spinnerContainer, lp); Spinner spinner = (Spinner) spinnerContainer.findViewById(R.id.actionbar_spinner); spinner.setAdapter(mTopLevelSpinnerAdapter); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> spinner, View view, int position, long itemId) { } @Override public void onNothingSelected(AdapterView<?> adapterView) { } }); /** if (itemToSelect >= 0) { Log.d(TAG, "Restoring item selection to primary spinner: " + itemToSelect); spinner.setSelection(itemToSelect); }*/ } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { // If the nav drawer is open, hide action items related to the content view return super.onPrepareOptionsMenu(menu); } private class ExploreSpinnerItem { boolean isHeader; String tag, title; int color; boolean indented; ExploreSpinnerItem(boolean isHeader, String tag, String title, boolean indented, int color) { this.isHeader = isHeader; this.tag = tag; this.title = title; this.indented = indented; this.color = color; } } private class ExploreSpinnerAdapter extends BaseAdapter { private int mDotSize; private boolean mTopLevel; private ExploreSpinnerAdapter(boolean topLevel) { this.mTopLevel = topLevel; } // pairs of (tag, title) private ArrayList<ExploreSpinnerItem> mItems = new ArrayList<ExploreSpinnerItem>(); public void clear() { mItems.clear(); } public void addItem(String title, boolean indented, int color) { mItems.add(new ExploreSpinnerItem(false, "", title, indented, color)); } public void addHeader(String title) { mItems.add(new ExploreSpinnerItem(true, "", title, false, 0)); } @Override public int getCount() { return mItems.size(); } @Override public Object getItem(int position) { return mItems.get(position); } @Override public long getItemId(int position) { return position; } private boolean isHeader(int position) { return position >= 0 && position < mItems.size() && mItems.get(position).isHeader; } @Override public View getDropDownView(int position, View view, ViewGroup parent) { if (view == null || !view.getTag().toString().equals("DROPDOWN")) { view = getLayoutInflater().inflate(R.layout.explore_spinner_item_dropdown, parent, false); view.setTag("DROPDOWN"); } TextView headerTextView = (TextView) view.findViewById(R.id.header_text); View dividerView = view.findViewById(R.id.divider_view); TextView normalTextView = (TextView) view.findViewById(android.R.id.text1); if (isHeader(position)) { headerTextView.setText(getTitle(position)); headerTextView.setVisibility(View.VISIBLE); normalTextView.setVisibility(View.GONE); dividerView.setVisibility(View.VISIBLE); } else { headerTextView.setVisibility(View.GONE); normalTextView.setVisibility(View.VISIBLE); dividerView.setVisibility(View.GONE); setUpNormalDropdownView(position, normalTextView); } return view; } @Override public View getView(int position, View view, ViewGroup parent) { if (view == null || !view.getTag().toString().equals("NON_DROPDOWN")) { view = getLayoutInflater().inflate(mTopLevel ? R.layout.explore_spinner_item_actionbar : R.layout.explore_spinner_item, parent, false); view.setTag("NON_DROPDOWN"); } TextView textView = (TextView) view.findViewById(android.R.id.text1); textView.setText(getTitle(position)); return view; } private String getTitle(int position) { return position >= 0 && position < mItems.size() ? mItems.get(position).title : ""; } private int getColor(int position) { return position >= 0 && position < mItems.size() ? mItems.get(position).color : 0; } private String getTag(int position) { return position >= 0 && position < mItems.size() ? mItems.get(position).tag : ""; } private void setUpNormalDropdownView(int position, TextView textView) { textView.setText(getTitle(position)); ShapeDrawable colorDrawable = (ShapeDrawable) textView.getCompoundDrawables()[2]; int color = getColor(position); if (color == 0) { if (colorDrawable != null) { textView.setCompoundDrawables(null, null, null, null); } } else { if (mDotSize == 0) { mDotSize = getResources().getDimensionPixelSize( R.dimen.tag_color_dot_size); } if (colorDrawable == null) { colorDrawable = new ShapeDrawable(new OvalShape()); colorDrawable.setIntrinsicWidth(mDotSize); colorDrawable.setIntrinsicHeight(mDotSize); colorDrawable.getPaint().setStyle(Paint.Style.FILL); textView.setCompoundDrawablesWithIntrinsicBounds(null, null, colorDrawable, null); } colorDrawable.getPaint().setColor(color); } } @Override public boolean isEnabled(int position) { return !isHeader(position); } @Override public int getItemViewType(int position) { return 0; } @Override public int getViewTypeCount() { return 1; } @Override public boolean areAllItemsEnabled() { return false; } } @Override protected void onResume() { super.onResume(); // Call the 'activateApp' method to log an app event for use in analytics and advertising // reporting. Do so in the onResume methods of the primary Activities that an app may be // launched into. AppEventsLogger.activateApp(this); updateUI(); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); callbackManager.onActivityResult(requestCode, resultCode, data); } @Override public void onPause() { super.onPause(); // Call the 'deactivateApp' method to log an app event for use in analytics and advertising // reporting. Do so in the onPause methods of the primary Activities that an app may be // launched into. AppEventsLogger.deactivateApp(this); } @Override protected void onDestroy() { super.onDestroy(); profileTracker.stopTracking(); } private void updateUI() { profilePictureView = getProfilePictureView(); nameTextView = getNameTextView(); emailTextView = getEmailTextView(); Profile profile = Profile.getCurrentProfile(); if (profile != null) { profilePictureView.setProfileId(profile.getId()); nameTextView.setText(profile.getName()); } else { profilePictureView.setProfileId(null); } } }
package disciplinas; import java.util.ArrayList; import java.util.List; public class PreencherMatrizCurricular { protected static List<Disciplina> disciplinas = new ArrayList<>(); public static List<Disciplina> getDisciplinas() { return disciplinas; } public static void setDisciplinas(List<Disciplina> disciplinas) { PreencherMatrizCurricular.disciplinas = disciplinas; } public static void criarDisciplinas() { semestre1(); semestre2(); semestre3(); semestre4(); semestre5(); semestre6(); semestre7(); semestre8(); } private static void semestre8() { //8º Semestre (5) disciplinas.add(new Disciplina("N525", 8, "COMPILADORES I", getDisciplina("N587"))); disciplinas.add(new Disciplina("N534", 8, "GERENCIA DE PROJETOS", getDisciplina("N562"))); disciplinas.add(new Disciplina("N589", 8, "PROCESSAMENTO DE IMAGENS", getDisciplina("N094"), getDisciplina("N512"))); disciplinas.add(new Disciplina("N597", 8, "TRABALHO CONCLUSAO DE CURSO II", getDisciplina("N596"))); disciplinas.add(new Disciplina("N598", 8, "SISTEMAS DISTRIBUIDOS", getDisciplina("N562"), getDisciplina("T958"))); } private static void semestre7() { //7º Semestre (6) disciplinas.add(new Disciplina("N517", 7, "ENGENHARIA DE SOFTWARE", getDisciplina("N562"))); disciplinas.add(new Disciplina("N519", 7, "INTELIGENCIA ARTIFICIAL", getDisciplina("N097"), getDisciplina("N593"), getDisciplina("N584"))); disciplinas.add(new Disciplina("N521", 7, "COMPUTACAO GRAFICA", getDisciplina("N617"), getDisciplina("N524"))); disciplinas.add(new Disciplina("N588", 7, "COMPUTABILIDADE", getDisciplina("N587"))); disciplinas.add(new Disciplina("N595", 7, "REDES DE COMPUTADORES II", getDisciplina("T958"))); disciplinas.add(new Disciplina("N596", 7, "TRABALHO CONCLUSAO CURSO I", getDisciplina("N421"), getDisciplina("N592"), getDisciplina("T958"), getDisciplina("N672"))); } private static void semestre6() { //6º Semestre (5) disciplinas.add(new Disciplina("N562", 6, "ANALISE E PROJETO SISTEMAS II", getDisciplina("N672"))); disciplinas.add(new Disciplina("N564", 6, "PESQUISA OPERACIONAL", getDisciplina("N617"))); disciplinas.add(new Disciplina("N587", 6, "TEORIA DOS AUT E LING FORMAIS", getDisciplina("N097"), getDisciplina("N583"))); disciplinas.add(new Disciplina("N593", 6, "PARADIGMAS DE LING PROGRAMACAO", getDisciplina("N512"))); disciplinas.add(new Disciplina("T958", 6, "REDES DE COMPUTADORES", getDisciplina("T952"))); } private static void semestre5() { //5º Semestre (6) disciplinas.add(new Disciplina("N421", 5, "PRODUÇÃO DE TRAB CIENTÍFICOS")); disciplinas.add(new Disciplina("N565", 5, "GESTAO DA TECN DA INFORMACAO", getDisciplina("N620"))); disciplinas.add(new Disciplina("N584", 5, "PROJ ANALISE DE ALGORITMOS", getDisciplina("N618"), getDisciplina("N583"))); disciplinas.add(new Disciplina("N592", 5, "TEC DE IMPL DE SISTEMAS DE BD", getDisciplina("N673"))); disciplinas.add(new Disciplina("N672", 5, "ENG REQUISITOS TESTE SOFTWARE", getDisciplina("N579"), getDisciplina("N524"))); disciplinas.add(new Disciplina("T952", 5, "SISTEMAS OPERACIONAIS", getDisciplina("N607"), getDisciplina("T922"))); } private static void semestre4() { //4º Semestre (5) disciplinas.add(new Disciplina("N554", 4, "TECNOLOGIAS INTERNET I", getDisciplina("N524"))); disciplinas.add(new Disciplina("N583", 4, "TEORIA DOS GRAFOS", getDisciplina("N512"))); disciplinas.add(new Disciplina("N617", 4, "CÁLCULO NUMÉRICO", getDisciplina("N094"), getDisciplina("N611"), getDisciplina("N573"))); disciplinas.add(new Disciplina("N618", 4, "PROBABILIDADE E ESTATÍSTICA")); disciplinas.add(new Disciplina("N673", 4, "FUNDAMENTOS DE BANCO DE DADOS", getDisciplina("N512"))); } private static void semestre3() { //3º Semestre (5) disciplinas.add(new Disciplina("N097", 3, "LOGICA MATEMATICA", getDisciplina("N096"))); disciplinas.add(new Disciplina("N524", 3, "TECNICAS DE PROGRAMACAO", getDisciplina("T922"))); disciplinas.add(new Disciplina("N607", 3, "ARQUIT E ORG DE COMPUTADORES", getDisciplina("N532"))); disciplinas.add(new Disciplina("N620", 3, "ADMIN, EMPREEND E INOVAÇÃO")); disciplinas.add(new Disciplina("N512", 3, "ESTRUTURA DE DADOS", getDisciplina("T922"))); } private static void semestre2() { //2º Semestre (5) disciplinas.add(new Disciplina("N094", 2, "ALG LINEAR E GEOM ANALÍTICA")); disciplinas.add(new Disciplina("N532", 2, "SISTEMAS LOGICOS E DIGITAIS", getDisciplina("N096"))); disciplinas.add(new Disciplina("N579", 2, "PROJETO DE INTERFACE", getDisciplina("N573"))); disciplinas.add(new Disciplina("N611", 2, "CÁLCULO II", getDisciplina("N610"))); disciplinas.add(new Disciplina("T922", 2, "PROG ORIENTADA A OBJETOS", getDisciplina("N573"))); } private static void semestre1() { //1º Semestre (5) disciplinas.add(new Disciplina("N096", 1, "MATEMATICA DISCRETA")); disciplinas.add(new Disciplina("N501", 1, "INTRODUCAO A COMPUTACAO")); disciplinas.add(new Disciplina("N573", 1, "LOGICA DE PROGRAMACAO")); disciplinas.add(new Disciplina("N605", 1, "INFORMÁTICA E SOCIEDADE")); disciplinas.add(new Disciplina("N610", 1, "CÁLCULO I")); } private static Disciplina getDisciplina(String codigo) { for (Disciplina disciplina : disciplinas) { if (codigo.equals(disciplina.getCodigo())) { return disciplina; } } return null; } public static void imprimirMatrizCurricular() { for (Disciplina disciplina : disciplinas) { System.out.printf("Semestre: %d\tCodigo: %s\tNome: %s\n", disciplina.getSemestre(), disciplina.getCodigo(), disciplina.getNome()); if (disciplina.getPreRequisitos().length > 0) { System.out.println("Pre-Requisito"); for (Disciplina preRequisito : disciplina.getPreRequisitos()) { System.err.printf("Semestre: %d\tCodigo: %s\tNome: %s\n", preRequisito.getSemestre(), preRequisito.getCodigo(), preRequisito.getNome()); } } } } }
/* * Copyright 2017 University of Michigan * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package edu.umich.verdict.relation; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; public class SamplePlans { private List<SamplePlan> plans; public SamplePlans() { this(new ArrayList<SamplePlan>()); } public SamplePlans(List<SamplePlan> plans) { this.plans = plans; } public void add(SamplePlan plan) { plans.add(plan); } public List<SamplePlan> getPlans() { return plans; } /** * Creates candidate plans that can answer one more expression. * * @param groups * A candidate approx relations that can answer an expression */ public void consolidateNewExpr(List<SampleGroup> groups) { List<SamplePlan> newPlans = new ArrayList<SamplePlan>(); if (plans.size() == 0) { for (SampleGroup group : groups) { newPlans.add(new SamplePlan(Arrays.asList(group))); } } else { for (SamplePlan oldPlan : plans) { for (SampleGroup group : groups) { newPlans.add(oldPlan.createByMerge(group)); } } } this.plans = newPlans; prune(10); } // keeps the top 'num' number of plans. // this method does not remove the plan that includes only a single sample // group. public void prune(int num) { Comparator<SamplePlan> costComparator = new Comparator<SamplePlan>() { @Override public int compare(SamplePlan a, SamplePlan b) { if (a.cost() < b.cost()) { return -1; } else if (a.cost() > b.cost()) { return 1; } else { return 0; } } }; Collections.sort(plans, costComparator); List<SamplePlan> newPlans = new ArrayList<SamplePlan>(); for (int i = 0; i < plans.size(); i++) { if (num > 0) { newPlans.add(plans.get(i)); num--; continue; } if (plans.get(i).getSampleGroups().size() == 1) { newPlans.add(plans.get(i)); } } plans = newPlans; } public SamplePlan bestPlan(double relative_cost_ratio) { // find the original plan (the plan that uses the original tables) and the cost // of the plan. double original_cost = Double.NEGATIVE_INFINITY; SamplePlan original_plan = null; for (SamplePlan plan : plans) { if (plan.getSampleGroups().size() == 1) { double cost = plan.cost(); if (cost > original_cost) { original_cost = cost; original_plan = plan; } } } // find the best plan (the plan whose cost is not too large and its sampling // prob is good) SamplePlan best = null; double bestScore = Double.NEGATIVE_INFINITY; SamplePlan fallback = null; double fallbackCost = Double.POSITIVE_INFINITY; for (SamplePlan plan : plans) { double cost = plan.cost(); if (cost < original_cost * relative_cost_ratio) { double samplingProb = plan.harmonicSamplingProb(); double thisScore = computeScore(cost, samplingProb); if (thisScore > bestScore) { bestScore = thisScore; best = plan; } // VerdictLogger.debug(this, plan.toString() + ", cost: " + cost + ", prob: " + // plan.harmonicSamplingProb()); } if (cost < fallbackCost) { fallbackCost = cost; fallback = plan; } } if (best != null) { return best; } else { return fallback; } } private double computeScore(double cost, double samplingProbability) { return samplingProbability / Math.sqrt(cost); } }
package com.redbus.tests; import java.util.HashMap; import org.apache.log4j.Logger; import org.testng.AssertJUnit; import org.testng.annotations.Test; import com.redbus.pages.TicketDetailsPage; import com.redbus.utils.CommonUtils; import com.redbus.utils.ExtentReport; import com.relevantcodes.extentreports.LogStatus; public class TicketDetailsTest extends ExtentReport { public static final Logger log = Logger.getLogger(TicketDetailsTest.class); public String sheetName = "TicketData"; @Test() public void valid_togetETicket() throws InterruptedException { log.info("Valid Test: When User wants to get the eTicket of booked journey "); extentTest = extent.startTest("Valid scenario: When User wants to get the eTicket of booked journey"); String testName = "Valid Scenario- valid ticket number and email"; TicketDetailsPage ticket = new TicketDetailsPage(driver); HashMap<String, String> testData = new HashMap<String, String>(); testData = reader.getRowTestData(sheetName, testName); log.info(testData); String executionRequired = testData.get("Execution Required").toLowerCase(); String ticket_no = testData.get("Ticket Number"); String email = testData.get("Email Used For Booking"); CommonUtils.toCheckExecutionRequired(executionRequired); ticket.click_managebooking(); log.info("Successfully clicked on Manage Booking Button."); extentTest.log(LogStatus.INFO,"Successfully clicked on Manage Booking Button."); ticket.click_showMyTicket(); log.info("Successfully clicked on Show My Ticket Option."); extentTest.log(LogStatus.INFO,"Successfully clicked on Show My Ticket Option."); // waits and assertions getImplicitlyWait(); String expectedTitle2 = ticket.getText_printticketPage(); AssertJUnit.assertEquals("PRINT TICKET", expectedTitle2); log.info("Assertion Passes, " + " Actual: " + "PRINT TICKET"+ ",Expected: " + expectedTitle2); extentTest.log(LogStatus.INFO,"Assertion Passes, " + " Actual: " + "PRINT TICKET"+ ",Expected: " + expectedTitle2); ticket.enter_ticketNumber(ticket_no); log.info("Ticket Number entered is- " + ticket_no); extentTest.log(LogStatus.INFO,"Ticket Number entered is- " + ticket_no); ticket.enter_eMail(email); log.info("Email used for booking is- " + email); extentTest.log(LogStatus.INFO,"Email used for booking is- " + email); ticket.click_searchTicket(); log.info("Successfully clicked on Search Ticket Button."); extentTest.log(LogStatus.INFO,"Successfully clicked on Search Ticket Button."); // waits and assertions getImplicitlyWait(); String expectedTitle = ticket.getText_eTicketPage(); AssertJUnit.assertEquals("eTICKET", expectedTitle); log.info("Assertion Passes, " + " Actual: " + "eTICKET"+ ",Expected: " + expectedTitle); extentTest.log(LogStatus.INFO,"Assertion Passes, " + " Actual: " + "eTICKET"+ ",Expected: " + expectedTitle); extentTest.log(LogStatus.INFO, "Test Case Passes - When User wants to get the eTicket of booked journey!!"); } @Test() public void invalid_togetETicket() throws InterruptedException { log.info("Invalid Test: To get the E-ticket by entering valid Ticket number and invalid email "); extentTest = extent.startTest("Invalid Test: To get the E-ticket by entering valid Ticket number and invalid email"); String testName = "Invalid Scenario- Valid Ticket Number And invalid email"; TicketDetailsPage ticket = new TicketDetailsPage(driver); HashMap<String, String> testData = new HashMap<String, String>(); testData = reader.getRowTestData(sheetName, testName); log.info(testData); String executionRequired = testData.get("Execution Required").toLowerCase(); String ticket_no = testData.get("Ticket Number"); String email = testData.get("Email Used For Booking"); CommonUtils.toCheckExecutionRequired(executionRequired); ticket.click_managebooking(); log.info("Successfully clicked on Manage Booking Button."); extentTest.log(LogStatus.INFO,"Successfully clicked on Manage Booking Button."); ticket.click_showMyTicket(); log.info("Successfully clicked on Show My Ticket Option."); extentTest.log(LogStatus.INFO,"Successfully clicked on Show My Ticket Option."); // waits and assertions getImplicitlyWait(); String expectedTitle2 = ticket.getText_printticketPage(); AssertJUnit.assertEquals("PRINT TICKET", expectedTitle2); log.info("Assertion Passes, " + " Actual: " + "PRINT TICKET"+ ",Expected: " + expectedTitle2); extentTest.log(LogStatus.INFO,"Assertion Passes, " + " Actual: " + "PRINT TICKET"+ ",Expected: " + expectedTitle2); ticket.enter_ticketNumber(ticket_no); log.info("Ticket Number entered is- " + ticket_no); extentTest.log(LogStatus.INFO,"Ticket Number entered is- " + ticket_no); ticket.enter_eMail(email); log.info("Email used for booking is- " + email); extentTest.log(LogStatus.INFO,"Email used for booking is- " + email); ticket.click_searchTicket(); log.info("Successfully clicked on Search Ticket Button."); extentTest.log(LogStatus.INFO,"Successfully clicked on Search Ticket Button."); // waits and assertions getImplicitlyWait(); String expectedTitle = ticket.getText_error_msg(); AssertJUnit.assertEquals(CommonUtils.prop.getProperty("ERROR_MSG_FOR_TICKET_TEST"), expectedTitle); log.info("Assertion Passes, " + " Actual: " + CommonUtils.prop.getProperty("ERROR_MSG_FOR_TICKET_TEST") + ",Expected: " + expectedTitle); extentTest.log(LogStatus.INFO,"Assertion Passes, " + " Actual: " + CommonUtils.prop.getProperty("ERROR_MSG_FOR_TICKET_TEST") + ",Expected: " + expectedTitle); extentTest.log(LogStatus.INFO, "Test Case Passes - To get the E-ticket by entering valid Ticket number and invalid email"); } @Test() public void invalid_togetETicket1() throws InterruptedException { log.info("Invalid Test: To get the E-ticket by entering valid Ticket number and invalid email "); extentTest = extent.startTest("Invalid Test: To get the E-ticket by entering valid Ticket number and invalid email"); String testName = "Invalid Scenario- invalid Ticket Number And valid email"; TicketDetailsPage ticket = new TicketDetailsPage(driver); HashMap<String, String> testData = new HashMap<String, String>(); testData = reader.getRowTestData(sheetName, testName); log.info(testData); String executionRequired = testData.get("Execution Required").toLowerCase(); String ticket_no = testData.get("Ticket Number"); String email = testData.get("Email Used For Booking"); CommonUtils.toCheckExecutionRequired(executionRequired); ticket.click_managebooking(); log.info("Successfully clicked on Manage Booking Button."); extentTest.log(LogStatus.INFO,"Successfully clicked on Manage Booking Button."); ticket.click_showMyTicket(); log.info("Successfully clicked on Show My Ticket Option."); extentTest.log(LogStatus.INFO,"Successfully clicked on Show My Ticket Option."); // waits and assertions getImplicitlyWait(); String expectedTitle2 = ticket.getText_printticketPage(); AssertJUnit.assertEquals("PRINT TICKET", expectedTitle2); log.info("Assertion Passes, " + " Actual: " + "PRINT TICKET"+ ",Expected: " + expectedTitle2); extentTest.log(LogStatus.INFO,"Assertion Passes, " + " Actual: " + "PRINT TICKET"+ ",Expected: " + expectedTitle2); ticket.enter_ticketNumber(ticket_no); log.info("Ticket Number entered is- " + ticket_no); extentTest.log(LogStatus.INFO,"Ticket Number entered is- " + ticket_no); ticket.enter_eMail(email); log.info("Email used for booking is- " + email); extentTest.log(LogStatus.INFO,"Email used for booking is- " + email); ticket.click_searchTicket(); log.info("Successfully clicked on Search Ticket Button."); extentTest.log(LogStatus.INFO,"Successfully clicked on Search Ticket Button."); // waits and assertions getImplicitlyWait(); String expectedTitle = ticket.getText_error_msg(); AssertJUnit.assertEquals("Something went wrong, please try again later!", expectedTitle); log.info("Assertion Passes, " + " Actual: " + "Something went wrong, please try again later!"+ ",Expected: " + expectedTitle); extentTest.log(LogStatus.INFO,"Assertion Passes, " + " Actual: " + "Something went wrong, please try again later!"+ ",Expected: " + expectedTitle); extentTest.log(LogStatus.INFO, "Test Case Passes - To get the E-ticket by entering valid Ticket number and invalid email"); } @Test() public void invalid_togetETicket2() throws InterruptedException { log.info("Invalid Test: To get the E-ticket by entering invalid Ticket number and invalid email "); extentTest = extent.startTest("Invalid Test: To get the E-ticket by entering invalid Ticket number and invalid email"); String testName = "Invalid Scenario- invalid Ticket Number And invalid email"; TicketDetailsPage ticket = new TicketDetailsPage(driver); HashMap<String, String> testData = new HashMap<String, String>(); testData = reader.getRowTestData(sheetName, testName); log.info(testData); String executionRequired = testData.get("Execution Required").toLowerCase(); String ticket_no = testData.get("Ticket Number"); String email = testData.get("Email Used For Booking"); CommonUtils.toCheckExecutionRequired(executionRequired); ticket.click_managebooking(); log.info("Successfully clicked on Manage Booking Button."); extentTest.log(LogStatus.INFO,"Successfully clicked on Manage Booking Button."); ticket.click_showMyTicket(); log.info("Successfully clicked on Show My Ticket Option."); extentTest.log(LogStatus.INFO,"Successfully clicked on Show My Ticket Option."); // waits and assertions getImplicitlyWait(); String expectedTitle2 = ticket.getText_printticketPage(); AssertJUnit.assertEquals("PRINT TICKET", expectedTitle2); log.info("Assertion Passes, " + " Actual: " + "PRINT TICKET"+ ",Expected: " + expectedTitle2); extentTest.log(LogStatus.INFO,"Assertion Passes, " + " Actual: " + "PRINT TICKET"+ ",Expected: " + expectedTitle2); ticket.enter_ticketNumber(ticket_no); log.info("Ticket Number entered is- " + ticket_no); extentTest.log(LogStatus.INFO,"Ticket Number entered is- " + ticket_no); ticket.enter_eMail(email); log.info("Email used for booking is- " + email); extentTest.log(LogStatus.INFO,"Email used for booking is- " + email); ticket.click_searchTicket(); log.info("Successfully clicked on Search Ticket Button."); extentTest.log(LogStatus.INFO,"Successfully clicked on Search Ticket Button."); // waits and assertions getImplicitlyWait(); String expectedTitle = ticket.getText_error_msg(); AssertJUnit.assertEquals("Something went wrong, please try again later!", expectedTitle); log.info("Assertion Passes, " + " Actual: " + "Something went wrong, please try again later!"+ ",Expected: " + expectedTitle); extentTest.log(LogStatus.INFO,"Assertion Passes, " + " Actual: " + "Something went wrong, please try again later!"+ ",Expected: " + expectedTitle); extentTest.log(LogStatus.INFO, "Test Case Passes - To get the E-ticket by entering invalid Ticket number and invalid email"); } }
import java.util.Arrays; import java.util.Iterator; import org.bson.Document; import com.mongodb.MongoClient; import com.mongodb.MongoCredential; import com.mongodb.ServerAddress; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.MongoIterable; public class MyMain { public static void main(String[] args) { MongoCredential mongoCredential = MongoCredential.createCredential ("admin", "admin","admin123".toCharArray()); ServerAddress serverAddress = new ServerAddress("localhost"); try(MongoClient mongoClient = new MongoClient(serverAddress, Arrays.asList(mongoCredential));){ MongoDatabase db = mongoClient.getDatabase("admin"); System.out.println("List of collections:"); MongoIterable<String> itr = db.listCollectionNames(); Iterator<String> s = itr.iterator(); while(s.hasNext()) { System.out.println(s.next()); } //create collection /*db.createCollection("User"); System.out.println("List of collections after creating User coll:"); MongoIterable<String> itr1 = db.listCollectionNames(); Iterator<String> s1 = itr1.iterator(); while(s1.hasNext()) { System.out.println(s1.next()); }*/ MongoCollection<Document> collection = db.getCollection("User"); /*Document doc = new Document(); doc.put("_id", 1234); doc.put("name", "pqr"); doc.put("description", "data insertion2 in collection"); //insert a doc collection.insertOne(doc);*/ //update a doc /*Document updatedDoc = new Document(); updatedDoc.put("$set", new Document("description", "learning doc update")); collection.updateOne(new Document("name", "pqr"), updatedDoc);*/ //update a doc with array /*Document updateDoc = new Document("$addToSet", new Document().append("friends", "rohan2")); collection.updateOne(new Document("name", "pqr"), updateDoc);*/ //update - remove an element from array /*Document updateDoc = new Document("$pull", new Document("friends", "rohan2")); collection.updateOne(new Document("name", "pqr"), updateDoc);*/ //print all the doc in a collection FindIterable<Document> findItr = collection.find(); Iterator<Document> itr2 = findItr.iterator(); while(itr2.hasNext()) { System.out.println(itr2.next()); } }catch(Exception e) { System.out.println("exp:"+e.getMessage()); } } }
import becker.robots.City; import becker.robots.Direction; import becker.robots.Robot; import becker.robots.Wall; /* * To change this template, choose Tools | Templates * and open the template in the editor. */ /** * * @author kulla6503 */ public class A1Q4 { /** * @param args the command line arguments */ public static void main(String[] args) { //Make a City for the Robot to live in City NYC = new City(); Robot karel = new Robot(NYC, 0, 0, Direction.SOUTH); Robot steve = new Robot(NYC, 0, 1, Direction.SOUTH); new Wall(NYC, 0, 1, Direction.WEST); new Wall(NYC, 1, 1, Direction.WEST); new Wall(NYC, 1, 1, Direction.SOUTH); karel.move(); steve.move(); karel.move(); steve.turnLeft(); steve.move(); steve.turnLeft(); steve.turnLeft(); steve.turnLeft(); steve.move(); karel.turnLeft(); steve.turnLeft(); steve.turnLeft(); steve.turnLeft(); karel.move(); steve.move(); } }
package com.tencent.mm.plugin.game.gamewebview.jsapi.biz; import android.content.Intent; import com.tencent.mm.plugin.game.gamewebview.ui.d; import com.tencent.mm.ui.MMActivity.a; class e$1 implements a { final /* synthetic */ int doP; final /* synthetic */ d jGF; final /* synthetic */ e jGQ; e$1(e eVar, d dVar, int i) { this.jGQ = eVar; this.jGF = dVar; this.doP = i; } public final void b(int i, int i2, Intent intent) { if (i != (this.jGQ.hashCode() & 65535)) { return; } if (i2 == -1) { this.jGF.E(this.doP, com.tencent.mm.plugin.game.gamewebview.jsapi.a.f("batch_view_card:ok", null)); } else { this.jGF.E(this.doP, com.tencent.mm.plugin.game.gamewebview.jsapi.a.f("batch_view_card:fail", null)); } } }
package Erbauer; public interface IGearShift { public int getGearCount(); }
package http; import java.io.Closeable; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Map; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.StatusLine; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.ResponseHandler; import org.apache.http.client.config.RequestConfig; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpUriRequest; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.apache.http.message.BasicNameValuePair; import org.apache.http.util.EntityUtils; import lombok.NonNull; import lombok.extern.slf4j.Slf4j; @Slf4j public class HttpClientUtils { public static final String CHARSET = "UTF-8"; public static CloseableHttpClient getHttpClient() { RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(35000).build(); return HttpClientBuilder.create().setDefaultRequestConfig(config).build(); } public static CloseableHttpClient getHttpClient(int timeOut) { RequestConfig config = RequestConfig.custom().setConnectTimeout(timeOut).setSocketTimeout(timeOut).build(); return HttpClientBuilder.create().setDefaultRequestConfig(config).build(); } /** * HTTP Get * * @param url 请求的url地址 ?之前的地址 * @param params 请求的参数 * @param charset 编码格式 * @return 页面内容 */ public static String doGet(String url, Map<String, String> params) { return doGet(url, params, CHARSET); } public static String doGet(String url, Map<String, String> params, String charset) { return doGet(url, params, charset, null); } public static String doGet(String url, Map<String, String> params, String charset, Collection<Header> headers) { if (StringUtils.isBlank(url)) { return null; } try { if (params != null && !params.isEmpty()) { List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size()); for (Map.Entry<String, String> entry : params.entrySet()) { String value = entry.getValue(); if (value != null) { pairs.add(new BasicNameValuePair(entry.getKey(), value)); } } url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset)); } HttpGet httpGet = new HttpGet(url); if (CollectionUtils.isNotEmpty(headers)) { for (Header header : headers) { httpGet.addHeader(header); } } return execute(null, httpGet, charset, null); } catch (Exception e) { log.error("",e); } return null; } public static String execute(HttpClient httpClient, @NonNull HttpUriRequest request, String charset, Integer timeOut) { boolean closeHttpClient = false; if (httpClient == null) { closeHttpClient = true; if (timeOut != null) { httpClient = getHttpClient(timeOut); } else { httpClient = getHttpClient(); } } if (StringUtils.isBlank(charset)) { charset = CHARSET; } try { long current = System.currentTimeMillis(); // log.debug("send request:{}", request); String result = httpClient.execute(request, new StringResponseHandler(request, charset)); log.info("cost:{} ms to execute http method:{},url:{}", System.currentTimeMillis() - current, request.getMethod(), request.getURI()); return result; } catch (IOException e) { throw new RuntimeException("do request exception - ", e); } finally { if (closeHttpClient) { if (httpClient != null) { if (httpClient instanceof Closeable) { try { ((Closeable) httpClient).close(); } catch (final IOException ignore) { } } } } } } static class StringResponseHandler implements ResponseHandler<String> { private HttpUriRequest request; private String charset; public StringResponseHandler(HttpUriRequest request, String charset) { this.request = request; this.charset = charset; } @Override public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException { try { StatusLine status = response.getStatusLine(); log.debug("doPost - execute end, url:{}, status:{}", request.getURI(), status); if (status.getStatusCode() != HttpStatus.SC_OK) { request.abort(); throw new RuntimeException("HttpClient,error status code :" + status); } HttpEntity responseEntity = response.getEntity(); String result = null; if (responseEntity != null) { result = EntityUtils.toString(responseEntity, charset); } log.debug("http response - url:{}, status:{}, response:{}", request.getURI(), status, result); return result; } finally { if (response != null) { final HttpEntity entity = response.getEntity(); if (entity != null) { try { EntityUtils.consume(entity); } catch (final IOException ex) { } } } } } } }
import java.util.*; public class Dictionary<v> { Integer M; //Number of buckets ArrayList<ArrayList<Pair<v>>> data; public Dictionary (int M) { this.M = new Integer(M); // Create array of empty lists this.data = new ArrayList<ArrayList<Pair<v>>>(M); for (int m = 0; m < M; m++) { ArrayList<Pair<v>> array = new ArrayList<Pair<v>>(); this.data.add(array); } } public v search(Integer key) { Integer index = hash(key); Integer size = data.get(index).size(); for (int i = 0; i < size; i++) { if (data.get(index).get(i).key == key) { return data.get(index).get(i).val; } } return null; } public void insert(Pair<v> pair_in) { Integer key = pair_in.key; v value = pair_in.val; Integer index = hash(key); Integer size = data.get(index).size(); for (int i = 0; i < size; i++) { if (data.get(index).get(i).key == key) { data.get(index).get(i).val = value; return; } } data.get(index).add(pair_in); } private Integer yomama(Integer int_in) { return int_in; } private Integer hash(Integer int_in) { return int_in.hashCode() % M; } public void Print_table() { for (int m = 0; m < M; m++) { System.out.println("Entries for index " + m + ";"); for (int i = 0; i < data.get(m).size(); i++) { System.out.println("i = " + i + ": " + data.get(m).get(i).key + ", " + data.get(m).get(i).val); } } } }
package com.rc.portal.commons; public class ConstantUtil { public static final String PWDKEY="wozhongla.com"; //加密key public static final int POUNDAGE=2; //提现手续费 public static final int BANKDRAW=301; //银行提现方式 public static final int ZFBDRAW=302; //支付宝提现方式 public static final int SYSACCOUNT=88; //系统发送广播账号 }
package com.btsandjjiao.service.impl; import com.btsandjjiao.dao.EmployeeMapper; import com.btsandjjiao.domain.Employee; import com.btsandjjiao.domain.EmployeeExample; import com.btsandjjiao.service.EmployeeService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class EmployeeImpl implements EmployeeService { @Autowired EmployeeMapper employeeMapper; /*查询所有员工*/ @Override public List<Employee> getAll() { return employeeMapper.selectByExampleWithDept(null); } /*保存员工信息*/ @Override public void saveEmp(Employee employee) { employeeMapper.insertSelective(employee); } /*校验员工名字是否可用*/ @Override public boolean checkUser(String empName) { EmployeeExample example = new EmployeeExample(); EmployeeExample.Criteria criteria = example.createCriteria(); criteria.andEmpNameEqualTo(empName); long count = employeeMapper.countByExample(example); return count == 0; } /*按照员工id查找员工*/ @Override public Employee getEmp(Integer id) { Employee employee = employeeMapper.selectByPrimaryKey(id); return employee; } /*按照员工进行更新员工信息*/ @Override public void updateEmp(Employee employee) { employeeMapper.updateByPrimaryKeySelective(employee); } /*批量删除*/ @Override public void deleteBatch(List<Integer> del_ids) { //按照条件删除 EmployeeExample example = new EmployeeExample(); EmployeeExample.Criteria criteria = example.createCriteria(); //delete from xxx where emp_id in (del_ids) criteria.andEmpIdIn(del_ids); employeeMapper.deleteByExample(example); } /*单个删除*/ @Override public void deleteEmp(Integer id) { employeeMapper.deleteByPrimaryKey(id); } }
package com.udacity.ranjitha.tourguide; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ListView; import android.widget.TextView; import java.util.ArrayList; /** * A simple {@link Fragment} subclass. */ public class MythologyFragment extends Fragment { public MythologyFragment() { // Required empty public constructor } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.word_list, container, false); //Arraylist for intializing data ArrayList<Word> word = new ArrayList<Word>(); word.add(new Word(R.string.mythology_malyavanta, R.drawable.maly)); word.add(new Word(R.string.mythology_kurugodu, R.drawable.kuru)); word.add(new Word(R.string.mythology_kanaviraya, R.drawable.kan)); word.add(new Word(R.string.mythology_jambunatha, R.drawable.jamb)); WordAdapter wordAdapter = new WordAdapter(getActivity(), word); ListView listView = (ListView) rootView.findViewById(R.id.list); listView.setAdapter(wordAdapter); return rootView; } }
//This file will determine crime sentence of drug crime. Drug crime has two types of offences: dictable and summary. //The offence will be determined based on whether the criminal do the trafficking or possession, the amount of drugs they have, //and the types of drugs(the more serious drugs will result as high jail sentence) package legaladvisor; public class DrugCrime extends CriminalCase{ private boolean trafficking; private boolean possession; private double quantity; private String typeOfDrug; private String typeOfOffense; private String crimeType; private String scheType; public DrugCrime(String rem, String jur, String crim, String sen, boolean pos, boolean traf, String tOD) { super(rem, jur, crim, sen); this.trafficking=traf; this.possession=pos; } //this method decide the crime sentence differently if the criminal does the drug trafficking or drug possession. //The crime sentence will be more serious for schedule I and in trafficking category //The crime sentence depends on whether the drug is in schedule I, II, or II, trafficking or drug possession, //and the quantity that they trafficking or possess public void setCrimeTypeAndSentence(String keyword){ String sentence; if(super.SearchMechanism(keyword, super.getDrugType(), 0) && this.getTrafficking()){ this.typeOfOffense = "Possession with the intent of trafficking which is indictable"; if(keyword.equalsIgnoreCase(super.getDrugType()[2]) || keyword.equals(super.getDrugType()[5]) || keyword.equalsIgnoreCase(super.getDrugType()[8])){ //cocaine,heroine,methamphetamine this.setScheduleType(keyword);//set which of these drugs in what schedule level (Level I is the most serious) if(this.quantity > 30){ //if the amount is greater than 30grams sentence = "The max jail sentence is life imprisonment."; }else if(this.quantity >3 ){ //if the amount is greater than 3 grams sentence = "The max jail sentence is between 6 to 8 years"; }else{ //if the amount is less than 3 grams sentence = "The max jail sentence is between 6 months to 2 years"; } }else if(keyword.equalsIgnoreCase(super.getDrugType()[6])){ //and LSD this.setScheduleType(keyword); sentence = "The maximum jail sentence is 10 years"; }else if(keyword.equalsIgnoreCase(super.getDrugType()[4]) || keyword.equalsIgnoreCase(super.getDrugType()[7])){ //hashish and marijuana this.setScheduleType(keyword); if(this.quantity > 30){ sentence = "The maximum jail sentence is life imprionment"; }else if(this.quantity < 3){ sentence = "The maximum jail sentence is 5 years"; } }else if(keyword.equalsIgnoreCase(super.getDrugType()[3])){ //if keyword equals to "hallucionogens" sentence = "The maximum jail sentence is 18 months."; } }else{ //else if this is not drug trafficking but drug possession if(this.quantity > 30){ this.typeOfOffense = "Possession and indictable"; if(this.scheType.equalsIgnoreCase("schedule I")){ sentence = "The max jail sentence is 7 years"; }else if(this.scheType.equalsIgnoreCase("schedule II")){ sentence = "The max jail sentence is five years less a day"; }else{ sentence = "The max jail sentence is 3 years"; } }else{//else if the equantity is less than 30grams this.typeOfOffense="Possession and summary"; if(keyword.equalsIgnoreCase(super.getDrugType()[1]) || keyword.equals(super.getDrugType()[4]) || keyword.equalsIgnoreCase(super.getDrugType()[0])|| keyword.equalsIgnoreCase(super.getDrugType()[2]) || keyword.equalsIgnoreCase(super.getDrugType()[5]) || (keyword.equalsIgnoreCase(super.getDrugType()[6])) ){ sentence = "For the first offense, the maximum fine is $1,000 and jail sentence is up to 6 months." + "For the second offense, the maximum fine is $2,000 and jail sentence is up to one year."; } } } } public boolean getPossession(){ return this.possession; } public boolean getTrafficking(){ return trafficking; } public void setDrugType(String keyword){ for(int i=0;i<super.getDrugType().length;i++){ if(keyword.equalsIgnoreCase(super.getDrugType()[i])){ this.typeOfDrug=super.getDrugType()[i]; } } } public void setTrafficking(String keyword){ //set whether the drug is trafficking or not if(super.SearchMechanism(keyword, super.getTraffickingTerm(), 0)){ //if keyword equals to one of Trafficking terms this.trafficking = true; //drug trafficking is true }else{ this.trafficking = false;//else false } } //This method will decide which drugs are in schedule I, II, or III. It will read if the keyword the users enter match one of the drugs public void setScheduleType(String keyword){ //if keyword equals to one of these drugs (cocaine, heroine, methamphetamine) if(keyword.equalsIgnoreCase(super.getDrugType()[2]) || keyword.equals(super.getDrugType()[5]) || keyword.equalsIgnoreCase(super.getDrugType()[8])){ this.scheType = "Schedule I"; }//if keyword equals to "hashish" and "marijuana" else if(keyword.equalsIgnoreCase(super.getDrugType()[4]) || keyword.equalsIgnoreCase(super.getDrugType()[7])){ this.scheType = "Schedule II"; }else if(keyword.equalsIgnoreCase(super.getDrugType()[0])){//if keyword equals to "amphetamine" this.scheType = "schedule III"; } } public String getScheType(){ return scheType; } public double getQuantity(double qty){ //get the amount of drug in grams that the criminal has return quantity; } public String getTypeOfDrug(){ return typeOfDrug; } public String getTypeOfOffense(){ return this.typeOfOffense; } public void setTypeOfOffense(String of){ this.typeOfOffense= of; } public void setQuantity(double q){ this.quantity=q; } public String getCrimeType(){ return crimeType; } @Override public String printInfo() { return "Type of Offence: " + this.getTypeOfOffense()+ "\nType of Drug: " + this.getTypeOfDrug()+"\nDrug Schedule:"+this.scheType +"\nCrime Type: "+ this.crimeType+super.printInfo(); } }
package edu.byu.cs.tweeter.presenter; import android.graphics.Bitmap; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mockito; import java.io.IOException; import edu.byu.cs.tweeter.model.domain.AuthToken; import edu.byu.cs.tweeter.model.domain.User; import edu.byu.cs.tweeter.model.service.RegisterService; import edu.byu.cs.tweeter.model.service.request.RegisterRequest; import edu.byu.cs.tweeter.model.service.response.RegisterResponse; import edu.byu.cs.tweeter.util.ByteArrayUtils; public class RegisterPresenterTest { private RegisterRequest request; private RegisterResponse response; private RegisterService mockRegisterService; private RegisterPresenter presenter; @BeforeEach public void setup() throws IOException { User currentUser = new User("FirstName", "LastName", null); User resultUser1 = new User("FirstName1", "LastName1", "https://faculty.cs.byu.edu/~jwilkerson/cs340/tweeter/images/donald_duck.png"); User resultUser2 = new User("FirstName2", "LastName2", "https://faculty.cs.byu.edu/~jwilkerson/cs340/tweeter/images/daisy_duck.png"); User resultUser3 = new User("FirstName3", "LastName3", "https://faculty.cs.byu.edu/~jwilkerson/cs340/tweeter/images/daisy_duck.png"); User testUser = new User("Test", "User", "https://faculty.cs.byu.edu/~jwilkerson/cs340/tweeter/images/donald_duck.png"); //Create a byte array from the given URL //Bitmap bm1 = Bitmap.createBitmap(100, 200, Bitmap.Config.ARGB_8888); request = new RegisterRequest(testUser.getName(), "Password", testUser.getFirstName(), testUser.getLastName(), null); response = new RegisterResponse(testUser, new AuthToken()); // Create a mock RegisterService mockRegisterService = Mockito.mock(RegisterService.class); Mockito.when(mockRegisterService.register(request)).thenReturn(response); // Wrap a RegisterPresenter in a spy that will use the mock service. presenter = Mockito.spy(new RegisterPresenter(new RegisterPresenter.View() {})); Mockito.when(presenter.getRegisterService()).thenReturn(mockRegisterService); } @Test public void testGetRegister_returnsServiceResult() throws IOException { Mockito.when(mockRegisterService.register(request)).thenReturn(response); // Assert that the presenter returns the same response as the service (it doesn't do // anything else, so there's nothing else to test). RegisterResponse tempR = response; RegisterResponse temp = presenter.register(request); //Here, we need to compare users, as the way that the facade works is that it creates a random new auth token //on each login. So it is impossible for it to match on both requests (it will be different each time). Assertions.assertEquals(response, presenter.register(request)); } @Test public void testGetRegister_serviceThrowsIOException_presenterThrowsIOException() throws IOException { Mockito.when(mockRegisterService.register(request)).thenThrow(new IOException()); Assertions.assertThrows(IOException.class, () -> { presenter.register(request); }); } }
package exam.zipcode.service; import java.util.*; import exam.zipcode.vo.*; /** * @author PC-01 * Service객체는 Dao에 설정된 메서드를 원하는 작업에 맞게 호출하여 결과를 받아오고, * 받아온 자료를 Controller에게 보내주는 역할을 수행한다. 보통 Dao의 메서드와 같은 구조를 갖는다. * */ public interface ZipCodeService { List<ZipCodeVO> getSearchZip(String comGet, String txtGet); }
package org.workers.impl.survival_expert; import org.OrionTutorial; import org.osbot.rs07.input.mouse.RectangleDestination; import org.workers.TutorialWorker; public class OpenInventory extends TutorialWorker { public OpenInventory(OrionTutorial mission) { super(mission); } @Override public boolean shouldExecute() { return true; } @Override public void work() { script.log(this, false, "Opening inventory"); mouse.click(new RectangleDestination(bot, 627, 167, 30, 36)); } }
/* * Copyright (c) 2018, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory * CODE-743439. * All rights reserved. * This file is part of CCT. For details, see https://github.com/LLNL/coda-calibration-tool. * * Licensed under the Apache License, Version 2.0 (the “Licensee”); you may not use this file except in compliance with the License. You may obtain a copy of the License at: * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations under the license. * * This work was performed under the auspices of the U.S. Department of Energy * by Lawrence Livermore National Laboratory under Contract DE-AC52-07NA27344. */ package gov.llnl.gnem.apps.coda.common.model.domain; public class Pair<L, R> { private L left; private R right; public Pair(L left, R right) { super(); this.left = left; this.right = right; } public L getLeft() { return left; } public R getRight() { return right; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((left == null) ? 0 : left.hashCode()); result = prime * result + ((right == null) ? 0 : right.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Pair<L, R> other = (Pair<L, R>) obj; if (left == null) { if (other.left != null) { return false; } } else if (!left.equals(other.left)) { return false; } if (right == null) { if (other.right != null) { return false; } } else if (!right.equals(other.right)) { return false; } return true; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("\"").append(left).append("\", \"").append(right).append('\"'); return builder.toString(); } public static <L, R> Pair<L, R> create(L l, R r) { return new Pair<L, R>(l, r); } }
package com.tstu; public enum Status { GIVE_UP("Игрок сдался"), MISTAKE("Введены неверные данные"), WIN("Вы отгадали последовательность!"), CONTINUE("Продолжить"); private String value; public String getValue() { return value; } Status(String value) { this.value = value; } }
package io.github.boapps.eSzivacs.Activities; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.LayoutInflater; import android.view.View; import android.widget.CheckBox; import android.widget.ListView; import android.widget.RadioGroup; import android.widget.TextView; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.Date; import io.github.boapps.eSzivacs.Adapters.EditLVAdapter; import io.github.boapps.eSzivacs.Datas.Evaluation; import io.github.boapps.eSzivacs.R; import io.github.boapps.eSzivacs.Utils.Themer; import static io.github.boapps.eSzivacs.Activities.MainPage.evaluations; public class HaKapnekEgy extends AppCompatActivity { ArrayList<Evaluation> subEvals = new ArrayList<>(); String lesson; ListView lessonEvalsLV; RadioGroup radioGroup; CheckBox checkTZ; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Themer.selectCurrentTheme(this); setContentView(R.layout.activity_ha_kapnek_egy); Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); Intent intent = getIntent(); System.out.println("TANTARGY:"); System.out.println(intent.getStringExtra("lesson")); if (savedInstanceState == null) { Bundle extras = getIntent().getExtras(); if (extras == null) { lesson = null; } else { lesson = extras.getString("lesson"); } } else { lesson = (String) savedInstanceState.getSerializable("lesson"); } System.out.println("\'" + lesson + "\'"); System.out.println(evaluations.size()); for (int n = 0; n < evaluations.size(); n++) { System.out.println(evaluations.get(n).getSubject()); System.out.println(evaluations.get(n).getSubjectCategory()); if (evaluations.get(n).getSubject().equals(lesson)) subEvals.add(evaluations.get(n)); } Collections.sort(subEvals, new Comparator<Evaluation>() { @Override public int compare(Evaluation o1, Evaluation o2) { return o2.getDate().compareTo(o1.getDate()); } }); lessonEvalsLV = findViewById(R.id.editlv); System.out.println(subEvals.size()); EditLVAdapter mainLVAdapter = new EditLVAdapter(subEvals, this); lessonEvalsLV.setAdapter(mainLVAdapter); lessonEvalsLV.deferNotifyDataSetChanged(); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { showSelectEvalDialog(); } }); updateAvarage(); } public void showSelectEvalDialog() { LayoutInflater li = LayoutInflater.from(this); View evsDialog = li.inflate(R.layout.select_hakap_dialog, null); AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( this); alertDialogBuilder.setView(evsDialog); alertDialogBuilder.setTitle("Új jegy"); alertDialogBuilder.setPositiveButton("Create", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { int evalValue = 0; switch (radioGroup.getCheckedRadioButtonId()) { case R.id.radioButton: evalValue = 1; break; case R.id.radioButton2: evalValue = 2; break; case R.id.radioButton3: evalValue = 3; break; case R.id.radioButton4: evalValue = 4; break; case R.id.radioButton5: evalValue = 5; break; } System.out.println("jegy: " + evalValue); System.out.println("TZ: " + checkTZ.isChecked()); SimpleDateFormat format = new SimpleDateFormat("yyyy. MM. dd. "); subEvals.add(0, new Evaluation(0, "form", "1-5", "Évközi :P", lesson, lesson, "mode", checkTZ.isChecked() ? "100%" : "200%", String.valueOf(evalValue), String.valueOf(evalValue), "Teacher", format.format(new Date()), format.format(new Date()), "Theme")); EditLVAdapter mainLVAdapter = new EditLVAdapter(subEvals, getApplicationContext()); lessonEvalsLV.setAdapter(mainLVAdapter); lessonEvalsLV.deferNotifyDataSetChanged(); updateAvarage(); } }); Dialog dialog = alertDialogBuilder.create(); dialog.show(); radioGroup = dialog.findViewById(R.id.radioGroup); checkTZ = dialog.findViewById(R.id.checkTZ); } public void updateAvarage() { int sum = 0; int count = 0; for (Evaluation evaluation : subEvals) { System.out.println(evaluation.getWeight()); sum += (Integer.valueOf(evaluation.getNumericValue()) * Integer.valueOf(evaluation.getWeight().substring(0, evaluation.getWeight().indexOf("%"))) / 100); count += (Integer.valueOf(evaluation.getWeight().substring(0, evaluation.getWeight().indexOf("%"))) / 100); } TextView avarageHakapTV = findViewById(R.id.avarage_hakap_tv); avarageHakapTV.setText("Átlag: " + String.format("%.2f", (float) sum / count)); } }
package com.testyantra.stockmanagement.controllers; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.CrossOrigin; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.testyantra.stockmanagement.dto.ResponseDTO; import com.testyantra.stockmanagement.entities.Company; import com.testyantra.stockmanagement.entities.Stock; import com.testyantra.stockmanagement.entities.User; import com.testyantra.stockmanagement.service.CompanyService; @RestController @RequestMapping("/companies") @CrossOrigin(origins = "*") public class CompanyController { @Autowired private CompanyService service; @PostMapping public ResponseDTO addCompany(@RequestBody Company company) { ResponseDTO response = new ResponseDTO(); response.setData(service.addCompany(company)); return response; } @DeleteMapping(path = "/{companyId}", produces = { MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE }) public ResponseDTO removeCompany(@PathVariable int companyId) { ResponseDTO response = new ResponseDTO(); response.setData(service.removeCompany(companyId)); return response; } @PutMapping public ResponseDTO updateCompany(@RequestBody Company company) { ResponseDTO response = new ResponseDTO(); response.setData(service.updateCompany(company)); return response; } @PostMapping("/company") public ResponseDTO getCompany(@RequestBody User user) { ResponseDTO response = new ResponseDTO(); response.setData(service.getCompanyDetail(user)); return response; } @GetMapping("/company") public ResponseDTO getCompany(String companyName) { ResponseDTO response = new ResponseDTO(); response.setData(service.getCompany(companyName)); return response; } @GetMapping public ResponseDTO getAllCompanies() { ResponseDTO response = new ResponseDTO(); response.setData(service.getAllCompanyDetails()); return response; } @PostMapping("/stock") public ResponseDTO addStock(@RequestBody Stock stock) { ResponseDTO response = new ResponseDTO(); response.setData(service.addStock(stock)); return response; } @PutMapping("/stock") public ResponseDTO updateStock(@RequestBody Stock stock) { ResponseDTO response = new ResponseDTO(); response.setData(service.updateStock(stock)); return response; } @PostMapping("/stocks") public ResponseDTO getStock(@RequestBody Company company) { ResponseDTO response = new ResponseDTO(); response.setData(service.getStock(company)); return response; } }
/** * Created by jason chou on 2016/11/7. */import java.util.Scanner; public class Test_3 { public static void main(String[] args){ int number; Scanner scanner = new Scanner(System.in); System.out.println("Input a number: "); number = scanner.nextInt(); for(int i=10;i>-1;i--){ System.out.println(number + "x" + i + "=" + (number*i)); } } }
package com.example.iutassistant.Model; public class CourseModel { private String credits; private String name; private String courseCode; public CourseModel() { } public void setCourseCode(String courseCode) { this.courseCode = courseCode; } public String getCredits() { return credits; } public String getName() { return name; } public String getCourseCode() { return courseCode; } public CourseModel(String credits, String name) { this.credits = credits; this.name = name; } }
package com.java8features.fefault; public interface B { public default void m1() { System.out.println("A -- m2 "); } }
/* * Copyright 2009 Kjetil Valstadsve * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package vanadis.blueprints; import junit.framework.Assert; import static junit.framework.Assert.*; import org.junit.Test; import vanadis.core.lang.Not; import vanadis.common.ver.Version; import vanadis.mvn.Coordinate; import vanadis.mvn.Repo; import java.io.ByteArrayInputStream; import java.net.URI; import java.net.URISyntaxException; public class BlueprintsReaderTest { private static final String XML_NS = "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://kjetilv.github.com/vanadis/blueprints\""; @Test public void loadConfiguration() throws URISyntaxException { Blueprints vc = loadV1(("<blueprints xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + " xmlns=\"http://kjetilv.github.com/vanadis/blueprints\">" + " <blueprint name=\"base\">" + " </blueprint>" + " <blueprint name=\"vanadis-basic\" extends=\"base\">" + " <module type=\"remoting\"/>" + " </blueprint>" + " <blueprint name=\"vanadis-routed\" extends=\"vanadis-basic\">" + " <module type=\"networker\"/>" + " </blueprint>" + "</blueprints>")); assertNotNull(vc); assertNotNull(vc.getBlueprint("base")); Blueprint template = vc.getBlueprint("vanadis-routed"); assertNotNull(template); assertTrue(template.getParents().contains(vc.getBlueprint("vanadis-basic"))); assertEquals("Unexpected # of parents: " + template.getParents(), 1, template.getParents().size()); } private static Blueprints loadV1(String input) { return BlueprintsReader.readBlueprints(URI.create("file://test"), new ByteArrayInputStream(input.getBytes())); } @Test public void captureMalformedInputNoParent() { try { Assert.fail("Illegal: " + new Blueprints (null, new Blueprint(null, "leaf1", "parent1", true, null, null, null)).validate()); } catch (IllegalArgumentException ignore) { } } @Test public void captureMalformedInputAbstractLeaf() { try { Assert.fail("Illegal: " + new Blueprints (null, new Blueprint(null, "leaf1", "parent1", true, null, null, null), new Blueprint(null, "parent1", (String)null, true, null, null, null)).validate()); } catch (IllegalArgumentException ignore) { } } @Test public void captureCycleNodes() { try { Assert.fail("Illegal: " + new Blueprints (null, new Blueprint(null, "leaf1", "parent1", false, null, null, null), new Blueprint(null, "parent1", "leaf1", false, null, null, null)).validate()); } catch (IllegalArgumentException ignore) { } } @Test public void testBundleProperties() { Blueprints blueprints = loadV1("<blueprints " + XML_NS + ">" + "<blueprint name=\"foo\">" + " <bundles group-prefix=\"aaa\" artifact-prefix=\"foo\">" + " <bundles artifact-prefix=\"bar\">" + " <bundle artifact=\"zot\">" + " <properties>" + " <property name=\"zip\">" + " zot" + " </property>" + " </properties>" + " </bundle>" + " </bundles>" + " </bundles>" + "</blueprint></blueprints>"); BundleSpecification spec = blueprints.getBlueprint("foo").getDynaBundles().iterator().next(); Assert.assertNotNull(spec.getPropertySet()); Assert.assertTrue(spec.getPropertySet().has("zip")); Assert.assertEquals("zot", spec.getPropertySet().getString("zip")); } @Test public void testBundleNesting() { Blueprints blueprints = loadV1("<blueprints " + XML_NS + ">" + "<blueprint name=\"foo\">" + " <bundles group-prefix=\"aaa\" artifact-prefix=\"foo\">" + " <bundles artifact-prefix=\"bar\">" + " <bundle artifact=\"zot\"/>" + " </bundles>" + " </bundles>" + "</blueprint></blueprints>"); Assert.assertTrue(blueprints.getBlueprint("foo").contains(bs (Coordinate.unversioned("aaa", "foo.bar.zot")))); } @Test public void testNodeData() { Blueprints blueprints = loadV1 ("<blueprints " + XML_NS + ">" + " <blueprint name=\"vanadis-routed\">" + " <module type=\"remoting\"/>" + " </blueprint>" + " <blueprint name=\"base-shell\">" + " <module type=\"networker\"/>" + " </blueprint>" + "</blueprints>"); SystemSpecification systemSpecification = blueprints.getSystemSpecification(Repo.DEFAULT.toURI(), "vanadis-routed", "base-shell"); assertTrue(systemSpecification.containsModuleSpecification("remoting")); assertTrue(systemSpecification.containsModuleSpecification("networker")); } @Test public void testBlueprintsVersionAndRepo() { Blueprints blueprints = loadV1 ("<blueprints " + XML_NS + " default-version=\"1.2.3\" repo=\"file:///foo/bar\">" + " <blueprint name=\"vanadis-routed\">" + " <bundle group=\"vanadis\" artifact=\"vanadis.foo\"/>" + " </blueprint>" + " <blueprint name=\"base-shell\">" + " <bundle group=\"vanadis\" artifact=\"vanadis.bar\"/>" + " </blueprint>" + "</blueprints>"); assertNodeAndBundle(blueprints, "vanadis-routed", "1.2.3", "file:///foo/bar"); assertNodeAndBundle(blueprints, "base-shell", "1.2.3", "file:///foo/bar"); } @Test public void testBlueprintsAndBlueprintVersionAndRepo() { Blueprints blueprints = loadV1 ("<blueprints " + XML_NS + " default-version=\"1.2.3\">" + " <blueprint name=\"vanadis-routed\">" + " <bundle group=\"vanadis\" artifact=\"vanadis.foo\" repo=\"file:///foo/bar\"/>" + " </blueprint>" + " <blueprint name=\"base-shell\" default-version=\"2.4.6\" repo=\"file:///foo/zot\">" + " <bundle group=\"vanadis\" artifact=\"vanadis.bar\"/>" + " </blueprint>" + "</blueprints>"); assertNodeAndBundle(blueprints, "vanadis-routed", "1.2.3", "file:///foo/bar"); assertNodeAndBundle(blueprints, "base-shell", "2.4.6", "file:///foo/zot"); } @Test public void testBlueprintVersionAndRepo() { Blueprints blueprints = loadV1 ("<blueprints " + XML_NS + ">" + " <blueprint name=\"vanadis-routed\" default-version=\"1.2.3\" repo=\"file:///foo/bar\">" + " <bundle group=\"vanadis\" artifact=\"vanadis.foo\"/>" + " </blueprint>" + " <blueprint name=\"base-shell\" default-version=\"2.4.6\" repo=\"file:///foo/zot\">" + " <bundle group=\"vanadis\" artifact=\"vanadis.bar\"/>" + " </blueprint>" + "</blueprints>"); assertNodeAndBundle(blueprints, "vanadis-routed", "1.2.3", "file:///foo/bar"); assertNodeAndBundle(blueprints, "base-shell", "2.4.6", "file:///foo/zot"); } private static void assertNodeAndBundle(Blueprints blueprints, String bpName, String ver, String repo) { BundleSpecification bs = blueprints.getBlueprint(bpName).getDynaBundles().iterator().next(); assertEquals(new Version(ver), bs.getCoordinate().getVersion()); assertEquals(URI.create(repo), bs.getRepo()); } public static BundleSpecification bs(Coordinate coordinate) { return BundleSpecification.create(null, Not.nil(coordinate, "coordinate"), null, null, null, null); } }
package com.example.tris_meneghetti; import android.view.View; public class PlayerVsPlayer implements IplayerVS { private Controllo cont = new Controllo(); public int onButtonClick(View view, Design[][] grigliaPulsanti, boolean turnoX, String[][] griglia, int pareggio) { for (int i = 0; i < 3; i++) { for (int k = 0; k < 3; k++) { if (grigliaPulsanti[i][k] == view) { if (turnoX) { griglia[i][k] = "X"; ((Design) view).drawX(); } else { griglia[i][k] = "O"; ((Design) view).drawO(); } pareggio++; grigliaPulsanti[i][k].setClickable(false); } } } return cont.controllo(griglia); } }