text
stringlengths
10
2.72M
package com.example.agnciadeturismo.presenter.view.ui; import androidx.appcompat.app.AppCompatActivity; import androidx.appcompat.widget.Toolbar; import androidx.lifecycle.Observer; import androidx.lifecycle.ViewModelProvider; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.content.Intent; import android.os.Bundle; import com.example.agnciadeturismo.R; import com.example.agnciadeturismo.data.repository.PacoteRepositoryTask; import com.example.agnciadeturismo.model.PacoteDto; import com.example.agnciadeturismo.presenter.view.adapter.PacoteAdapter; import com.example.agnciadeturismo.presenter.view.adapter.OnClickItemPacote; import com.example.agnciadeturismo.presenter.viewmodel.PacoteViewModel; import java.util.ArrayList; public class BuscarActivity extends AppCompatActivity implements OnClickItemPacote { Toolbar toolbar; RecyclerView recyclerViewPacote; PacoteViewModel pacoteViewModel; ArrayList<PacoteDto> listPacote = new ArrayList<>(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_buscar); initView(); initObserver(); } private void initObserver() { pacoteViewModel.getPacote().observe(this, new Observer<ArrayList<PacoteDto>>() { @Override public void onChanged(ArrayList<PacoteDto> response) { listPacote = response; atualizaAdapter(listPacote); } }); } private void initView() { pacoteViewModel = new ViewModelProvider(this, new PacoteViewModel.ViewModelFactory(new PacoteRepositoryTask())).get(PacoteViewModel.class); toolbar = findViewById(R.id.toolbar_buscar); recyclerViewPacote = findViewById(R.id.recycler_pacote); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); Bundle bundle = getIntent().getExtras(); if(bundle != null){ getSupportActionBar().setTitle("Pacotes para "+bundle.getString("destino")); pacoteViewModel.getAllPacotes( bundle.getInt("cdOrigem"), bundle.getInt("cdDestino"), bundle.getInt("tipo") ); } } private void atualizaAdapter(ArrayList<PacoteDto> listPacote) { PacoteAdapter adapter = new PacoteAdapter(this, listPacote); recyclerViewPacote.setLayoutManager(new LinearLayoutManager(this)); recyclerViewPacote.setAdapter(adapter); } @Override public boolean onSupportNavigateUp() { finish(); return super.onSupportNavigateUp(); } @Override public void onClick(int posicao) { PacoteDto pacote = listPacote.get(posicao); Intent intent = new Intent(this, DetalhesActivity.class); intent.putExtra("codigo", pacote.getCd()); intent.putExtra("viagem", pacote.getCdViagem()); intent.putExtra("hotel", pacote.getCdHotel()); intent.putExtra("categoria", pacote.getCdCategoria()); intent.putExtra("tipoTransporte", pacote.getCdTipoTranporte()); intent.putExtra("origem", pacote.getCdOrigem()); intent.putExtra("destino", pacote.getCdDestino()); intent.putExtra("nomePacote", pacote.getNomePacote()); intent.putExtra("descricao", pacote.getDescricaoPacote()); intent.putExtra("checkin", pacote.getDtCheckin()); intent.putExtra("checkout", pacote.getDtCheckout()); intent.putExtra("img", pacote.getImg()); intent.putExtra("valor", pacote.getVlPacote()); startActivity(intent); } }
import java.lang.*; import java.util.*; import java.io.*; enum SelfActionType { START, FIGHT, RUN, CHANGE, CHANGE_ARMOR, CHANGE_WEAPON, CONTAINER, CONTAINER_WEAPON, CONTAINER_ARMOR, CONTAINER_HEAL, CONTAINER_DAMAGE, CONTAINER_STORED, HERO_INFO } class HeroController { private Hero hero; private Scanner sc = new Scanner(System.in); private SelfActionType state = SelfActionType.START; private ArrayList<Enemy> enemies; public HeroController() { hero = new Hero(); } public boolean isAlive() { return hero.getHealth() > 0; } public Action makeMove() { return selectAction(); } public void applyMove(Action action) { System.out.println("Вам нанесли " + action.getValue() + " очков урона."); hero.changeHealth(-action.getValue()); } public void setEnemiesList(ArrayList<Enemy> enemies) { this.enemies = enemies; } // BEGIN PRIVATE private Action selectAction() { int choise = 0; switch(state) { case START: printGlobalActionList(); choise = getChoose(); switch(choise){ case 1: state = SelfActionType.FIGHT; break; case 2: state = SelfActionType.CHANGE; break; case 3: state = SelfActionType.HERO_INFO; break; case 4: state = SelfActionType.RUN; break; } return new Action(ActionType.SELF); case HERO_INFO: printHeroInfo(); state = SelfActionType.START; return new Action(ActionType.SELF); case CHANGE: printSelfActionList(); choise = getChoose(); switch(choise) { case 1: state = SelfActionType.CHANGE_ARMOR; break; case 2: state = SelfActionType.CHANGE_WEAPON; break; case 3: state = SelfActionType.CONTAINER; break; case 4: state = SelfActionType.START; break; } return new Action(ActionType.SELF); case CHANGE_ARMOR: getArmorList(); choise = getChoose(); hero.changeArmor(choise-1); state = SelfActionType.CHANGE; return new Action(ActionType.SELF); case CHANGE_WEAPON: getWeaponList(); choise = getChoose(); hero.changeWeapon(choise-1); state = SelfActionType.CHANGE; return new Action(ActionType.SELF); case CONTAINER: printBagUnitsList(); choise = getChoose(); switch(choise) { case 1: state = SelfActionType.CONTAINER_WEAPON; break; case 2: state = SelfActionType.CONTAINER_ARMOR; break; case 3: state = SelfActionType.CONTAINER_HEAL; break; case 4: state = SelfActionType.CONTAINER_DAMAGE; break; case 5: state = SelfActionType.CONTAINER_STORED; break; case 6: state = SelfActionType.CHANGE; break; } return new Action(ActionType.SELF); case CONTAINER_WEAPON: getWeaponList(); state = SelfActionType.CONTAINER; return new Action(ActionType.SELF); case CONTAINER_ARMOR: getArmorList(); state = SelfActionType.CONTAINER; return new Action(ActionType.SELF); case CONTAINER_HEAL: getHealItemsList(); state = SelfActionType.CONTAINER; return new Action(ActionType.SELF); case CONTAINER_DAMAGE: getDamageItemsList(); state = SelfActionType.CONTAINER; return new Action(ActionType.SELF); case CONTAINER_STORED: getStoredItemsList(); state = SelfActionType.CONTAINER; return new Action(ActionType.SELF); case RUN: state = SelfActionType.START; return new Action(ActionType.GO); case FIGHT: if (enemies.size() > 0) { state = SelfActionType.FIGHT; return pushEnemy(); } state = SelfActionType.START; return new Action(ActionType.SELF); } return null; } private Action pushEnemy() { printEnemiesList(); int choise = getChoose(); return new Action(ActionType.PUSH, enemies.get(choise-1).getId(), hero.getDamage()); } private int getChoose() { int res = sc.nextInt(); return res; } private void printEnemiesList() { for (Enemy e : this.enemies) { System.out.println("Имя: " + e.getName()); System.out.println("Здоровье: " + e.getHealth() + "/" + e.getMaxHealth()); System.out.println("Урон: " + e.getDamage()); System.out.println(); } } private void printGlobalActionList() { System.out.println("Действия: "); System.out.println("1) Вступить в бой"); System.out.println("2) Изменить состояние"); System.out.println("3) Данные об игроке"); System.out.println("4) Убежать"); } private void printSelfActionList() { System.out.println("Действия: "); System.out.println("1) Сменить броню"); System.out.println("2) Поменять оружие"); System.out.println("3) Посмотреть в рюкзак"); System.out.println("4) Выйти назад"); } private void printBagUnitsList() { System.out.println("Отделы: "); System.out.println("1) Оружие"); System.out.println("2) Броня"); System.out.println("3) Зелья и травы"); System.out.println("4) Ништяки"); System.out.println("5) Предметы"); System.out.println("6) Выйти назад"); } private void getArmorList() { int i = 0; ArrayList<Armor> armors = hero.getArmorItems(); if (armors == null) { System.out.println("В вашем мешке нет брони."); return; } for (Armor a : armors) { System.out.println((++i) + ") " + a.getName()); } } private void getWeaponList() { int i = 0; ArrayList<Weapon> weapon = hero.getWeaponItems(); if (weapon == null) { System.out.println("В вашем мешке нет оружия."); return; } for (Weapon a : weapon) { System.out.println((++i) + ") " + a.getName()); } } private void getHealItemsList() { int i = 0; ArrayList<InfluentableItem> heals = hero.getHealItems(); if (heals == null) { System.out.println("В вашем мешке нет трав."); return; } for (InfluentableItem a : heals) { System.out.println((++i) + ") " + a.getName()); } } private void getDamageItemsList() { int i = 0; ArrayList<InfluentableItem> damages = hero.getDamageItems(); if (damages == null) { System.out.println("В вашем мешке нет ништяков."); return; } for (InfluentableItem a : damages) { System.out.println((++i) + ") " + a.getName()); } } private void getStoredItemsList() { int i = 0; ArrayList<StoredItem> stores = hero.getStoredItems(); if (stores == null) { System.out.println("В вашем мешке нет предметов."); return; } for (StoredItem a : stores) { System.out.println((++i) + ") " + a.getName()); } } private void printHeroInfo() { System.out.println("Имя: " + hero.getName()); System.out.println("Здоровье: " + hero.getHealth() + "/" + hero.getMaxHealth()); System.out.println("Урон: " + hero.getDamage()); System.out.println("Оружие: " + hero.getWeaponName()); System.out.println("Броня: " + hero.getArmorName()); System.out.println(); } // END PRIVATE }
package com.needii.dashboard.service; import com.needii.dashboard.dao.CustomerBalanceHistoryDao; import com.needii.dashboard.model.CustomerBalanceHistory; import com.needii.dashboard.model.form.SearchForm; import com.needii.dashboard.utils.ChartData; import com.needii.dashboard.utils.Pagination; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.util.List; @Transactional @Service("customerBalanceHistoryService") public class CustomerBalanceHistoryServiceImpl implements CustomerBalanceHistoryService{ @Autowired private CustomerBalanceHistoryDao dao; @Override public List<CustomerBalanceHistory> findByCustomerId(long customerId) { // TODO Auto-generated method stub return dao.findByCustomerId(customerId); } @Override public CustomerBalanceHistory findOne(long id) { // TODO Auto-generated method stub return dao.findOne(id); } @Override public void create(CustomerBalanceHistory entity) { // TODO Auto-generated method stub dao.create(entity); } @Override public void update(CustomerBalanceHistory entity) { // TODO Auto-generated method stub dao.update(entity); } @Override public void delete(CustomerBalanceHistory entity) { // TODO Auto-generated method stub dao.delete(entity); } @Override public List<CustomerBalanceHistory> findByCustomerId(long customerId, int limit, int offset) { // TODO Auto-generated method stub return dao.findByCustomerId(customerId, limit, offset); } @Override public long count(long customerId) { // TODO Auto-generated method stub return dao.count(customerId); } @Override public List<CustomerBalanceHistory> findAll(SearchForm searchForm, Pagination pagination) { return dao.findAll(searchForm, pagination); } @Override public long count(SearchForm searchForm) { return dao.count(searchForm); } @Override public List<ChartData> findInWeek(String firstDay, String lastDay) { return dao.findInWeek(firstDay, lastDay); } @Override public List<ChartData> findInMonth(String firstDay, String lastDay) { return dao.findInMonth(firstDay, lastDay); } @Override public List<ChartData> findInYear(String firstDay, String lastDay) { return dao.findInYear(firstDay, lastDay); } }
package com.prince.joe.streams; import java.util.stream.IntStream; public class IntegerStream { public static void main(String[] args) { IntStream .range(1,10) //.skip(5) // it will print 6789 skips element until 5 .forEach(System.out::print); } }
/* * Copyright (c) 2004 Steve Northover and Mike Wilson * * Permission is hereby granted, free of charge, to any person obtaining a copy of this * software and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, modify, merge, * publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons * to whom the Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all copies or * substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, * INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR * PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE * FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ package part1.ch7; import org.eclipse.swt.*; import org.eclipse.swt.widgets.*; import org.eclipse.swt.layout.*; public class Combo2 { public static void main(String[] args) { Display display = new Display(); final Shell shell = new Shell(display); shell.setLayout(new RowLayout(SWT.VERTICAL)); final Combo combo = new Combo(shell, SWT.DROP_DOWN); combo.setItems(new String[] {"Text", "List", "Button"}); combo.setLayoutData(new RowData(200, SWT.DEFAULT)); final Label label = new Label(shell, SWT.NONE); combo.addListener(SWT.Modify, new Listener() { public void handleEvent(Event event) { String text = combo.getText(); int index = 0; while (index < text.length()) { char ch = text.charAt(index); if (!Character.isLetterOrDigit(ch)) break; index++; } if (index != text.length()) { label.setText( "Must contain only letters and digits"); } else { label.setText(""); } shell.layout(); } }); shell.pack(); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) display.sleep(); } display.dispose(); } }
package Main; import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.awt.image.*; import EstadosDoJogo.GerenciadorDeEstados; public class GamePanel extends JPanel implements Runnable, KeyListener { public static final int LARGURA = 1280; public static final int ALTURA = 720; Thread thread; private final int FPS = 60; // Quadros por segundos private final int tempoPorFrame = 1000/FPS; // Tempo mínimo que cada quadro deve gastar para ser desenhado BufferedImage imagem; //Imagem que armazena o quadro atual antes ser desenhado no painel Graphics2D g; //Usado para desenhar na imagem GerenciadorDeEstados gs; public GamePanel(){ super(); this.setPreferredSize(new Dimension(LARGURA, ALTURA)); // Definindo o tamanho do painel this.setFocusable(true); this.requestFocus(); this.addKeyListener(this); this.setVisible(true); } /** * A função addNotify é chamada quando GamePanel é adicionado à janela principal. * Ela será usada para criar um nova thread assim que isso acontecer. */ @Override public void addNotify(){ super.addNotify(); if(thread == null){ thread = new Thread(this); thread.start(); } } @Override public void run() { //Inicializando variáveis imagem = new BufferedImage(LARGURA, ALTURA, BufferedImage.TYPE_INT_RGB); g = (Graphics2D) imagem.getGraphics(); gs = new GerenciadorDeEstados(); long tempoInicial; //Tempo antes do quadro atual ser desenhado long tempoFinal; //Tempo após o quadro ser desenhado long tempoDeEspera; //Tempo em que o while loop deve esperar antes de começar a desenhar o próximo frame // GAME LOOP while(true){ tempoInicial = System.nanoTime(); // tempo inicial em nanossegundos //atualizando, renderizando e desenhando o novo quadro atualizar(); renderizar(); desenhar(); tempoFinal = (System.nanoTime() - tempoInicial)/1000000; //tempo final em milissegundos tempoDeEspera = tempoPorFrame - tempoFinal; //tempo de espera em milissegundos if(tempoDeEspera > 0){ try { Thread.sleep(tempoDeEspera); } catch (InterruptedException ex) { System.out.println("A thread do painel foi interrompida inesperadamente."); ex.printStackTrace(); } } } } //Atualiza a posição do mapa, do personagem, dos inimigos e dos projéteis private void atualizar(){ gs.atualizar(); } //Desenha o mapa, o personagem, os inimigos e os projéteis na imagem private void renderizar(){ gs.renderizar(g); } //Desenha a imagem no painel private void desenhar(){ Graphics2D g2 = (Graphics2D) this.getGraphics(); g2.drawImage(imagem, 0, 0, null); } @Override public void keyTyped(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { gs.keyPressed(e.getKeyCode()); } @Override public void keyReleased(KeyEvent e) { gs.keyReleased(e.getKeyCode()); } }
package com.uchain.core.consensus; import lombok.AllArgsConstructor; @AllArgsConstructor public class TwoTuple<A, B> { public final A first; public final B second; public String toString(){ return "(" + first + ", " + second + ")"; } }
package com.shangdao.phoenix.entity.report.strategy; import com.alibaba.fastjson.JSONObject; import com.shangdao.phoenix.entity.apisearch.APISearch; import com.shangdao.phoenix.entity.apisearch.APISearchRepository; import com.shangdao.phoenix.entity.report.Report; import com.shangdao.phoenix.entity.report.module.BaseModule; import com.shangdao.phoenix.entity.supplyAPI.SupplyAPI; import com.shangdao.phoenix.entity.supplyAPI.SupplyAPIRepository; import org.apache.tomcat.util.buf.StringUtils; import java.util.*; /** * @author huanghengkun * @date 2018/04/02 */ public abstract class BaseStrategy { protected Report report; protected SupplyAPIRepository supplyAPIRepository; protected APISearchRepository apiSearchRepository; protected final static JSONObject EMPTY_JSON = new JSONObject(); public BaseStrategy(Report report, SupplyAPIRepository supplyAPIRepository, APISearchRepository apiSearchRepository) { this.report = report; this.supplyAPIRepository = supplyAPIRepository; this.apiSearchRepository = apiSearchRepository; } public abstract boolean isAPIActive(); public abstract boolean isContainsAPI(Map<String, JSONObject> pool); public abstract boolean isAPIUnfinished(Map<String, JSONObject> pool); public abstract void tryPutEmptyAPI(Map<String, JSONObject> pool); public abstract void removeEmptyAPI(Map<String, JSONObject> pool); public abstract void putAPIResponseIntoPool(Map<String, JSONObject> pool); public abstract boolean fetchData(Map<String, JSONObject> pool); public abstract BaseModule analyseData(); public abstract void setModuleIntoReport(BaseModule module); public static class API { private SupplyAPI supplyAPI; private HashMap<String, String> parameters = new HashMap<>(); private HashMap<String, String> headers = new HashMap<>(); public SupplyAPI getSupplyAPI() { return supplyAPI; } public void setSupplyAPI(SupplyAPI supplyAPI) { this.supplyAPI = supplyAPI; } public HashMap<String, String> getParameters() { return parameters; } public void setParameters(HashMap<String, String> parameters) { this.parameters = parameters; } public HashMap<String, String> getHeaders() { return headers; } public void setHeaders(HashMap<String, String> headers) { this.headers = headers; } } protected void putCache(API api, JSONObject apiResponse) { APISearch apiSearchLog = new APISearch(); apiSearchLog.setCode(api.getSupplyAPI().getCode()); apiSearchLog.setCreatedAt(new Date()); apiSearchLog.setParameters(parametersToString(api.getParameters())); apiSearchLog.setResult(apiResponse.toJSONString()); System.out.println(apiSearchLog.toString()); apiSearchRepository.save(apiSearchLog); } protected JSONObject getCache(API api) { String parameters = parametersToString(api.getParameters()); APISearch ret = apiSearchRepository .findFirstByCodeAndParametersOrderByCreatedAtDesc(api.getSupplyAPI().getCode(), parameters); if (ret != null) { Calendar calendar = Calendar.getInstance(); calendar.setTime(ret.getCreatedAt()); calendar.add(Calendar.SECOND, api.getSupplyAPI().getEffectiveTime()); Calendar calendarNow = Calendar.getInstance(); if (calendar.compareTo(calendarNow) < 0) { return null; } return JSONObject.parseObject(ret.getResult()); } else { return null; } } private String parametersToString(Map<String, String> paramMap) { // 用于排序的list List<String> keyList = new ArrayList<>(); for (String key : paramMap.keySet()) { if (paramMap.get(key) != null && !paramMap.get(key).equals("")) { keyList.add(key); } } // 对list进行排序 Collections.sort(keyList); List<String> parameterList = new ArrayList<>(); // 将排序后的参数组成字符串 for (String key : keyList) { parameterList.add(key + "=" + paramMap.get(key)); } return StringUtils.join(parameterList, '&'); } }
package test; import br.pucrs.ep.es.ContaMagica; import br.pucrs.ep.es.model.Cliente; import org.junit.Before; import org.junit.Test; import java.math.BigDecimal; import static org.junit.Assert.*; public class ContaMagicaTest { private ContaMagica conta; @Before public void setUp() { conta = new ContaMagica(new Cliente("Felipe", 24)); conta.depositar(new BigDecimal("5000")); } @Test public void validarValorTest() { } @Test public void depositarTest() { conta.depositar(new BigDecimal("5000")); assertEquals(new BigDecimal("10000"), conta.getSaldo()); } @Test public void saldoTest() { assertEquals(new BigDecimal("5000"), conta.getSaldo()); } @Test public void retirarTest() { conta.retirar(new BigDecimal("1000")); assertEquals(new BigDecimal("4000"), conta.getSaldo()); } }
package us.ihmc.euclid.referenceFrame.interfaces; import us.ihmc.euclid.geometry.interfaces.BoundingBox3DBasics; import us.ihmc.euclid.geometry.interfaces.Line3DReadOnly; import us.ihmc.euclid.referenceFrame.FramePoint3D; import us.ihmc.euclid.referenceFrame.ReferenceFrame; import us.ihmc.euclid.referenceFrame.exceptions.ReferenceFrameMismatchException; import us.ihmc.euclid.referenceFrame.tools.EuclidFrameShapeTools; import us.ihmc.euclid.shape.primitives.interfaces.Cylinder3DReadOnly; import us.ihmc.euclid.tuple3D.interfaces.Point3DBasics; import us.ihmc.euclid.tuple3D.interfaces.Point3DReadOnly; import us.ihmc.euclid.tuple3D.interfaces.Vector3DReadOnly; /** * Read-only interface for a cylinder 3D expressed in a given reference frame. * <p> * A cylinder 3D is represented by its length, its radius, the position of its center, and its axis * of revolution. * </p> * * @author Sylvain Bertrand */ public interface FrameCylinder3DReadOnly extends Cylinder3DReadOnly, FrameShape3DReadOnly { /** {@inheritDoc} */ @Override FramePoint3DReadOnly getPosition(); /** {@inheritDoc} */ @Override FrameUnitVector3DReadOnly getAxis(); /** * {@inheritDoc} * <p> * Note that the centroid is also the position of this cylinder. * </p> */ @Override default FramePoint3DReadOnly getCentroid() { return getPosition(); } /** {@inheritDoc} */ @Override default FramePoint3DReadOnly getTopCenter() { FramePoint3D topCenter = new FramePoint3D(getReferenceFrame()); topCenter.scaleAdd(getHalfLength(), getAxis(), getPosition()); return topCenter; } /** {@inheritDoc} */ @Override default Point3DReadOnly getBottomCenter() { FramePoint3D bottomCenter = new FramePoint3D(getReferenceFrame()); bottomCenter.scaleAdd(-getHalfLength(), getAxis(), getPosition()); return bottomCenter; } /** * Computes the coordinates of the possible intersections between a line and this cylinder. * <p> * In the case the line and this cylinder do not intersect, this method returns {@code 0} and * {@code firstIntersectionToPack} and {@code secondIntersectionToPack} remain unmodified. * </p> * * @param line the line expressed in world coordinates that may intersect this * cylinder. Not modified. * @param firstIntersectionToPack the coordinate in world of the first intersection. Can be * {@code null}. Modified. * @param secondIntersectionToPack the coordinate in world of the second intersection. Can be * {@code null}. Modified. * @return the number of intersections between the line and this cylinder. It is either equal to 0, * 1, or 2. * @throws ReferenceFrameMismatchException if the frame argument is not expressed in the same * reference frame as {@code this}. */ default int intersectionWith(FrameLine3DReadOnly line, Point3DBasics firstIntersectionToPack, Point3DBasics secondIntersectionToPack) { return intersectionWith(line.getPoint(), line.getDirection(), firstIntersectionToPack, secondIntersectionToPack); } /** * Computes the coordinates of the possible intersections between a line and this cylinder. * <p> * In the case the line and this cylinder do not intersect, this method returns {@code 0} and * {@code firstIntersectionToPack} and {@code secondIntersectionToPack} remain unmodified. * </p> * * @param line the line expressed in world coordinates that may intersect this * cylinder. Not modified. * @param firstIntersectionToPack the coordinate in world of the first intersection. Can be * {@code null}. Modified. * @param secondIntersectionToPack the coordinate in world of the second intersection. Can be * {@code null}. Modified. * @return the number of intersections between the line and this cylinder. It is either equal to 0, * 1, or 2. * @throws ReferenceFrameMismatchException if {@code line} is not expressed in the same reference * frame as {@code this}. */ default int intersectionWith(FrameLine3DReadOnly line, FramePoint3DBasics firstIntersectionToPack, FramePoint3DBasics secondIntersectionToPack) { return intersectionWith(line.getPoint(), line.getDirection(), firstIntersectionToPack, secondIntersectionToPack); } /** * Computes the coordinates of the possible intersections between a line and this cylinder. * <p> * In the case the line and this cylinder do not intersect, this method returns {@code 0} and * {@code firstIntersectionToPack} and {@code secondIntersectionToPack} remain unmodified. * </p> * * @param line the line expressed in world coordinates that may intersect this * cylinder. Not modified. * @param firstIntersectionToPack the coordinate in world of the first intersection. Can be * {@code null}. Modified. * @param secondIntersectionToPack the coordinate in world of the second intersection. Can be * {@code null}. Modified. * @return the number of intersections between the line and this cylinder. It is either equal to 0, * 1, or 2. */ default int intersectionWith(Line3DReadOnly line, FramePoint3DBasics firstIntersectionToPack, FramePoint3DBasics secondIntersectionToPack) { return intersectionWith(line.getPoint(), line.getDirection(), firstIntersectionToPack, secondIntersectionToPack); } /** * Computes the coordinates of the possible intersections between a line and this cylinder. * <p> * In the case the line and this cylinder do not intersect, this method returns {@code 0} and * {@code firstIntersectionToPack} and {@code secondIntersectionToPack} remain unmodified. * </p> * * @param line the line expressed in world coordinates that may intersect this * cylinder. Not modified. * @param firstIntersectionToPack the coordinate in world of the first intersection. Can be * {@code null}. Modified. * @param secondIntersectionToPack the coordinate in world of the second intersection. Can be * {@code null}. Modified. * @return the number of intersections between the line and this cylinder. It is either equal to 0, * 1, or 2. * @throws ReferenceFrameMismatchException if any of the frame arguments is not expressed in the * same reference frame as {@code this}. */ default int intersectionWith(Line3DReadOnly line, FixedFramePoint3DBasics firstIntersectionToPack, FixedFramePoint3DBasics secondIntersectionToPack) { return intersectionWith(line.getPoint(), line.getDirection(), firstIntersectionToPack, secondIntersectionToPack); } /** * Computes the coordinates of the possible intersections between a line and this cylinder. * <p> * In the case the line and this cylinder do not intersect, this method returns {@code 0} and * {@code firstIntersectionToPack} and {@code secondIntersectionToPack} remain unmodified. * </p> * * @param line the line expressed in world coordinates that may intersect this * cylinder. Not modified. * @param firstIntersectionToPack the coordinate in world of the first intersection. Can be * {@code null}. Modified. * @param secondIntersectionToPack the coordinate in world of the second intersection. Can be * {@code null}. Modified. * @return the number of intersections between the line and this cylinder. It is either equal to 0, * 1, or 2. * @throws ReferenceFrameMismatchException if any of the arguments is not expressed in the same * reference frame as {@code this}. */ default int intersectionWith(FrameLine3DReadOnly line, FixedFramePoint3DBasics firstIntersectionToPack, FixedFramePoint3DBasics secondIntersectionToPack) { return intersectionWith(line.getPoint(), line.getDirection(), firstIntersectionToPack, secondIntersectionToPack); } /** * Computes the coordinates of the possible intersections between a line and this cylinder. * <p> * In the case the line and this cylinder do not intersect, this method returns {@code 0} and * {@code firstIntersectionToPack} and {@code secondIntersectionToPack} remain unmodified. * </p> * * @param pointOnLine a point expressed in world located on the infinitely long line. * Not modified. * @param lineDirection the direction expressed in world of the line. Not modified. * @param firstIntersectionToPack the coordinate in world of the first intersection. Can be * {@code null}. Modified. * @param secondIntersectionToPack the coordinate in world of the second intersection. Can be * {@code null}. Modified. * @return the number of intersections between the line and this cylinder. It is either equal to 0, * 1, or 2. * @throws ReferenceFrameMismatchException if any of the arguments is not expressed in the same * reference frame as {@code this}. */ default int intersectionWith(FramePoint3DReadOnly pointOnLine, FrameVector3DReadOnly lineDirection, Point3DBasics firstIntersectionToPack, Point3DBasics secondIntersectionToPack) { checkReferenceFrameMatch(pointOnLine, lineDirection); return Cylinder3DReadOnly.super.intersectionWith(pointOnLine, lineDirection, firstIntersectionToPack, secondIntersectionToPack); } /** * Computes the coordinates of the possible intersections between a line and this cylinder. * <p> * In the case the line and this cylinder do not intersect, this method returns {@code 0} and * {@code firstIntersectionToPack} and {@code secondIntersectionToPack} remain unmodified. * </p> * * @param pointOnLine a point expressed in world located on the infinitely long line. * Not modified. * @param lineDirection the direction expressed in world of the line. Not modified. * @param firstIntersectionToPack the coordinate in world of the first intersection. Can be * {@code null}. Modified. * @param secondIntersectionToPack the coordinate in world of the second intersection. Can be * {@code null}. Modified. * @return the number of intersections between the line and this cylinder. It is either equal to 0, * 1, or 2. */ default int intersectionWith(Point3DReadOnly pointOnLine, Vector3DReadOnly lineDirection, FramePoint3DBasics firstIntersectionToPack, FramePoint3DBasics secondIntersectionToPack) { if (firstIntersectionToPack != null) firstIntersectionToPack.setReferenceFrame(getReferenceFrame()); if (secondIntersectionToPack != null) secondIntersectionToPack.setReferenceFrame(getReferenceFrame()); return Cylinder3DReadOnly.super.intersectionWith(pointOnLine, lineDirection, firstIntersectionToPack, secondIntersectionToPack); } /** * Computes the coordinates of the possible intersections between a line and this cylinder. * <p> * In the case the line and this cylinder do not intersect, this method returns {@code 0} and * {@code firstIntersectionToPack} and {@code secondIntersectionToPack} remain unmodified. * </p> * * @param pointOnLine a point expressed in world located on the infinitely long line. * Not modified. * @param lineDirection the direction expressed in world of the line. Not modified. * @param firstIntersectionToPack the coordinate in world of the first intersection. Can be * {@code null}. Modified. * @param secondIntersectionToPack the coordinate in world of the second intersection. Can be * {@code null}. Modified. * @return the number of intersections between the line and this cylinder. It is either equal to 0, * 1, or 2. * @throws ReferenceFrameMismatchException if any of the arguments is not expressed in the same * reference frame as {@code this}. */ default int intersectionWith(Point3DReadOnly pointOnLine, Vector3DReadOnly lineDirection, FixedFramePoint3DBasics firstIntersectionToPack, FixedFramePoint3DBasics secondIntersectionToPack) { if (firstIntersectionToPack != null) checkReferenceFrameMatch(firstIntersectionToPack); if (secondIntersectionToPack != null) checkReferenceFrameMatch(secondIntersectionToPack); return Cylinder3DReadOnly.super.intersectionWith(pointOnLine, lineDirection, firstIntersectionToPack, secondIntersectionToPack); } /** * Computes the coordinates of the possible intersections between a line and this cylinder. * <p> * In the case the line and this cylinder do not intersect, this method returns {@code 0} and * {@code firstIntersectionToPack} and {@code secondIntersectionToPack} remain unmodified. * </p> * * @param pointOnLine a point expressed in world located on the infinitely long line. * Not modified. * @param lineDirection the direction expressed in world of the line. Not modified. * @param firstIntersectionToPack the coordinate in world of the first intersection. Can be * {@code null}. Modified. * @param secondIntersectionToPack the coordinate in world of the second intersection. Can be * {@code null}. Modified. * @return the number of intersections between the line and this cylinder. It is either equal to 0, * 1, or 2. * @throws ReferenceFrameMismatchException if either {@code pointOnLine} or {@code lineDirection} is * not expressed in the same reference frame as * {@code this}. */ default int intersectionWith(FramePoint3DReadOnly pointOnLine, FrameVector3DReadOnly lineDirection, FramePoint3DBasics firstIntersectionToPack, FramePoint3DBasics secondIntersectionToPack) { checkReferenceFrameMatch(pointOnLine, lineDirection); if (firstIntersectionToPack != null) firstIntersectionToPack.setReferenceFrame(getReferenceFrame()); if (secondIntersectionToPack != null) secondIntersectionToPack.setReferenceFrame(getReferenceFrame()); return Cylinder3DReadOnly.super.intersectionWith(pointOnLine, lineDirection, firstIntersectionToPack, secondIntersectionToPack); } /** * Computes the coordinates of the possible intersections between a line and this cylinder. * <p> * In the case the line and this cylinder do not intersect, this method returns {@code 0} and * {@code firstIntersectionToPack} and {@code secondIntersectionToPack} remain unmodified. * </p> * * @param pointOnLine a point expressed in world located on the infinitely long line. * Not modified. * @param lineDirection the direction expressed in world of the line. Not modified. * @param firstIntersectionToPack the coordinate in world of the first intersection. Can be * {@code null}. Modified. * @param secondIntersectionToPack the coordinate in world of the second intersection. Can be * {@code null}. Modified. * @return the number of intersections between the line and this cylinder. It is either equal to 0, * 1, or 2. */ default int intersectionWith(FramePoint3DReadOnly pointOnLine, FrameVector3DReadOnly lineDirection, FixedFramePoint3DBasics firstIntersectionToPack, FixedFramePoint3DBasics secondIntersectionToPack) { checkReferenceFrameMatch(pointOnLine, lineDirection); if (firstIntersectionToPack != null) checkReferenceFrameMatch(firstIntersectionToPack); if (secondIntersectionToPack != null) checkReferenceFrameMatch(secondIntersectionToPack); return Cylinder3DReadOnly.super.intersectionWith(pointOnLine, lineDirection, firstIntersectionToPack, secondIntersectionToPack); } /** {@inheritDoc} */ @Override default void getBoundingBox(BoundingBox3DBasics boundingBoxToPack) { FrameShape3DReadOnly.super.getBoundingBox(boundingBoxToPack); } /** {@inheritDoc} */ @Override default void getBoundingBox(ReferenceFrame destinationFrame, BoundingBox3DBasics boundingBoxToPack) { EuclidFrameShapeTools.boundingBoxCylinder3D(this, destinationFrame, boundingBoxToPack); } /** * Returns {@code null} as this shape is not defined by a pose. */ @Override default FrameShape3DPoseReadOnly getPose() { return null; } /** {@inheritDoc} */ @Override FixedFrameCylinder3DBasics copy(); /** * Tests on a per component basis if this cylinder and {@code other} are equal to an * {@code epsilon}. * <p> * If the two cylinders have different frames, this method returns {@code false}. * </p> * * @param other the other cylinder to compare against this. Not modified. * @param epsilon tolerance to use when comparing each component. * @return {@code true} if the two cylinders are equal component-wise and are expressed in the same * reference frame, {@code false} otherwise. */ default boolean epsilonEquals(FrameCylinder3DReadOnly other, double epsilon) { if (getReferenceFrame() != other.getReferenceFrame()) return false; else return Cylinder3DReadOnly.super.epsilonEquals(other, epsilon); } /** * Compares {@code this} and {@code other} to determine if the two cylinders are geometrically * similar. * * @param other the cylinder to compare to. Not modified. * @param epsilon the tolerance of the comparison. * @return {@code true} if the cylinders represent the same geometry, {@code false} otherwise. * @throws ReferenceFrameMismatchException if {@code this} and {@code other} are not expressed in * the same reference frame. */ default boolean geometricallyEquals(FrameCylinder3DReadOnly other, double epsilon) { checkReferenceFrameMatch(other); return Cylinder3DReadOnly.super.geometricallyEquals(other, epsilon); } /** * Tests on a per component basis, if this cylinder 3D is exactly equal to {@code other}. * <p> * If the two cylinders have different frames, this method returns {@code false}. * </p> * * @param other the other cylinder 3D to compare against this. Not modified. * @return {@code true} if the two cylinders are exactly equal component-wise and are expressed in * the same reference frame, {@code false} otherwise. */ default boolean equals(FrameCylinder3DReadOnly other) { if (other == this) { return true; } else if (other == null) { return false; } else { if (getReferenceFrame() != other.getReferenceFrame()) return false; if (getLength() != other.getLength()) return false; if (getRadius() != other.getRadius()) return false; if (!getPosition().equals(other.getPosition())) return false; if (!getAxis().equals(other.getAxis())) return false; return true; } } }
/* * Faça uma função que recebe a idade de um nadador por parâmetro e retorna , também por parâmetro, a categoria desse nadador (tipo String) de acordo com a tabela abaixo: */ package Lista3; import java.util.Scanner; public class Exercicio10 { static Scanner input = new Scanner(System.in); static int entrada(){ System.out.print("Idade: "); int idade = input.nextInt(); return idade; } static String categoria(int idade){ String categoria=""; if((idade>=5)&(idade<=7)){ categoria="Infantil A"; } else if((idade>=8)&(idade<=10)){ categoria="Infantil B"; } else if((idade>=11)&(idade<=13)){ categoria="Juvenil A"; } else if((idade>=14)&(idade<=17)){ categoria="Juvenil B"; } else if(idade>=18){ categoria="Adulto"; } else{ categoria="Não tem categoria para menores de 5 anos"; } return categoria; } static void imprimir(String categoria){ System.out.println(categoria); } public static void main(String[] args) { int idade=entrada(); String categoria=categoria(idade); imprimir(categoria); } }
package com.icia.example03.controller; import java.time.*; import org.springframework.stereotype.*; import org.springframework.web.bind.*; import org.springframework.web.bind.annotation.*; import org.springframework.web.servlet.*; import com.icia.example03.editor.*; import com.icia.example03.vo.*; import lombok.extern.slf4j.*; @Slf4j @RequestMapping("/sample3") @Controller public class SampleController35 { // pno=11&name=음료수&sales=1 @RequestMapping("/test51") public ModelAndView test1(@RequestParam int pno, @RequestParam String name, @RequestParam boolean sales) { log.info("{}", sales); return null; } // urlencoded 파라미터를 적절한 객체로 변환해주는 표준 : PropertyEditor // 스프링이 PropertyEditor인터페이스를 구현해서 몇개의 에디터를 제공 -> 자동 변환 // LocalDate의 경우 스프링이 제공하지 않는다 -> 내가 만든 다음 등록 @RequestMapping("/test52") public ModelAndView test2() { return new ModelAndView("test5/input"); } // pno=11&name=drink$price=1500&productday=2020-11-20 @RequestMapping(value="/test52", method=RequestMethod.POST) public ModelAndView test2(@ModelAttribute Product2 product) { return new ModelAndView("test5/result").addObject("product", product); } // 내가 만든 에디터를 WebDataBinder에 등록 @InitBinder public void init(WebDataBinder wdb) { // 타입으로 지정 -> 모든 LocalDate에 대해 적용 // wdb.registerCustomEditor(getClass(), null); // 필드명으로 지정 -> LocalDate중에서 productday에 대해 적용 wdb.registerCustomEditor(LocalDate.class, "productday", new CustomLocalDateEditor()); } }
package com.proximizer.client; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.TimeZone; import org.ksoap2.SoapEnvelope; import org.ksoap2.serialization.PropertyInfo; import org.ksoap2.serialization.SoapObject; import org.ksoap2.serialization.SoapSerializationEnvelope; import org.ksoap2.transport.HttpTransportSE; import android.util.Log; public class RemoteServices { private static final String NAMESPACE = "http://server.proximizer.com"; private static final String URL = "http://10.0.0.2:8080/Proximizer_server1/services/processor?wsdl"; private static final String SOAP_ACTION = "http://10.0.0.2:8080/Proximizer_server1/services/processor"; private static final String TAG = "RemoteService"; public RemoteServices() { // TODO Auto-generated constructor stub } /** * Represents an Register task for registering new users */ public static boolean register(String username,String password) { boolean status =false ; return status ; } /** * This method calls the external web service for authentication */ /** * * Adds friends for the user */ public static boolean addFriend(String username,String friendName) { boolean isAdded = false ; return isAdded ; } /** * * This deletes the friend for the particular user. * @return */ public static boolean deleteFriend(String username, String friendName) { boolean isDeleted =false ; return isDeleted ; } /** * * Get location of a users. * Returns Location object */ /* public static Location getLocation(String username) { Location loc =null ; return loc ; }*/ }
package com.davivienda.utilidades.ws.cliente.solicitarNotaDebitoCuentaAhorrosServiceATM; import java.net.MalformedURLException; import java.net.URL; import javax.xml.namespace.QName; import javax.xml.ws.Service; import javax.xml.ws.WebEndpoint; import javax.xml.ws.WebServiceClient; import javax.xml.ws.WebServiceException; import javax.xml.ws.WebServiceFeature; /** * This class was generated by the JAX-WS RI. * JAX-WS RI 2.2.6-1b01 * Generated source version: 2.2 * */ @WebServiceClient(name = "SolictarNotaDebitoCuentaAhorrosServiceATMService", targetNamespace = "http://solictarnotadebitocuentaahorrosservice.servicios.procesadortransacciones.davivienda.com/") public class SolictarNotaDebitoCuentaAhorrosServiceATMService extends Service { private final static QName SOLICTARNOTADEBITOCUENTAAHORROSSERVICEATMSERVICE_QNAME = new QName("http://solictarnotadebitocuentaahorrosservice.servicios.procesadortransacciones.davivienda.com/", "SolictarNotaDebitoCuentaAhorrosServiceATMService"); public SolictarNotaDebitoCuentaAhorrosServiceATMService(URL wsdlLocation) { super(wsdlLocation, SOLICTARNOTADEBITOCUENTAAHORROSSERVICEATMSERVICE_QNAME); } @WebEndpoint(name = "SolictarNotaDebitoCuentaAhorrosServiceATMPort") public ISolictarNotaDebitoCuentaAhorrosServiceATM getSolictarNotaDebitoCuentaAhorrosServiceATMPort() { return super.getPort(new QName("http://solictarnotadebitocuentaahorrosservice.servicios.procesadortransacciones.davivienda.com/", "SolictarNotaDebitoCuentaAhorrosServiceATMPort"), ISolictarNotaDebitoCuentaAhorrosServiceATM.class); } }
package com.ecolife.ApirestEcolife.repository; import org.springframework.data.jpa.repository.JpaRepository; import com.ecolife.ApirestEcolife.models.Ecocliente; public interface EcoclienteRepository extends JpaRepository<Ecocliente, Long> { Ecocliente findById(long id); Ecocliente findByCpfOrEmail(String cpf, String email); }
package com.github.fierioziy.particlenativeapi.core.asm.mapping; public interface ClassMapping { String internalName(); String className(); String desc(); }
public class Servico implements Vendavel { private String descricao; private Integer codigo; private Integer quantHoras; private Double valorHora; public Servico(String descricao, Integer codigo, Integer quantHoras, Double valorHora) { this.descricao = descricao; this.codigo = codigo; this.quantHoras = quantHoras; this.valorHora = valorHora; } @Override public Double getValorVenda() { return quantHoras * valorHora; } @Override public String toString() { return "Servico{" + "descricao='" + descricao + '\'' + ", codigo=" + codigo + ", quantHoras=" + quantHoras + ", valorHora=" + valorHora + ", valorVenda=" + getValorVenda() + '}'; } }
package com.restapi.model; import com.restapi.security.service.PasswordHandler; import lombok.Data; import org.bson.types.ObjectId; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.index.Indexed; import org.springframework.data.mongodb.core.mapping.Document; import org.springframework.security.core.userdetails.UserDetails; import java.util.ArrayList; import java.util.List; import java.util.UUID; @Data @Document(collection = "users") public class User implements UserDetails { private String firstName; private String lastName; @Indexed(unique = true) private String username; private String password; private int accType; // 1:Child; 2:Parent; private boolean enabled; private String email; private int birthday; private String gender; private String token; private ArrayList<String> relatives = new ArrayList<>(); private String familyId; @Id private ObjectId id; private String fcmToken; private List<Role> authorities; //private boolean accountNonExpired; public User(String firstName, String lastName, String username, String email, String password, int birthday, String gender, boolean enabled, int accType){ this.firstName = firstName; this.lastName = lastName; this.username = username; this.password = password; this.accType = accType; this.enabled = enabled; this.email = email; this.birthday = birthday; this.gender = gender; } public String getFcmToken() { return fcmToken; } public void setFcmToken(String fcmToken) { this.fcmToken = fcmToken; } @Override public List<Role> getAuthorities() { return this.authorities; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } @Override public String getUsername() { return username; } @Override public boolean isAccountNonExpired() { return false; } @Override public boolean isAccountNonLocked() { return false; } @Override public boolean isCredentialsNonExpired() { return false; } // @Override // public boolean isEnabled() { // return false; // } public void setUsername(String username) { this.username = username; } // @Override // public Collection<? extends GrantedAuthority> getAuthorities() { // return null; // } public void setAuthorities(List<Role> authorities) { this.authorities = authorities; } @Override public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } public void encodePassword() { setPassword(PasswordHandler.securePassword(this.password)); } public int getAccType() { return accType; } public void setAccType(int accType) { this.accType = accType; } @Override public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public int getBirthday() { return birthday; } public void setBirthday(int birthday) { this.birthday = birthday; } public String getGender() { return gender; } public void setGender(String gender) { this.gender = gender; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } public ArrayList<String> getParentUsernames() { return relatives; } public void setConnections(ArrayList<String> parents) { this.relatives = parents; } public void addConnectedUser(String username) { this.relatives.add(username); } public void removeConnectedUser(String username) { this.relatives.remove(username); } public String generateFamilyId() { this.familyId = UUID.randomUUID().toString(); return this.familyId; } public ObjectId getId() { return id; } public void setId(ObjectId id) { this.id = id; } public String getFamilyId() { return familyId; } public void setFamilyId(String familyId) { this.familyId = familyId; } // public void setAccountNonExpired(boolean accountNonExpired) { // this.accountNonExpired = true; // } }
package com.example.devnews; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.FragmentManager; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.ImageButton; import android.widget.TextView; import com.bumptech.glide.Glide; import com.example.devnews.activity.Authorization; import com.example.devnews.fragment.NewsFragment; import com.example.devnews.model.UserInformation; import com.example.devnews.rests.ApiClient; import com.example.devnews.rests.ApiInterface; import com.google.android.material.navigation.NavigationView; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener { private NavigationView navigationView; private TextView userName; private ImageButton imageProfile; private SharedPreferences mySharedPreferences; public static final String LOGIN_ACCOUNT = "user"; public static final String PASSWORD_ACCOUNT = "pass"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mySharedPreferences = getSharedPreferences(Authorization.MY_PREFERENCES, Context.MODE_PRIVATE); setContentView(R.layout.activity_main); navigationView = findViewById(R.id.main_navigation_view); if (navigationView != null) { navigationView.setNavigationItemSelectedListener(this); } View view = navigationView.inflateHeaderView(R.layout.navigation_header_image); userName = view.findViewById(R.id.header_profile_username); imageProfile = view.findViewById(R.id.header_profile_photo); ApiInterface apiService = ApiClient.getClient().create(ApiInterface.class); Call<UserInformation> call = apiService.getUserOfUrl("alfredosalzillo"); call.enqueue(new Callback<UserInformation>() { @Override public void onResponse(Call<UserInformation> call, Response<UserInformation> response) { UserInformation userInformation = response.body(); userName.setText(userInformation.getName()); Glide.with(getBaseContext()) .load(userInformation.getProfileImage()) .circleCrop().into(imageProfile); } @Override public void onFailure(Call<UserInformation> call, Throwable t) { } }); FragmentManager manager = getSupportFragmentManager(); manager.beginTransaction().replace(R.id.main_root_layout_of_fragment, NewsFragment.newInstance()).addToBackStack(null).commit(); } @Override protected void onResume() { super.onResume(); Log.d("logining","onResume"); if(mySharedPreferences.contains(Authorization.LOGIN_USER)){ Log.d("logining","exist"); String user_account = mySharedPreferences.getString(MainActivity.LOGIN_ACCOUNT,""); String pass_account = mySharedPreferences.getString(MainActivity.PASSWORD_ACCOUNT,""); String user_name = mySharedPreferences.getString(Authorization.LOGIN_USER,""); String pass_name = mySharedPreferences.getString(Authorization.PASS_USER,""); if (!(user_name.equals(user_account) && pass_name.equals(pass_account))){ startActivity(new Intent(getApplicationContext(),Authorization.class)); }} else {startActivity(new Intent(getApplicationContext(),Authorization.class));} } @Override public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) { FragmentManager manager = getSupportFragmentManager(); int id = menuItem.getItemId(); switch (id){ case R.id.menu_item_news: manager.beginTransaction().replace(R.id.main_root_layout_of_fragment, NewsFragment.newInstance()).addToBackStack(null).commit(); break; case R.id.menu_item_logout: SharedPreferences.Editor edit = mySharedPreferences.edit(); edit.putString(Authorization.LOGIN_USER,""); edit.putString(Authorization.PASS_USER,""); edit.apply(); startActivity(new Intent(getBaseContext(),Authorization.class)); break; } return false; } }
package kr.or.ddit.user.controller; import java.io.IOException; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import kr.or.ddit.common.model.PageVo; import kr.or.ddit.user.model.UserVo; import kr.or.ddit.user.service.UserService; import kr.or.ddit.user.service.UserServiceI; @WebServlet("/pagingUser") public class pagingUser extends HttpServlet { private UserServiceI service = new UserService(); @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // left.jsp " // ===> pagingUser // doGet 메소드에서 page, pageSize 파라미터가 request 객체에 존재하지 않을 때 // page는 1로 pageSize는 5로 생각하여 코드 작성 // 파라미터가 존재하면 해당 파라미터를 이용 // primitive Type 원시타입 ==> class(wrapper 클래스) // if/ else ==> 조건 ? true일대 반환할 값 : false 일때 반환할 값 // refactoring : 코드를 깔끔하게 바꾸는데 기존 동작 방식을 유지한 채로 변경하는 기봅 // int page = req.getParameter("page") == null? 1: Integer.parseInt(req.getParameter("page")); // int pageSize = req.getParameter("pageSize") == null? 5: Integer.parseInt(req.getParameter("pageSize")); // refactoring 하기 String pageParam = req.getParameter("page"); String pageSizeParam = req.getParameter("pageSize"); int page = pageParam == null? 1: Integer.parseInt(req.getParameter("page")); int pageSize = pageSizeParam == null? 5: Integer.parseInt(req.getParameter("pageSize")); PageVo vo = new PageVo(page, pageSize); // List<UserVo> pageList = service.selectPagingUser(vo); Map<String, Object> map = service.selectPagingUser(vo); List<UserVo> pageList = (List<UserVo>)map.get("userList"); int userCnt = (int)map.get("userCnt"); // 페이징 계산 int pagination = (int)Math.ceil((double)userCnt/ pageSize); //숫자 4라는 값을 만들어 낼 수 있다 req.setAttribute("pageList",pageList); // 4라는 값을 만들어서 넣어주기 req.setAttribute("pagination", pagination); // 현재의 페이지를 나타내기 위한 pageVo를 넣어준다 - 속성값 req.setAttribute("pageVo", vo); // req.getRequestDispatcher("/user/pagingUser.jsp").forward(req, resp); req.getRequestDispatcher("/user/pagingUser_sem.jsp").forward(req, resp); } }
package it.unical.dimes.processmining.core; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.TreeSet; public class NodeSplits { private class SemanticNode { int node; HashMap<TreeSet<Integer>, Integer> split = new HashMap<TreeSet<Integer>, Integer>(); HashMap<TreeSet<Integer>, Integer> join = new HashMap<TreeSet<Integer>, Integer>(); private TreeSet<Integer> spl = new TreeSet<Integer>(); private TreeSet<Integer> joi = new TreeSet<Integer>(); private SemanticNode(int node) { this.node = node; } private void calcolaSplitJoin(LinkedList<Integer> trace) { if (trace.contains(node)) { TreeSet<Integer> localSplitBinding = getLocalSplitBinding(trace); TreeSet<Integer> localJoinBinding = getLocalJoinBinding(trace); Integer splitOccurrence = split.get(localSplitBinding); if (splitOccurrence == null) { splitOccurrence = 0; } Integer joinOccurrence = join.get(localJoinBinding); if (joinOccurrence == null) { joinOccurrence = 0; } split.put(localSplitBinding, splitOccurrence + 1); join.put(localJoinBinding, joinOccurrence + 1); } } private TreeSet<Integer> getLocalSplitBinding(Collection<Integer> trace) { Iterator<Integer> it = trace.iterator(); boolean trovato = false; TreeSet<Integer> localSplitSet = new TreeSet<Integer>(); while (it.hasNext()) { Integer ne = it.next(); if(!trovato && ne != node) continue; else trovato = true; if(trovato && spl.contains(ne)) localSplitSet.add(ne); } return localSplitSet; } private TreeSet<Integer> getLocalJoinBinding(LinkedList<Integer> trace) { Iterator<Integer> it = trace.descendingIterator(); boolean trovato = false; TreeSet<Integer> localJoinSet = new TreeSet<Integer>(); while (it.hasNext()) { Integer ne = it.next(); if(!trovato && ne!=node) continue; else trovato = true; if(trovato && joi.contains(ne)) localJoinSet.add(ne); } return localJoinSet; } } private LinkedList<LinkedList<Integer>> traces; private SemanticNode[] nodi; private boolean[][] graph; public NodeSplits(LinkedList<LinkedList<Integer>> linkedList, int Nnodi, boolean[][] graph) { super(); this.traces = linkedList; this.nodi = new SemanticNode[Nnodi]; this.graph = graph; this.generate(); } public NodeSplits(LinkedList<LinkedList<Integer>> linkedList, int Nnodi, boolean[][] graph, boolean flag) { // TODO Auto-generated constructor stub super(); this.nodi = new SemanticNode[Nnodi]; this.traces = linkedList; this.graph = graph; for(int i = 0 ; i < Nnodi ; i++) nodi[i] = new SemanticNode(i); } private void generate() { for (int i = 0; i < graph.length; i++) { for (int j = 0; j < graph[0].length; j++) { if (nodi[j] == null) { nodi[j] = new SemanticNode(j); } if (graph[i][j]) { nodi[i].spl.add(j); nodi[j].joi.add(i); } } } for (LinkedList<Integer> trace : traces) for (int i = 0; i < nodi.length; i++) { nodi[i].calcolaSplitJoin(trace); } } public void setTraces(LinkedList<LinkedList<Integer>> traces) { this.traces = traces; } public void setNodi(SemanticNode[] nodi) { this.nodi = nodi; } public void setGraph(boolean[][] graph) { this.graph = graph; } public HashMap<TreeSet<Integer>, Integer> getJoinSets(int node) { return nodi[node].join; } public HashMap<TreeSet<Integer>, Integer> getSplitSets(int node) { return nodi[node].split; } public void setJoinSets(HashMap<TreeSet<Integer>, Integer> join, int node) { nodi[node].join = join; } public void setSplitSets(HashMap<TreeSet<Integer>, Integer> split, int node) { nodi[node].split = split; } public int size() { return nodi.length; } }
package com.ganyoubing.study; public class Study { private int age ; private String six; private int no; }
package com.stk123.app.config; import com.stk123.common.CommonConstant; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.messaging.simp.config.MessageBrokerRegistry; import org.springframework.web.socket.config.annotation.*; import org.springframework.web.socket.server.standard.ServletServerContainerFactoryBean; //@Configuration //@EnableWebSocketMessageBroker public class WebSocketConfig implements WebSocketMessageBrokerConfigurer { private static final int MAX_MESSAGE_SIZE = 64 * 1024 * 100; private static final long MAX_IDLE = 60 * 60 * 1000; @Override public void configureMessageBroker(MessageBrokerRegistry config) { config.enableSimpleBroker("/topic"); config.setApplicationDestinationPrefixes(CommonConstant.WS_PREFIX); } @Override public void registerStompEndpoints(StompEndpointRegistry registry) { registry.addEndpoint(CommonConstant.WS_ENDPOINT).withSockJS(); } /* The solution for WebSocket size limitation: 添加下面2个方法,并设置MAX_MESSAGE_SIZE configureWebSocketTransport createServletServerContainerFactoryBean 具体是哪个方法起作用还有待验证 */ @Override public void configureWebSocketTransport(WebSocketTransportRegistration registration) { registration.setMessageSizeLimit(MAX_MESSAGE_SIZE); // default : 64 * 1024 registration.setSendTimeLimit(20 * 10000); // default : 10 * 10000 registration.setSendBufferSizeLimit(10 * MAX_MESSAGE_SIZE); // default : 512 * 1024 } @Bean public ServletServerContainerFactoryBean createServletServerContainerFactoryBean() { ServletServerContainerFactoryBean container = new ServletServerContainerFactoryBean(); container.setMaxTextMessageBufferSize(MAX_MESSAGE_SIZE); container.setMaxBinaryMessageBufferSize(MAX_MESSAGE_SIZE); container.setMaxSessionIdleTimeout(MAX_IDLE); return container; } }
package gameLogic; import com.badlogic.gdx.Game; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import screens.MainMenuScreen; public class GameManager extends Game { //used on launch, starts an instance of the Splash Screen public SpriteBatch batcher; public BitmapFont font; @Override public void create(){ batcher = new SpriteBatch(); font= new BitmapFont(); setScreen(new MainMenuScreen(this)); } @Override public void render(){ super.render(); } @Override public void dispose(){ batcher.dispose(); font.dispose(); } }
/****************************************************************************** * __ * * <-----/@@\-----> * * <-< < \\// > >-> * * <-<-\ __ /->-> * * Data / \ Crow * * ^ ^ * * info@datacrow.net * * * * This file is part of Data Crow. * * Data Crow is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public * * License as published by the Free Software Foundation; either * * version 3 of the License, or any later version. * * * * Data Crow is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public * * License along with this program. If not, see http://www.gnu.org/licenses * * * ******************************************************************************/ package net.datacrow.core.modules.upgrade; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import java.util.Collection; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import net.datacrow.core.DataCrow; import net.datacrow.core.modules.ModuleJar; import net.datacrow.core.modules.xml.XmlField; import net.datacrow.core.modules.xml.XmlModule; import net.datacrow.core.modules.xml.XmlObject; import net.datacrow.core.resources.DcResources; import net.datacrow.util.XMLParser; import org.apache.log4j.Logger; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; /** * Upgrades the actual module jar file. Fields can be added, removed or altered. * * @author Robert Jan van der Waals */ public class ModuleUpgrade extends XmlObject { private static Logger logger = Logger.getLogger(ModuleUpgrade.class.getName()); private File add; private File alter; private File remove; /** * Upgrades the module based on a XML upgrade definition. * * @param xml * @return * @throws ModuleUpgradeException */ public byte[] upgrade(byte[] xml) throws ModuleUpgradeException { return xml; } public void upgrade() throws ModuleUpgradeException { removeDuplicates(); add = new File(DataCrow.upgradeDir + "add.xml"); alter = new File(DataCrow.upgradeDir + "alter.xml"); remove = new File(DataCrow.upgradeDir + "remove.xml"); try { if (remove.exists()) remove(); if (add.exists()) add(); if (alter.exists()) alter(); } catch (Exception exp) { throw new ModuleUpgradeException(exp); } } private void save(XmlModule module, String filename) throws Exception { ModuleJar mj = new ModuleJar(module); mj.setFilename(filename); mj.save(); } private XmlField getField(int index, Collection<XmlField> fields) { for (XmlField field : fields) if (field.getIndex() == index) return field; return null; } private void add() throws Exception { Document document = read(add); Element element = document.getDocumentElement(); NodeList nodes = element.getElementsByTagName("module"); for (int i = 0; i < nodes.getLength(); i++) { Element module = (Element) nodes.item(i); String jarfile = XMLParser.getString(module, "module-jar"); int index = XMLParser.getInt(module, "module-index"); if (!new File(DataCrow.moduleDir + jarfile).exists()) continue; ModuleJar jar = new ModuleJar(jarfile); jar.load(); // get the fields to add XmlModule xmlModule = jar.getModule(); for (XmlField field : getFields(module, index)) { if (getField(field.getIndex(), xmlModule.getFields()) == null) { xmlModule.getFields().add(field); logger.info(DcResources.getText("msgUpgradedModuleXAdded", new String[]{xmlModule.getName(), field.getName()})); } } save(xmlModule, jarfile); } } private void alter() throws Exception { Document document = read(alter); Element element = document.getDocumentElement(); NodeList nodes = element.getElementsByTagName("module"); for (int i = 0; i < nodes.getLength(); i++) { Element module = (Element) nodes.item(i); String jarfile = XMLParser.getString(module, "module-jar"); int index = XMLParser.getInt(module, "module-index"); if (!new File(DataCrow.moduleDir + jarfile).exists()) continue; ModuleJar jar = new ModuleJar(jarfile); jar.load(); // get the fields to add XmlModule xmlModule = jar.getModule(); for (XmlField fieldNew : getFields(module, index)) { XmlField fieldOrg = getField(fieldNew.getIndex(), xmlModule.getFields()); if (fieldOrg == null) continue; fieldOrg.setColumn(fieldNew.getColumn()); fieldOrg.setEnabled(fieldNew.isEnabled()); fieldOrg.setFieldType(fieldNew.getFieldType()); fieldOrg.setIndex(fieldNew.getIndex()); fieldOrg.setMaximumLength(fieldNew.getMaximumLength()); fieldOrg.setModuleReference(fieldNew.getModuleReference()); fieldOrg.setName(fieldNew.getName()); fieldOrg.setOverwritable(fieldNew.isOverwritable()); fieldOrg.setReadonly(fieldNew.isReadonly()); fieldOrg.setSearchable(fieldNew.isSearchable()); fieldOrg.setUiOnly(fieldNew.isUiOnly()); fieldOrg.setValueType(fieldNew.getValueType()); logger.info(DcResources.getText("msgUpgradedModuleXAltered", new String[]{xmlModule.getName(), fieldOrg.getName()})); } save(xmlModule, jarfile); } } private void remove() throws Exception { Document document = read(remove); Element element = document.getDocumentElement(); NodeList nodes = element.getElementsByTagName("module"); for (int i = 0; i < nodes.getLength(); i++) { Element module = (Element) nodes.item(i); String jarfile = XMLParser.getString(module, "module-jar"); int index = XMLParser.getInt(module, "module-index"); if (!new File(DataCrow.moduleDir + jarfile).exists()) continue; ModuleJar jar = new ModuleJar(jarfile); jar.load(); // get the fields to add XmlModule xmlModule = jar.getModule(); for (XmlField field : getFields(module, index)) { XmlField fieldOrg = getField(field.getIndex(), xmlModule.getFields()); if (fieldOrg != null) { xmlModule.getFields().remove(fieldOrg); logger.info(DcResources.getText("msgUpgradedModuleXRemoved", new String[]{xmlModule.getName(), fieldOrg.getName()})); } } save(xmlModule, jarfile); } } private void removeDuplicates() { String[] modules = new File(DataCrow.moduleDir).list(); if (modules == null) return; for (String module : modules) { if (module.toLowerCase().endsWith(".jar")) { boolean containsUpper = false; for (char c : module.toCharArray()) { if (Character.isUpperCase(c)) { containsUpper = true; break; } } if (containsUpper) removeDuplicate(module.toLowerCase(), module); } } } private void removeDuplicate(String lowercase, String uppercase) { String[] modules = new File(DataCrow.moduleDir).list(); boolean foundLowercase = false; boolean foundUppercase = false; for (String module : modules) { if (module.equals(uppercase)) foundUppercase = true; else if (module.equals(lowercase)) foundLowercase = true; } if (foundLowercase && foundUppercase) new File(DataCrow.moduleDir + uppercase).delete(); } private Collection<XmlField> getFields(Element element, int module) throws Exception { Collection<XmlField> fields = new ArrayList<XmlField>(); NodeList nodes = element.getElementsByTagName("field"); for (int i = 0; i < nodes.getLength(); i++) { Element el = (Element) nodes.item(i); XmlModule xmlModule = new XmlModule(); xmlModule.setIndex(module); fields.add(new XmlField(xmlModule, el)); } return fields; } private Document read(File file) throws Exception { DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); DocumentBuilder db = dbf.newDocumentBuilder(); FileInputStream bis = new FileInputStream(file); Document doc = db.parse(bis); bis.close(); return doc; } }
package cloud.microservices.spring.boot.organizationservice; import cloud.microservices.spring.boot.organizationservice.utils.UserContextInterceptor; import com.netflix.hystrix.HystrixCommand; import com.netflix.hystrix.HystrixCommandGroupKey; import com.netflix.hystrix.HystrixCommandProperties; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2RestOperationsConfiguration; import org.springframework.cloud.client.circuitbreaker.Customizer; import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker; import org.springframework.cloud.client.discovery.EnableDiscoveryClient; import org.springframework.cloud.client.loadbalancer.LoadBalanced; import org.springframework.cloud.netflix.eureka.EnableEurekaClient; import org.springframework.cloud.netflix.hystrix.HystrixCircuitBreakerFactory; import org.springframework.cloud.openfeign.EnableFeignClients; import org.springframework.context.annotation.Bean; import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.security.oauth2.client.OAuth2ClientContext; import org.springframework.security.oauth2.client.OAuth2RestTemplate; import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails; import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.client.RestTemplate; import java.util.ArrayList; import java.util.Collections; import java.util.List; @EnableEurekaClient @EnableDiscoveryClient @EnableFeignClients @EnableCircuitBreaker @SpringBootApplication @EnableResourceServer public class OrganizationServiceApplication { public static void main(String[] args) { SpringApplication.run(OrganizationServiceApplication.class, args); } @Bean @LoadBalanced public RestTemplate getRestTemplate(){ RestTemplate restTemplate = new RestTemplate(); List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors(); if(interceptors == null) { restTemplate.setInterceptors(Collections.singletonList(new UserContextInterceptor())); } else { interceptors.add(new UserContextInterceptor()); restTemplate.setInterceptors(interceptors); } return restTemplate; } /*@Bean @LoadBalanced public OAuth2RestTemplate oAuth2RestTemplate(OAuth2ClientContext oAuth2ClientContext, OAuth2ProtectedResourceDetails details) { final OAuth2RestTemplate restTemplate = new OAuth2RestTemplate(details, oAuth2ClientContext); final List<ClientHttpRequestInterceptor> interceptors = restTemplate.getInterceptors(); if(interceptors == null) { restTemplate.setInterceptors(Collections.singletonList(new UserContextInterceptor())); } else { interceptors.add(new UserContextInterceptor()); restTemplate.setInterceptors(interceptors); } return restTemplate; }*/ /* @Bean public Customizer<HystrixCircuitBreakerFactory> defaultConfig() { return factory -> factory.configureDefault(id -> HystrixCommand.Setter .withGroupKey(HystrixCommandGroupKey.Factory.asKey(id)) .andCommandPropertiesDefaults(HystrixCommandProperties.Setter() .withExecutionTimeoutInMilliseconds(12000))); }*/ }
import java.util.Scanner; public class project { public static void main(String[] args) { int Toan, Ly, Hoa; String Ten; Scanner input = new Scanner(System.in); System.out.println("Nhap diem Toan: "); Toan = input.nextInt(); System.out.println("Nhap diem Ly: "); Ly = input.nextInt(); System.out.println("Nhap diem Hoa: "); Hoa = input.nextInt(); System.out.printf("NHap ten cua ban: "); Ten = input.next(); System.out.printf("Ten: %s Toan: %d Ly: %d Hoa: %d", Ten, Toan, Ly, Hoa); } }
package io.vertx.ext.swagger.router; import java.nio.charset.Charset; import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeoutException; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import com.fasterxml.jackson.databind.type.TypeFactory; import com.google.common.escape.Escaper; import com.google.common.net.UrlEscapers; import io.swagger.models.Swagger; import io.swagger.parser.SwaggerParser; import io.vertx.core.Vertx; import io.vertx.core.buffer.Buffer; import io.vertx.core.eventbus.EventBus; import io.vertx.core.file.FileSystem; import io.vertx.core.http.HttpClient; import io.vertx.core.http.HttpClientOptions; import io.vertx.core.http.HttpClientRequest; import io.vertx.core.http.HttpHeaders; import io.vertx.core.json.Json; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.ext.swagger.router.model.User; import io.vertx.ext.unit.Async; import io.vertx.ext.unit.TestContext; import io.vertx.ext.unit.junit.VertxUnitRunner; import io.vertx.ext.web.Router; @RunWith(VertxUnitRunner.class) public class BuildRouterTest { private static final int TEST_PORT = 9292; private static final String TEST_HOST = "localhost"; private static final String TEST_FILENAME = "testUpload.json"; private static Vertx vertx; private static EventBus eventBus; private static HttpClient httpClient; @BeforeClass public static void beforClass(TestContext context) { Async before = context.async(); vertx = Vertx.vertx(); eventBus = vertx.eventBus(); // init Router FileSystem vertxFileSystem = vertx.fileSystem(); vertxFileSystem.readFile("swagger.json", readFile -> { if (readFile.succeeded()) { Swagger swagger = new SwaggerParser().parse(readFile.result().toString(Charset.forName("utf-8"))); Router swaggerRouter = SwaggerRouter.swaggerRouter(Router.router(vertx), swagger, eventBus); vertx.createHttpServer().requestHandler(swaggerRouter::accept).listen(TEST_PORT, TEST_HOST, listen -> { if (listen.succeeded()) { before.complete(); } else { context.fail(listen.cause()); } }); } else { context.fail(readFile.cause()); } }); // init consumers eventBus.<JsonObject> consumer("GET_store_inventory").handler(message -> { message.reply(new JsonObject().put("sold", 2L).encode()); }); eventBus.<JsonObject> consumer("test.dummy").handler(message -> { context.fail("should not be called"); }); eventBus.<JsonObject> consumer("GET_pet_petId").handler(message -> { String petId = message.body().getString("petId"); message.reply(new JsonObject().put("petId_received", petId).encode()); }); eventBus.<JsonObject> consumer("POST_pet_petId").handler(message -> { String petId = message.body().getString("petId"); String name = message.body().getString("name"); String status = message.body().getString("status"); message.reply(new JsonObject() .put("petId_received", petId) .put("name_received", name) .put("status_received", status).encode() ); }); eventBus.<JsonObject> consumer("DELETE_pet_petId").handler(message -> { String petId = message.body().getString("petId"); String apiKey = message.body().getString("api_key"); message.reply(new JsonObject() .put("petId_received", petId) .put("header_received", apiKey).encode() ); }); eventBus.<JsonObject> consumer("POST_pet_petId_uploadImage").handler(message -> { JsonObject result = new JsonObject(); String petId = message.body().getString("petId"); String additionalMetadata = message.body().getString("additionalMetadata"); String fileName = message.body().getString("file"); vertxFileSystem.readFile(fileName, readFile -> { if(readFile.succeeded()) { result.put("fileContent_received", readFile.result().toString()); result.put("petId_received", petId); result.put("additionalMetadata_received", additionalMetadata); message.reply(result.encode()); } else { context.fail(readFile.cause()); } }); }); eventBus.<JsonObject> consumer("GET_user_login").handler(message -> { String username = message.body().getString("username"); message.reply(new JsonObject().put("username_received", username).encode()); }); eventBus.<JsonObject> consumer("GET_pet_findByStatus").handler(message -> { JsonArray status = message.body().getJsonArray("status"); JsonObject result = new JsonObject(); for (int i = 0; i < status.size(); i++) { result.put("element " + i, status.getString(i)); } message.reply(result.encode()); }); eventBus.<JsonObject> consumer("POST_user_createWithArray").handler(message -> { try { List<User> users = Json.mapper.readValue(message.body().getString("body"), TypeFactory.defaultInstance().constructCollectionType(List.class, User.class)); JsonObject result = new JsonObject(); for (int i = 0; i < users.size(); i++) { result.put("user " + (i + 1), users.get(i).toString()); } message.reply(result.encode()); } catch (Exception e) { message.fail(500, e.getLocalizedMessage()); } }); eventBus.<JsonObject> consumer("GET_user_logout").handler(message -> { message.reply(null); }); // init http Server HttpClientOptions options = new HttpClientOptions(); options.setDefaultPort(TEST_PORT); httpClient = Vertx.vertx().createHttpClient(); } @Test(timeout = 2000) public void testResourceNotfound(TestContext context) { Async async = context.async(); httpClient.getNow(TEST_PORT, TEST_HOST, "/dummy", response -> { context.assertEquals(response.statusCode(), 404); async.complete(); }); } @Test(timeout = 2000) public void testMessageIsConsume(TestContext context) { Async async = context.async(); httpClient.getNow(TEST_PORT, TEST_HOST, "/store/inventory", response -> { response.bodyHandler(body -> { JsonObject jsonBody = new JsonObject(body.toString(Charset.forName("utf-8"))); context.assertTrue(jsonBody.containsKey("sold")); context.assertEquals(2L, jsonBody.getLong("sold")); async.complete(); }); }); } @Test(timeout = 2000, expected = TimeoutException.class) public void testMessageIsNotConsume(TestContext context) { Async async = context.async(); httpClient.getNow(TEST_PORT, TEST_HOST, "/user/logout", response -> response.exceptionHandler(err -> { async.complete(); })); } @Test(timeout = 2000) public void testWithPathParameter(TestContext context) { Async async = context.async(); httpClient.getNow(TEST_PORT, TEST_HOST, "/pet/5", response -> { response.bodyHandler(body -> { JsonObject jsonBody = new JsonObject(body.toString(Charset.forName("utf-8"))); context.assertTrue(jsonBody.containsKey("petId_received")); context.assertEquals("5", jsonBody.getString("petId_received")); async.complete(); }); }); } @Test(timeout = 2000) public void testWithQuerySimpleParameter(TestContext context) { Async async = context.async(); httpClient.getNow(TEST_PORT, TEST_HOST, "/user/login?username=myUser&password=mySecret", response -> { response.bodyHandler(body -> { JsonObject jsonBody = new JsonObject(body.toString(Charset.forName("utf-8"))); context.assertTrue(jsonBody.containsKey("username_received")); context.assertEquals("myUser", jsonBody.getString("username_received")); async.complete(); }); }); } @Test(timeout = 2000) public void testWithQueryArrayParameter(TestContext context) { Async async = context.async(); httpClient.getNow(TEST_PORT, TEST_HOST, "/pet/findByStatus?status=available", response -> { response.bodyHandler(body -> { JsonObject jsonBody = new JsonObject(body.toString(Charset.forName("utf-8"))); context.assertTrue(jsonBody.containsKey("element 0")); context.assertEquals("available", jsonBody.getString("element 0")); async.complete(); }); }); } @Test(timeout = 2000) public void testWithQueryManyArrayParameter(TestContext context) { Async async = context.async(); httpClient.getNow(TEST_PORT, TEST_HOST, "/pet/findByStatus?status=available&status=pending", response -> { response.bodyHandler(body -> { JsonObject jsonBody = new JsonObject(body.toString(Charset.forName("utf-8"))); context.assertTrue(jsonBody.containsKey("element 0")); context.assertEquals("available", jsonBody.getString("element 0")); context.assertTrue(jsonBody.containsKey("element 1")); context.assertEquals("pending", jsonBody.getString("element 1")); async.complete(); }); }); } @Test(timeout = 2000) public void testWithBodyParameterNoBody(TestContext context) { Async async = context.async(); HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/user/createWithArray"); req.handler(response -> { context.assertEquals(response.statusCode(), 400); async.complete(); }).end(); } @Test(timeout = 2000) public void testWithBodyParameter(TestContext context) { Async async = context.async(); User user1 = new User(1L, "user 1", "first 1", "last 1", "email 1", "secret 1", "phone 1", 1); User user2 = new User(2L, "user 2", "first 2", "last 2", "email 2", "secret 2", "phone 2", 2); JsonArray users = new JsonArray(Arrays.asList(user1, user2)); HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/user/createWithArray"); req.setChunked(true); req.handler(response -> response.bodyHandler(result -> { JsonObject jsonBody = new JsonObject(result.toString(Charset.forName("utf-8"))); context.assertTrue(jsonBody.containsKey("user 1")); context.assertEquals(user1.toString(), jsonBody.getString("user 1")); context.assertTrue(jsonBody.containsKey("user 2")); context.assertEquals(user2.toString(), jsonBody.getString("user 2")); async.complete(); })).end(users.encode()); } @Test(timeout = 2000) public void testNullBodyResponse(TestContext context) { Async async = context.async(); httpClient.getNow(TEST_PORT, TEST_HOST, "/user/logout", response -> { context.assertEquals(response.statusCode(), 200); async.complete(); }); } @Test(timeout = 2000) public void testWithFormParameterMultiPart(TestContext context) { Async async = context.async(); HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/pet/1/uploadImage"); req.setChunked(false); req.handler(response -> response.bodyHandler(result -> { JsonObject jsonBody = new JsonObject(result.toString(Charset.forName("utf-8"))); context.assertTrue(jsonBody.containsKey("petId_received")); context.assertEquals("1", jsonBody.getString("petId_received")); context.assertTrue(jsonBody.containsKey("additionalMetadata_received")); context.assertEquals("Exceptionnal file !!", jsonBody.getString("additionalMetadata_received")); context.assertTrue(jsonBody.containsKey("fileContent_received")); context.assertEquals("This is a test file.", jsonBody.getString("fileContent_received")); async.complete(); })); // Construct multipart data req.putHeader(HttpHeaders.CONTENT_TYPE, "multipart/form-data; boundary=MyBoundary"); Buffer buffer = Buffer.factory.buffer(); buffer.appendString("\r\n"); buffer.appendString("--MyBoundary\r\n"); buffer.appendString("Content-Disposition: form-data; name=\"additionalMetadata\" \r\n"); buffer.appendString("\r\n"); buffer.appendString("Exceptionnal file !!"); FileSystem vertxFileSystem = vertx.fileSystem(); vertxFileSystem.readFile(TEST_FILENAME, readFile -> { if (readFile.succeeded()) { buffer.appendString("\r\n"); buffer.appendString("--MyBoundary\r\n"); buffer.appendString("Content-Disposition: form-data; name=\"file\"; filename=\""+TEST_FILENAME+"\"\r\n"); buffer.appendString("Content-Type: text/plain\r\n"); buffer.appendString("\r\n"); buffer.appendString(readFile.result().toString(Charset.forName("utf-8"))); buffer.appendString("\r\n"); buffer.appendString("--MyBoundary--"); req.end(buffer); } else { context.fail(readFile.cause()); } }); } @Test(timeout = 2000) public void testWithFormParameterUrlEncoded(TestContext context) { Async async = context.async(); HttpClientRequest req = httpClient.post(TEST_PORT, TEST_HOST, "/pet/1"); req.handler(response -> response.bodyHandler(result -> { JsonObject jsonBody = new JsonObject(result.toString(Charset.forName("utf-8"))); context.assertTrue(jsonBody.containsKey("petId_received")); context.assertEquals("1", jsonBody.getString("petId_received")); context.assertTrue(jsonBody.containsKey("name_received")); context.assertEquals("MyName", jsonBody.getString("name_received")); context.assertTrue(jsonBody.containsKey("status_received")); context.assertEquals("MyStatus", jsonBody.getString("status_received")); async.complete(); })); // Construct form Escaper esc = UrlEscapers.urlFormParameterEscaper(); StringBuffer payload = new StringBuffer() .append("name=") .append(esc.escape("MyName")) .append("&status=") .append(esc.escape("MyStatus")); req.putHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded"); req.end(payload.toString()); } @Test(timeout = 2000) public void testWithHeaderParameter(TestContext context) { Async async = context.async(); HttpClientRequest req = httpClient.delete(TEST_PORT, TEST_HOST, "/pet/1"); req.putHeader("api_key", "MyAPIKey"); req.handler(response -> response.bodyHandler(result -> { JsonObject jsonBody = new JsonObject(result.toString(Charset.forName("utf-8"))); context.assertTrue(jsonBody.containsKey("petId_received")); context.assertEquals("1", jsonBody.getString("petId_received")); context.assertTrue(jsonBody.containsKey("header_received")); context.assertEquals("MyAPIKey", jsonBody.getString("header_received")); async.complete(); })); req.end(); } }
package com.bruce.flyweight.jdkdemo; public class FlyWeight { public static void main(String[] args) { Integer x=Integer.valueOf(3); Integer y=new Integer(3);; Integer z=new Integer(3); Integer a=Integer.valueOf(3); System.out.println( x==y); System.out.println( y==z); System.out.println( x==a); } }
import java.util.Iterator; import java.io.*; import java.net.*; import java.util.*; //Mention use of JSON Library //Mention E-mail libtrary / api //filewriter + e-mail to store digital receipt + send it to client //add both seminar case and city case public class MainMenu { //static Room[][] hotelsTable = new Room[100000][2]; static int[][] hotelsTableIDs = new int[100000][2]; static int counterOfFindings = 0; static int magicCheck = 0; static Map<Integer, Room> hotelMap = new HashMap<>(); static Map<Integer, String> amenitiesMap = new HashMap<>(); private static String readUrl(String urlString) throws Exception { BufferedReader reader = null; try { URL url = new URL(urlString); reader = new BufferedReader(new InputStreamReader(url.openStream())); StringBuffer buffer = new StringBuffer(); int read; char[] chars = new char[1024]; while ((read = reader.read(chars)) != -1) buffer.append(chars, 0, read); return buffer.toString(); } finally { if (reader != null) reader.close(); } } public static void createAmenitiesMap() { try { String urlString = "http://engine.hotellook.com/api/v2/static/amenities/en.json?token=6251c90d5bc52c88b60a38bd84373513"; String data = readUrl(urlString); JSONArray amenities = new JSONArray(data); for(int i=0;i<amenities.length();i++) { JSONObject tempObject = amenities.getJSONObject(i); int id = Integer.parseInt(tempObject.getString("id")); String name = tempObject.getString("name"); amenitiesMap.put(id, name); } /*System.out.println("AMENITIES:"); //debug System.out.print(amenitiesMap); */ } catch(Exception e) { System.out.println("Ameinities Not Found"); } } public static Room readHotelSelectionsData(JSONObject jsonObj) { //instead of creating object with blank attributes for null values, could better use inheritance int hotelID = jsonObj.getInt("hotel_id"); Double distanceFromCityCenter = jsonObj.getDouble("distance"); String nameOfHotel = jsonObj.getString("name"); int stars = jsonObj.getInt("stars"); int visitorRating = jsonObj.getInt("rating"); String summary = ""; if(!jsonObj.isNull("ty_summary")) { //mention how this was an issue summary = jsonObj.getString("ty_summary"); } String propertyType = jsonObj.getString("property_type"); JSONArray hotelTypes = jsonObj.getJSONArray("hotel_type"); String[] hotelTypesArray = new String[hotelTypes.length()]; for(int i=0; i<hotelTypes.length(); i++) { hotelTypesArray[i] = hotelTypes.getString(i); } int totalPrice = -1; int numberOfNights = -1; int pricePerNight = -1; if(!jsonObj.isNull("last_price_info")) { JSONObject pricingInfo = jsonObj.getJSONObject("last_price_info"); totalPrice = pricingInfo.getInt("price"); numberOfNights = pricingInfo.getInt("nights"); pricePerNight = pricingInfo.getInt("price_pn"); } String[] facilities = new String[100]; //change later, use dynamic list if(jsonObj.get("has_wifi") instanceof Boolean){ //as it will be list, we do not care about other case + mention hardship of boolean/int if (jsonObj.getBoolean("has_wifi")) { facilities[0] = "Wifi"; } } return (new Room(hotelID, distanceFromCityCenter, nameOfHotel, stars, visitorRating, summary, propertyType, hotelTypesArray, new PriceInformation(totalPrice, numberOfNights, pricePerNight), facilities, null)); } public static void getHotelSelectionsData(BasicPersonInfo browsingUser) { try { String urlString = ("http://yasen.hotellook.com/tp/public/widget_location_dump.json?currency=" + browsingUser.getCurrency() + "&language=" + browsingUser.getLanguage() + "&limit=" + 10000 + "&id=" + browsingUser.getLocation() + "&type=available_selections.json&check_in=" + browsingUser.getCheckInDate() + "&check_out=" + browsingUser.getCheckOutDate() + "&token=6251c90d5bc52c88b60a38bd84373513"); String data = readUrl(urlString); JSONObject object = new JSONObject(data); JSONArray hotels = object.getJSONArray("available_selections.json"); //Read All Data and Add Rooms to First Column of Table //int counterOfFindings = 0; //used for debugging + to keep track of existing indexes in array counterOfFindings = 0; for(int i=0; i<hotels.length(); i++) { JSONObject jsonObj = hotels.getJSONObject(i); //hotelsTable[i][0] = readHotelSelectionsData(jsonObj); Room tempRoom = readHotelSelectionsData(jsonObj); hotelsTableIDs[i][0] = tempRoom.getHotelID(); hotelMap.put(tempRoom.getHotelID(), tempRoom); counterOfFindings = i; } } catch(Exception e) { System.out.println("Unfortunately we were not able to meet your request. Please try again later."); } } public static void readHotelListData(JSONObject jsonObj) { int hotelID = jsonObj.getInt("id"); if(hotelMap.containsKey(hotelID)) { JSONArray shortFacilitiesJSON = jsonObj.getJSONArray("shortFacilities"); String[] shortFacilitiesArray = (hotelMap.get(hotelID)).getFacilitiesShort(); for (int i=0;i<shortFacilitiesJSON.length();i++) { //+1 is used because the 0 position is reserved for wifi from previous request shortFacilitiesArray[i+1] = shortFacilitiesJSON.getString(i); } (hotelMap.get(hotelID)).setFacilitiesShort(shortFacilitiesArray); Node rootNode = new Node("Root"); Node listNode = rootNode; //TODO: Create hasMap to turn AmenitiesID to String, use additional request JSONArray facilitiesExtendedListJSON = jsonObj.getJSONArray("facilities"); for (int i=0;i<facilitiesExtendedListJSON.length();i++) { //+1 is used because the 0 position is reserved for wifi from previous request int amenityCode = facilitiesExtendedListJSON.getInt(i); listNode = listNode.next = new Node(amenitiesMap.get(amenityCode)); } //rootNode = rootNode.next; (hotelMap.get(hotelID)).setFacilitiesExtendedList(rootNode); magicCheck += 1; } } public static void getHotelListData(BasicPersonInfo browsingUser) { try { String urlString = ("http://engine.hotellook.com/api/v2/static/hotels.json?locationId=" + browsingUser.getLocation() + "&token=6251c90d5bc52c88b60a38bd84373513"); String data = readUrl(urlString); JSONObject object = new JSONObject(data); JSONArray hotels = object.getJSONArray("hotels"); //location, address, photos -> add to class for(int i=0; i<hotels.length(); i++) { JSONObject jsonObj = hotels.getJSONObject(i); readHotelListData(jsonObj); } } catch(Exception e) { System.out.println("Unfortunately we were not able to meet your request. Please try again later."); } } public static void main(String[] args) { System.out.println("Please select mode: 1. City-Based Mode\n2. Seminar-Based Mode"); System.out.println("Please Select Location: \n1. Athens \n2. Thessaloniki \n3. Berlin"); //maybe can allow to insert name, or display broader list Scanner scanner = new Scanner(System.in); System.out.println("Please enter your Check-In-Date (yyyy-mm-dd) : "); String checkInDate = scanner.next(); System.out.println("Please enter your Check-Out-Date (yyyy-mm-dd) : "); String checkOutDate = scanner.next(); String language = "en"; String currency = "eur"; String limit = "1000"; String locationID = "23721"; BasicPersonInfo browsingUser = new BasicPersonInfo(checkInDate, checkOutDate, locationID, currency, language); //Must ask for: check-in, check-out, Currency, language. //Can also ask for limit //Personalized limit //String data = readUrl("http://yasen.hotellook.com/tp/public/widget_location_dump.json?currency=eur&language=en&limit=1000&id=23721&type=available_selections.json&check_in=2018-02-02&check_out=2018-02-17&token=6251c90d5bc52c88b60a38bd84373513"); //Must change link according to info added createAmenitiesMap(); getHotelSelectionsData(browsingUser); getHotelListData(browsingUser); System.out.println(counterOfFindings); System.out.println(magicCheck); for (int i = 0; i<=counterOfFindings; i++) { ////System.out.println(hotelsTable[i][0].printAll() + "\n"); Room tempRoom = hotelMap.get(hotelsTableIDs[i][0]); System.out.println(tempRoom.printAll() + "\n"); } //Different Display Methods -> stock , alphabetical, populatiry, ratings, price -> all of them ascending/descending (can possible use opposite order of for) //Filtered Mode //Booking Process (Can write to file info from different hotels and then read it to send info to client) -> Send email to client } }
/** * The MIT License * Copyright (c) 2015 Alexander Sova (bird@codeminders.com) * <p/> * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * <p/> * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * <p/> * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.codeminders.socketio.server.transport.jetty; import com.codeminders.socketio.protocol.*; import com.codeminders.socketio.server.*; import com.codeminders.socketio.common.ConnectionState; import com.codeminders.socketio.common.DisconnectReason; import com.codeminders.socketio.common.SocketIOException; import com.codeminders.socketio.server.transport.AbstractTransportConnection; import com.google.common.io.ByteStreams; import org.eclipse.jetty.websocket.api.StatusCode; import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose; import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect; import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage; import org.eclipse.jetty.websocket.api.annotations.WebSocket; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.util.Collection; import java.util.logging.Level; import java.util.logging.Logger; /** * @author Alexander Sova (bird@codeminders.com) */ @WebSocket public final class JettyWebSocketTransportConnection extends AbstractTransportConnection { private static final Logger LOGGER = Logger.getLogger(JettyWebSocketTransportConnection.class.getName()); private org.eclipse.jetty.websocket.api.Session remote_endpoint; public JettyWebSocketTransportConnection(Transport transport) { super(transport); } @Override protected void init() { getSession().setTimeout(getConfig().getTimeout(Config.DEFAULT_PING_TIMEOUT)); if (LOGGER.isLoggable(Level.FINE)) LOGGER.fine(getConfig().getNamespace() + " WebSocket configuration:" + " timeout=" + getSession().getTimeout()); } @OnWebSocketConnect public void onWebSocketConnect(org.eclipse.jetty.websocket.api.Session session) { remote_endpoint = session; if(getSession().getConnectionState() == ConnectionState.CONNECTING) { try { send(EngineIOProtocol.createHandshakePacket(getSession().getSessionId(), new String[]{}, getConfig().getPingInterval(Config.DEFAULT_PING_INTERVAL), getConfig().getTimeout(Config.DEFAULT_PING_TIMEOUT))); getSession().onConnect(this); } catch (SocketIOException e) { LOGGER.log(Level.SEVERE, "Cannot connect", e); getSession().setDisconnectReason(DisconnectReason.CONNECT_FAILED); abort(); } } } @OnWebSocketClose public void onWebSocketClose(int closeCode, String message) { if(LOGGER.isLoggable(Level.FINE)) LOGGER.log(Level.FINE, "Session[" + getSession().getSessionId() + "]:" + " websocket closed. Close code: " + closeCode + " message: " + message); //If close is unexpected then try to guess the reason based on closeCode, otherwise the reason is already set if(getSession().getConnectionState() != ConnectionState.CLOSING) getSession().setDisconnectReason(fromCloseCode(closeCode)); getSession().setDisconnectMessage(message); getSession().onShutdown(); } @OnWebSocketMessage public void onWebSocketText(String text) { if (LOGGER.isLoggable(Level.FINE)) LOGGER.fine("Session[" + getSession().getSessionId() + "]: text received: " + text); getSession().resetTimeout(); try { getSession().onPacket(EngineIOProtocol.decode(text), this); } catch (SocketIOProtocolException e) { if(LOGGER.isLoggable(Level.WARNING)) LOGGER.log(Level.WARNING, "Invalid packet received", e); } } @OnWebSocketMessage public void onWebSocketBinary(InputStream is) { if (LOGGER.isLoggable(Level.FINE)) LOGGER.fine("Session[" + getSession().getSessionId() + "]: binary received"); getSession().resetTimeout(); try { getSession().onPacket(EngineIOProtocol.decode(is), this); } catch (SocketIOProtocolException e) { if(LOGGER.isLoggable(Level.WARNING)) LOGGER.log(Level.WARNING, "Problem processing binary received", e); } } @Override public void handle(HttpServletRequest request, HttpServletResponse response) throws IOException { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Unexpected request on upgraded WebSocket connection"); } @Override public void abort() { getSession().clearTimeout(); if (remote_endpoint != null) { disconnectEndpoint(); remote_endpoint = null; } } @Override public void send(EngineIOPacket packet) throws SocketIOException { sendString(EngineIOProtocol.encode(packet)); } @Override public void send(SocketIOPacket packet) throws SocketIOException { send(EngineIOProtocol.createMessagePacket(packet.encode())); if(packet instanceof BinaryPacket) { Collection<InputStream> attachments = ((BinaryPacket) packet).getAttachments(); for (InputStream is : attachments) { ByteArrayOutputStream os = new ByteArrayOutputStream(); try { os.write(EngineIOPacket.Type.MESSAGE.value()); ByteStreams.copy(is, os); } catch (IOException e) { if(LOGGER.isLoggable(Level.WARNING)) LOGGER.log(Level.SEVERE, "Cannot load binary object to send it to the socket", e); } sendBinary(os.toByteArray()); } } } protected void sendString(String data) throws SocketIOException { if (!remote_endpoint.isOpen()) throw new SocketIOClosedException(); if (LOGGER.isLoggable(Level.FINE)) LOGGER.log(Level.FINE, "Session[" + getSession().getSessionId() + "]: send text: " + data); try { remote_endpoint.getRemote().sendString(data); } catch (IOException e) { disconnectEndpoint(); throw new SocketIOException(e); } } //TODO: implement streaming. right now it is all in memory. //TODO: read and send in chunks using sendPartialBytes() protected void sendBinary(byte[] data) throws SocketIOException { if (!remote_endpoint.isOpen()) throw new SocketIOClosedException(); if (LOGGER.isLoggable(Level.FINE)) LOGGER.log(Level.FINE, "Session[" + getSession().getSessionId() + "]: send binary"); try { remote_endpoint.getRemote().sendBytes(ByteBuffer.wrap(data)); } catch (IOException e) { disconnectEndpoint(); throw new SocketIOException(e); } } private void disconnectEndpoint() { try { remote_endpoint.disconnect(); } catch (IOException ex) { // ignore } } private DisconnectReason fromCloseCode(int code) { switch (code) { case StatusCode.SHUTDOWN: return DisconnectReason.CLIENT_GONE; default: return DisconnectReason.ERROR; } } }
package ua.od.atomspace; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String[] args) { String text = "Hello, guys! I send you my email joe@gmail.com so we can" + "keep in touch. Thanks, Joe! That's cool! I am sending you" + "my address: tim@yandex.ru. Let's stay in touch..."; Pattern email = Pattern.compile("(\\w)+@(gmail|yandex)\\.(com|ru)");// конструктор паттерна приватный, поэтому получаем объект // этого класса с помощью статического метода, в который передаем регулярное выражение Matcher matcher = email.matcher(text);// получаем объект класса мэтчер с помощью метода класса паттерн, в который передаем строку для поиска while (matcher.find()){// пока находим по регулярному выражению System.out.println(matcher.group());// если метод .group() без аргументов, то получаем всю строку, подходящую по регулярному выражению } while (matcher.find()){ System.out.println(matcher.group(1));// если указываем первую группу, то получаем только то с регулярного выражения, что соответсует группе (\w) } while (matcher.find()){ System.out.println(matcher.group(2));// если указываем вторую группу, то получаем только то с регулярного выражения, что соответсует группе (gmail|yandex) } while (matcher.find()){ System.out.println(matcher.group(3));// если указываем третью группу, то получаем только то с регулярного выражения, что соответсует группе (com|ru) } } }
package testing; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; class register_class_Test extends register_test_class { @Test // testing class not null public void testConstructor() { register_test_class rtc = new register_test_class(); assertNotNull(rtc); } @Test // Register inserting test pass public void testGetters() { register_test_class rt = new register_test_class("karma","karmagrg","karma123",987, "ktm"); String expected = "karmagrg"; String actual = rt.getuserName(); assertEquals(expected,actual); } @Test // Register inserting test fail public void testGetters1() { register_test_class rt = new register_test_class("karma","karmagrg","karma123",987, "ktm"); String expected = "nepal"; String actual = rt.getaddress(); assertEquals(expected,actual); } }
package com.company; import java.util.ArrayList; public class TestGrade { public static void main(String[] args){ TestGrade test = new TestGrade(); if(test.testGetValue() == true) System.out.println("testGradeValue : correct"); else System.out.println("testGradeValue : incorrect"); if(test.testToString() == true) System.out.println("testToString : correct"); else System.out.println("testToString : incorrect"); if(test.testAverageGrade() == true) System.out.println("testAverageGrade : correct"); else System.out.println("testAverageGrade : incorrect"); } public boolean testGetValue(){ Grade grade = new Grade(12.5); double val = grade.getValue(); if(val == 12.5) return true; else return false; } public boolean testToString(){ Grade grade = new Grade(13.7); String gradeString = grade.toString(); if(gradeString.equals("13.7/20")) return true; else return false; } public boolean testAverageGrade(){ ArrayList<Grade> list = new ArrayList<Grade>(); list.add(new Grade(10)); list.add(new Grade(8)); list.add(new Grade(12)); list.add(new Grade(20)); list.add(new Grade(6)); Grade average = Grade.averageGrade(list); if(average.getValue() == 11.2) return true; else return false; } }
package com.gr.cinema.domain; public class BookingConfirmation { String bookingConfNum; Double amount; String showTime; String cinemaHallNumber; public String getBookingConfNum() { return bookingConfNum; } public void setBookingConfNum(String bookingConfNum) { this.bookingConfNum = bookingConfNum; } public Double getAmount() { return amount; } public void setAmount(Double amount) { this.amount = amount; } public String getShowTime() { return showTime; } public void setShowTime(String showTime) { this.showTime = showTime; } public String getCinemaHallNumber() { return cinemaHallNumber; } public void setCinemaHallNumber(String cinemaHallNumber) { this.cinemaHallNumber = cinemaHallNumber; } }
import java.io.*; import java.util.*; class baek__9935 { public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String s = br.readLine(); String ex = br.readLine(); Stack<Integer> st1 = new Stack<>(); Stack<Integer> st2 = new Stack<>(); boolean[] check = new boolean[s.length()]; Arrays.fill(check, true); for (int i = 0; i < s.length(); i++) { if (s.charAt(i) == ex.charAt(0)) { st1.add(0); st2.add(i); if (st1.peek() == ex.length() - 1) { for (int j = 0; j < ex.length(); j++) { st1.pop(); check[st2.pop()] = false; } } } else { if (st1.isEmpty()) continue; if (s.charAt(i) == ex.charAt(st1.peek() + 1)) { st1.add(st1.peek() + 1); st2.add(i); if (st1.peek() == ex.length() - 1) { for (int j = 0; j < ex.length(); j++) { st1.pop(); check[st2.pop()] = false; } } } else { while (!st1.isEmpty()) { st1.pop(); st2.pop(); } } } } StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { if (check[i]) { sb.append(s.charAt(i)); } } System.out.print(sb.toString().length() == 0 ? "FRULA" : sb); } }
package kz.greetgo.gbatis.struct.exceptions; import kz.greetgo.gbatis.struct.ParsedType; public class DuplicateType extends SyntaxException { public final ParsedType currentType; public final ParsedType alreadyExistsType; public DuplicateType(ParsedType currentType, ParsedType alreadyExistsType) { super(currentType.name + ", currentTypePlace = " + currentType.placement() + ", alreadyExistsTypePlace = " + alreadyExistsType.placement()); this.currentType = currentType; this.alreadyExistsType = alreadyExistsType; } }
package br.com.huegroup.salao.utils; import java.io.IOException; import java.util.HashMap; import java.util.Map; import java.util.Properties; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public class JPAManager { private final EntityManagerFactory emf; private boolean teste; public JPAManager() { Properties properties = new Properties(); try { properties.load(JPAManager.class.getClassLoader().getResourceAsStream("properties/flyway.properties")); } catch (IOException e) { e.printStackTrace(); } Map<String, String> map = new HashMap<String, String>(); map.put("javax.persistence.jdbc.url", "jdbc:mysql://localhost:3306/" + properties.getProperty("schema")); emf = Persistence.createEntityManagerFactory("salao-bootstrap", map); } public JPAManager(boolean teste) { this(); this.teste = teste; } public EntityManager getEntityManager() { return emf.createEntityManager(); } public void close() { emf.close(); } public void beginTransaction(EntityManager manager) { manager.getTransaction().begin(); } public void commitTransaction(EntityManager manager) { if (teste) manager.getTransaction().rollback(); else manager.getTransaction().commit(); } }
package group29; import genius.core.Bid; import genius.core.issue.Issue; import genius.core.issue.IssueDiscrete; import genius.core.uncertainty.UserModel; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; public class IaMap extends HashMap<Issue, List<ValueNew>> { public int countBidNumber = 0; // t: total number of prior bids HashMap<Issue, Double> weightList = new HashMap<>(); // store the weight of each issue public IaMap(UserModel userModel){ super(); // inherit HashMap for(Issue issue:userModel.getDomain().getIssues()){ IssueDiscrete values = (IssueDiscrete) issue; // turn issue to IssueDiscrete type List<ValueNew> list = new ArrayList<>(); for(int i = 0; i < values.getNumberOfValues(); i ++){ ValueNew temp = new ValueNew(values.getValue(i)); list.add(temp); } this.put(issue, list); // put <issue, list> } } public void JonnyBlack(Bid lastOffer){ this.countBidNumber += 1; // t: total number of prior bids for(Issue issue : lastOffer.getIssues()){ int num = issue.getNumber(); // This is issue num for(ValueNew valueNew : this.get(issue)){ if(valueNew.valueName.toString().equals(lastOffer.getValue(num).toString())){ // add up to the option for the lastOffer valueNew.count += 1; } IssueDiscrete issueDiscrete = (IssueDiscrete) issue; // 其实这个不需要每一次都赋值,第一次赋值完就不会改变了 valueNew.totalOfOptions = issueDiscrete.getNumberOfValues(); // renew countBidNumber in each valueNew valueNew.countBidNumber = this.countBidNumber; } // sort in a descending order Collections.sort(this.get(issue), this.get(issue).get(0)); // renew rank in each valueNew for(ValueNew valueNew : this.get(issue)){ // rank = index + 1 valueNew.rank = this.get(issue).indexOf(valueNew) + 1; } } // calculate the weights for every issue below for(Issue issue : lastOffer.getIssues()){ for(ValueNew valueNew : this.get(issue)){ // calculate the unnormalized weights valueNew.compute(); } } for(Issue issue : lastOffer.getIssues()){ double totalWeight = 0.0f; // store the total unnormalized weight double maxWeight = 0.0f; // store the max weight in the issue for(ValueNew valueNew : this.get(issue)){ totalWeight += valueNew.weightUnnormalized; if (valueNew.rank == 1) { maxWeight = valueNew.weightUnnormalized; } } double issueWeight = maxWeight / totalWeight; this.weightList.put(issue, issueWeight); } // calculate the utility double temp = JBpredict(lastOffer); } public double JBpredict(Bid lastOffer){ double utility = 0.0f; //先进行初始化 for(Issue issue : lastOffer.getIssues()){ int num = issue.getNumber(); for(ValueNew valueNew : this.get(issue)){ if(valueNew.valueName.toString().equals(lastOffer.getValue(num).toString())) { utility += weightList.get(issue) * valueNew.calculatedValue; break; } } } // System.out.println(countBidNumber + "-> Group29: The utility of opponent is " + utility); return utility; } }
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.context.annotation; import java.util.List; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.core.annotation.Order; import static org.assertj.core.api.Assertions.assertThat; /** * @author Stephane Nicoll */ class Spr11310Tests { @Test void orderedList() { ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(Config.class); StringHolder holder = context.getBean(StringHolder.class); assertThat(holder.itemsList).containsExactly("second", "first", "unknownOrder"); context.close(); } @Test void orderedArray() { ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(Config.class); StringHolder holder = context.getBean(StringHolder.class); assertThat(holder.itemsArray).containsExactly("second", "first", "unknownOrder"); context.close(); } @Configuration static class Config { @Bean @Order(50) public String first() { return "first"; } @Bean public String unknownOrder() { return "unknownOrder"; } @Bean @Order(5) public String second() { return "second"; } @Bean public StringHolder stringHolder() { return new StringHolder(); } } private static class StringHolder { @Autowired private List<String> itemsList; @Autowired private String[] itemsArray; } }
package algorithm.annealing.temperature; public class ExponentialSchedule implements TemperatureSchedule { private static final double DEFAULT_INIT_TEMP = 10000; private static final double DEFAULT_COOLING_RATE = 0.97; private static final double COOL_THRESHOLD = 1; private double initialTemperature = DEFAULT_INIT_TEMP; private double currentTemperature = DEFAULT_INIT_TEMP; private double coolingRate = DEFAULT_COOLING_RATE; public ExponentialSchedule() { // Empty constructor } public ExponentialSchedule(double initialTemperature, double coolingRate) { this.initialTemperature = this.currentTemperature = initialTemperature; this.coolingRate = coolingRate; } @Override public double getTemperature(int iteration) { return currentTemperature = initialTemperature * (Math.pow(coolingRate, iteration)); } @Override public boolean isCool() { return currentTemperature < COOL_THRESHOLD; } @Override public void reset() { this.currentTemperature = initialTemperature; } }
package hard; import java.util.Arrays; public class SwapNumbersInMemory { public static void swapTwoNumbers(int[] twoNumbers) { if (null == twoNumbers || twoNumbers.length != 2) { return; } else { twoNumbers[0] = twoNumbers[0] + twoNumbers[1]; twoNumbers[1] = twoNumbers[0] - twoNumbers[1]; twoNumbers[0] = twoNumbers[0] - twoNumbers[1]; } } public static void swapUsingXOR(int[] numbers) { numbers[0] = numbers[0] ^ numbers[1]; // difference numbers[1] = numbers[1] ^ numbers[0]; // current number 2 XORed with // difference to get number 1 numbers[0] = numbers[1] ^ numbers[0]; } public static void main(String[] args) { int[] twoNumbers = { 2, 3 }; System.out.println(Arrays.toString(twoNumbers)); // swapTwoNumbers(twoNumbers); swapUsingXOR(twoNumbers); System.out.println(Arrays.toString(twoNumbers)); /** * output: * * [2, 3] * * [3, 2] */ } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.tfar.services; import com.tfar.entity.Cousin; import java.util.List; /** * * @author hatem */ public interface CousinService { public List <Cousin> getAllCousin(); public void add(Cousin newCousin); public void update(Cousin cousin); public Cousin getCousinParnCousin(String nCousin); public List <Cousin> getListCousinParnDossier(String nDossier); public void delete(Cousin cousin); }
package java8.stream; import java.util.ArrayList; import java.util.Comparator; import java.util.List; public class MinMaxFunctions { public static void main(String[] args) { List<Product> list = new ArrayList<Product>(); list.add(new Product(1, "Book 1", 1000)); list.add(new Product(2, "Book 2", 2000)); list.add(new Product(3, "Book 3", 3000)); list.add(new Product(4, "Book 4", 4000)); Product productMax = list.stream().max(new Comparator<Product>() { @Override public int compare(Product p1, Product p2) { if(p1.price > p2.price){ return 1; } else { return -1; } } }).get(); System.out.println("Max: " + productMax.price); Product productMin = list.stream().min((product1, product2) -> { if(product1.price > product2.price) { return 1; } else { return -1; } }).get(); System.out.println("Min: " + productMin.price); } }
package com.myvodafone.android.service; import android.os.Build; import android.util.Pair; import com.myvodafone.android.utils.GlobalData; import com.myvodafone.android.utils.StaticTools; import org.repackage.ksoap2.HeaderProperty; import org.repackage.ksoap2.SoapEnvelope; import org.repackage.ksoap2.serialization.SoapObject; import org.repackage.ksoap2.serialization.SoapSerializationEnvelope; import org.repackage.ksoap2.transport.HttpTransportSE; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.SocketTimeoutException; import java.net.URL; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.List; /** * Created by kakaso on 10/20/2015. */ public class RequestsManager { public static final String DATA_NETWORK_3G = "3G"; public static final String DATA_NETWORK_WIFI = "WIFI"; public static final int connectionTimeout = 60000; public static String headerRoaming; public static String postRequest(String urlStr, String network, List<Pair> params) { String result = null; try { result = postRequest(urlStr, network, getQuery(params)); } catch (Exception e) { StaticTools.Log(e); } return result; } static String postRequest(String urlStr, String network) { String result = null; try { result = postRequest(urlStr, network, ""); } catch (Exception e) { StaticTools.Log(e); } return result; } static String postRequest(String urlStr, String network, String params) { HttpURLConnection urlConnection = null; try { URL url = new URL(urlStr); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setConnectTimeout(connectionTimeout); urlConnection.setReadTimeout(connectionTimeout); urlConnection = setPostHeaders(urlConnection, buildHeadersMap(network)); if (params != null) { OutputStream os = urlConnection.getOutputStream(); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(os, "UTF-8")); writer.write(params); writer.flush(); writer.close(); os.close(); } urlConnection.connect(); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); String headerVal = urlConnection.getHeaderField("X-WSB-Roaming"); headerRoaming = StaticTools.isNullOrEmpty(headerVal) ? headerRoaming : headerVal; String response = readStream(in); if (GlobalData.debugRequests) { StaticTools.Log("Request"); StaticTools.Log("URL", urlStr); StaticTools.Log("Parameters", params); StaticTools.Log("Response", response); } return response; } catch (Exception e) { StaticTools.Log(e); } finally { if (urlConnection != null) urlConnection.disconnect(); } return null; } private static String getQuery(List<Pair> params) throws UnsupportedEncodingException { StringBuilder result = new StringBuilder(); boolean first = true; for (Pair pair : params) { if (first) first = false; else result.append("&"); result.append(URLEncoder.encode((String) pair.first, "UTF-8")); result.append("="); result.append(URLEncoder.encode((String) pair.second, "UTF-8")); } return result.toString(); } static String getRequest(String urlStr, String network) { HttpURLConnection urlConnection = null; try { URL url = new URL(urlStr); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection = setGetHeaders(urlConnection, buildHeadersMap(network)); urlConnection.setConnectTimeout(connectionTimeout); urlConnection.setReadTimeout(connectionTimeout); urlConnection = (HttpURLConnection) url.openConnection(); InputStream in = new BufferedInputStream(urlConnection.getInputStream()); return readStream(in); } catch (Exception e) { StaticTools.Log(e); } finally { if (urlConnection != null) urlConnection.disconnect(); } return null; } static SoapObject soapRequest(SoapObject request, String URL, String SOAP_ACTION) { SoapObject result = null; List<HeaderProperty> headers = buildHeaderProperties(DATA_NETWORK_WIFI); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.setOutputSoapObject(request); HttpTransportSE androidHttpTransport = new HttpTransportSE(URL, connectionTimeout); try { androidHttpTransport.debug = true; androidHttpTransport.call(SOAP_ACTION, envelope, headers); result = (SoapObject) envelope.getResponse(); if (GlobalData.debugRequests) { StaticTools.Log("DUMP Request: ", androidHttpTransport.requestDump.trim()); StaticTools.Log("DUMP Response: ", androidHttpTransport.responseDump.trim()); } } catch (Exception e){ StaticTools.Log(e); } return result; } static SoapResult enhancedSoapRequest(SoapObject request, String URL, String SOAP_ACTION, int connectionTimeout) { SoapResult soapResult = new SoapResult(); SoapObject result = null; List<HeaderProperty> headers = buildHeaderProperties(DATA_NETWORK_WIFI); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.setOutputSoapObject(request); HttpTransportSE androidHttpTransport = new HttpTransportSE(URL, connectionTimeout); try { androidHttpTransport.debug = true; androidHttpTransport.call(SOAP_ACTION, envelope, headers); result = (SoapObject) envelope.getResponse(); if (GlobalData.debugRequests) { StaticTools.Log("DUMP Request: ", androidHttpTransport.requestDump.trim()); StaticTools.Log("DUMP Response: ", androidHttpTransport.responseDump.trim()); } soapResult.setResponseStatus(SoapResult.RESPONSE_SUCCESS); } catch (SocketTimeoutException e){ soapResult.setResponseStatus(SoapResult.RESPONSE_TIMEOUT); StaticTools.Log(e); } catch (Exception e){ soapResult.setResponseStatus(SoapResult.RESPONSE_ERROR); StaticTools.Log(e); } soapResult.setSoapResponse(result); return soapResult; } static String soapStringRequest(SoapObject request, String URL, String SOAP_ACTION) { List<HeaderProperty> headers = buildHeaderProperties(DATA_NETWORK_WIFI); SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.setOutputSoapObject(request); HttpTransportSE androidHttpTransport = new HttpTransportSE(URL, connectionTimeout); try { androidHttpTransport.debug = true; androidHttpTransport.call(SOAP_ACTION, envelope, headers); if (GlobalData.debugRequests) { StaticTools.Log("DUMP Request: ", androidHttpTransport.requestDump.trim()); StaticTools.Log("DUMP Response: ", androidHttpTransport.responseDump.trim()); } } catch (Exception e){ StaticTools.Log(e); } return androidHttpTransport.responseDump; } public static List<HeaderProperty> buildHeaderProperties(String network) { List<HeaderProperty> headers = new ArrayList<>(); headers.add(new HeaderProperty("vf-app-version", GlobalData.APP_VERSION)); headers.add(new HeaderProperty("vf-app-device", "android " + android.os.Build.DEVICE + " " + android.os.Build.MODEL)); headers.add(new HeaderProperty("vf-app-device-os", Build.VERSION.RELEASE)); headers.add(new HeaderProperty("vf-app-type", "app")); headers.add(new HeaderProperty("vf-app-network", network)); // TODO: check if this fixes EOFExceptions headers.add(new HeaderProperty("Connection", "close")); return headers; } private static HashMap<String, String> buildHeadersMap(String network) { HashMap<String, String> headers = new HashMap<>(); headers.put("vf-app-version", GlobalData.APP_VERSION); headers.put("vf-app-device", android.os.Build.DEVICE + " " + android.os.Build.MODEL); headers.put("vf-app-device-os", Build.VERSION.RELEASE); headers.put("vf-app-type", "app"); headers.put("vf-app-network", network); if (network.equals(DATA_NETWORK_3G)) { headers.put("Content-Type", "application/json"); } else { headers.put("Content-Type", "application/xml;charset=UTF-8"); } // TODO: check if this fixes EOFExceptions headers.put("Connection", "close"); return headers; } public static HashMap<String, String> buildWebViewHeadersMap() { HashMap<String, String> headers = new HashMap<>(); headers.put("vf-app-type", "app"); return headers; } private static HttpURLConnection setPostHeaders(HttpURLConnection httpURLConnection, HashMap<String, String> headers) { try { httpURLConnection.setRequestMethod("POST"); for (String header : headers.keySet()) { httpURLConnection.setRequestProperty(header, headers.get(header)); } } catch (Exception e) { StaticTools.Log(e); } return httpURLConnection; } private static HttpURLConnection setGetHeaders(HttpURLConnection httpURLConnection, HashMap<String, String> headers) { try { httpURLConnection.setRequestMethod("GET"); for (String header : headers.keySet()) { httpURLConnection.setRequestProperty(header, headers.get(header)); } } catch (Exception e) { StaticTools.Log(e); } return httpURLConnection; } private static String readStream(InputStream inputStream) { try { BufferedReader r = new BufferedReader(new InputStreamReader(inputStream)); StringBuilder total = new StringBuilder(); String line; while ((line = r.readLine()) != null) { total.append(line); } return total.toString().trim(); } catch (Exception e) { StaticTools.Log(e); } return null; } }
package com.atguigu.java2; import org.junit.Test; /** 自定义泛型类,泛型接口,泛型方法 */ public class GenericTest2 { /* * 自定义泛型接口 */ @Test public void test4(){ class A implements MyInterface<String>{ @Override public void setE(String e) { // TODO Auto-generated method stub } @Override public String getE() { // TODO Auto-generated method stub return null; } } MyInterface<String> m = new MyInterface<String>(){ @Override public void setE(String e) { // TODO Auto-generated method stub } @Override public String getE() { // TODO Auto-generated method stub return null; } }; } /* * 通过子类指明父类的泛型类型 * 方式一 : 子类在继承父类的时候就指明父类的泛型类型 * 方式二 : 通过创建子类的对象时候指明父类的泛型类型 */ @Test public void test3(){ SubClass<Integer> sc = new SubClass<Integer>(); } /* * 自定义泛型类 */ @Test public void test2(){ Student<String, Integer, Double> student = new Student<String,Integer,Double>(); } /* * 自定义泛型类 */ @Test public void test(){ Person<String> person = new Person<String>(); person.setT("aaa"); String name = person.getT(); System.out.println(name); Person<Integer> p2 = new Person<Integer>(); p2.setT(1111); } }
package com.citibank.ods.modules.client.knowledgeexp.functionality.valueobject; import java.math.BigInteger; import com.citibank.ods.common.dataset.DataSet; import com.citibank.ods.common.functionality.valueobject.BaseODSFncVO; @SuppressWarnings("serial") public class BaseKnowledgeExperienceDetailFncVO extends BaseODSFncVO{ /** * Número do Cliente */ private BigInteger clientNumber; /** * Nome do cliente */ private String clientNameText; private DataSet results; public DataSet getResults() { return results; } public void setResults(DataSet result) { this.results = result; } public String getClientNameText() { return clientNameText; } public void setClientNameText(String clientNameText) { this.clientNameText = clientNameText; } public BigInteger getClientNumber() { return clientNumber; } public void setClientNumber(BigInteger clientNumber) { this.clientNumber = clientNumber; } }
package in.vamsoft.excersise2; /* * @author vignesh */ public class CharUtils { public static String padChars1(int n, String orig) { String result = ""; for(int i=0; i<n; i++) { result = result + orig; } return(result); } public static String padChars2(int n, String orig) { StringBuilder result = new StringBuilder(""); for(int i=0; i<n; i++) { result = result.append(orig); } return(result.toString()); } }
package com.larryhsiao.nyx.core.tags; import com.silverhetch.clotho.Action; import com.silverhetch.clotho.Source; import java.sql.Connection; import java.sql.PreparedStatement; /** * Action to remove */ public class TagRemoval implements Action { private final Source<Connection> db; private final long id; public TagRemoval(Source<Connection> db, long id) { this.db = db; this.id = id; } @Override public void fire() { try { final PreparedStatement linkRemoval = db.value().prepareStatement( // language=H2 "UPDATE TAG_JOT " + "SET DELETE = 1, VERSION = VERSION + 1 " + "WHERE TAG_ID=?;" ); linkRemoval.setLong(1, id); linkRemoval.executeUpdate(); linkRemoval.close(); final PreparedStatement tagRemoval = db.value().prepareStatement( // language=H2 "UPDATE tags " + "SET DELETE = 1, VERSION = VERSION + 1 " + "WHERE id=?;" ); tagRemoval.setLong(1, id); tagRemoval.executeUpdate(); tagRemoval.close(); } catch (Exception e) { throw new IllegalArgumentException(e); } } }
package ffm.slc.model; import ffm.slc.model.enums.GenerationCodeSuffixType; import ffm.slc.model.enums.PersonalInformationVerificationType; import ffm.slc.model.enums.PersonalTitlePrefixType; import ffm.slc.model.resources.SimpleName; public class Name { private PersonalTitlePrefixType personalTitlePrefix; public PersonalTitlePrefixType getPersonalTitlePrefix() { return personalTitlePrefix; } public void setPersonalTitlePrefix(PersonalTitlePrefixType personalTitlePrefix) { this.personalTitlePrefix = personalTitlePrefix; } private SimpleName firstName; public SimpleName getFirstName() { return firstName; } public void setFirstName(SimpleName firstName) { this.firstName = firstName; } private SimpleName middleName; public SimpleName getMiddleName() { return middleName; } public void setMiddleName(SimpleName middleName) { this.middleName = middleName; } private SimpleName lastSurname; public SimpleName getLastSurname() { return lastSurname; } public void setLastSurname(SimpleName lastSurname) { this.lastSurname = lastSurname; } private GenerationCodeSuffixType generationCodeSuffix; public GenerationCodeSuffixType getGenerationCodeSuffix() { return generationCodeSuffix; } public void setGenerationCodeSuffix(GenerationCodeSuffixType generationCodeSuffix) { this.generationCodeSuffix = generationCodeSuffix; } private SimpleName maidenName; public SimpleName getMaidenName() { return maidenName; } public void setMaidenName(SimpleName maidenName) { this.maidenName = maidenName; } private PersonalInformationVerificationType verification; public PersonalInformationVerificationType getVerification() { return verification; } public void setVerification(PersonalInformationVerificationType verification) { this.verification = verification; } public String getFullame() { return (personalTitlePrefix!=null?personalTitlePrefix:"")+" "+firstName+" "+lastSurname; } }
package base.javaThread.demoSync; /** * 死锁 * 两个线程都在等待对方先施放锁。 * @author adminitartor * */ public class SyncDemo5 { public static void main(String[] args) { final Coo c = new Coo(); Thread t1 = new Thread(){ public void run(){ c.methodA(); } }; Thread t2 = new Thread(){ public void run(){ c.methodB(); } }; t1.start(); t2.start(); } } class Coo{ private Object oa = new Object(); private Object ob = new Object(); public void methodA(){ Thread t = Thread.currentThread(); synchronized (oa) { System.out.println( t.getName()+":正在执行A方法.."); try { Thread.sleep(5000); } catch (InterruptedException e) { } methodB(); System.out.println( t.getName()+"运行A方法完毕"); } } public void methodB(){ Thread t = Thread.currentThread(); synchronized (ob) { System.out.println(t.getName()+":正在执行B方法.."); try { Thread.sleep(5000); } catch (InterruptedException e) { } methodA(); System.out.println(t.getName()+"运行B方法完毕"); } } }
package com.zzh.config; import feign.Feign; import feign.auth.BasicAuthRequestInterceptor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Scope; /** * @author zhaozh * @version 1.0 * @date 2018-1-4 13:25 **/ @Configuration public class EurekaAuthConfiguration { /** * 主要配置登录 Eureka 服务器的帐号与密码。 * * @return */ @Bean public BasicAuthRequestInterceptor basicAuthRequestInterceptor() { return new BasicAuthRequestInterceptor("admin", "admin"); } /** * 在该配置中,加入这个方法的话,表明使用了该配置的地方,就会禁用该模块使用 Hystrix 容灾降级的功能; * * @return */ // @Bean //// @Scope //// public Feign.Builder feignBuilder() { //// return Feign.builder(); //// } }
/* * 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 pertemuan7; import javax.swing.JOptionPane; /** * * @author Angga */ public class Validasi { public static void main(String[] args) { String firstName=JOptionPane.showInputDialog(null,"Masukan Nama Depan : "); String lastName=JOptionPane.showInputDialog(null,"Masukan Nama Belakang : "); String address=JOptionPane.showInputDialog(null,"Masukan Alamat : "); String city = JOptionPane.showInputDialog(null,"Masukan Kota : "); String zip=JOptionPane.showInputDialog(null,"Masuka Kode Pos : "); String phone=JOptionPane.showInputDialog(null,"Masukan Nomor Telp : "); if(!ValidateInput.validateFirstName(firstName)) JOptionPane.showMessageDialog(null,"Hasil Validasi : Nama Depan Salah"); else if(!ValidateInput.validateLastName(lastName)) JOptionPane.showMessageDialog(null,"Hasil Validasi : Nama Belakang Salah"); else if (!ValidateInput.validateAddress(address)) JOptionPane.showMessageDialog(null,"Hasil Validasi : Alamat Salah "); else if (!ValidateInput.validateCity(city)) JOptionPane.showMessageDialog(null,"Hasil Validasi : Kota Salah "); else if (!ValidateInput.validateZip(zip)) JOptionPane.showMessageDialog(null,"Hasil Validasi : Kode Pos Salah "); else if (!ValidateInput.validatePhone(phone)) JOptionPane.showMessageDialog(null,"Hasil Validasi : Nomor Telp Salah "); else System.out.println("Terima Kasih"); } }
/* * 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 PPI.Vista; import PPI.Controladores.ControladorIniciarSesion; import PPI.Modelos.ModeloUsuario; import javax.swing.ImageIcon; import javax.swing.JOptionPane; /** * * @author Personal */ public class VistaIniciarSesion extends javax.swing.JFrame { ControladorIniciarSesion controlador; /** * Creates new form VistaIniciarSesion */ public VistaIniciarSesion() { initComponents(); //Agregamos la locación de donde sale el proyecto y le agregamos un icono this.setLocationRelativeTo(null); this.setIconImage(new ImageIcon(getClass().getResource("/Imagenes/grano-de-cafe.png")).getImage()); //Agregamos un placeholder a los campos de textos que tenemos TextPrompt placeHolder = new TextPrompt("Ingrese la contraseña registrada", txtContrasena); placeHolder = new TextPrompt("Ingrese el correo electrónico registrado", txtCorreoElectronico); controlador = new ControladorIniciarSesion(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel3 = new javax.swing.JPanel(); jPanel4 = new javax.swing.JPanel(); lblLogo = new javax.swing.JLabel(); lblVolver = new javax.swing.JLabel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); txtCorreoElectronico = new javax.swing.JTextField(); jLabel3 = new javax.swing.JLabel(); jLabel4 = new javax.swing.JLabel(); jLabel5 = new javax.swing.JLabel(); jLabel6 = new javax.swing.JLabel(); btnIniciarSesion = new javax.swing.JButton(); txtContrasena = new javax.swing.JPasswordField(); jLabel7 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); setTitle("Iniciar Sesión - CoffeWine"); jPanel3.setBackground(new java.awt.Color(215, 204, 200)); jPanel4.setBackground(new java.awt.Color(93, 64, 55)); lblLogo.setBackground(new java.awt.Color(255, 255, 255)); lblLogo.setFont(new java.awt.Font("Dialog", 3, 18)); // NOI18N lblLogo.setForeground(new java.awt.Color(255, 255, 255)); lblLogo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/grano-de-cafe.png"))); // NOI18N lblLogo.setText("CoffeWine"); lblVolver.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/atras.png"))); // NOI18N lblVolver.setCursor(new java.awt.Cursor(java.awt.Cursor.HAND_CURSOR)); lblVolver.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { lblVolverMouseClicked(evt); } }); jLabel1.setBackground(new java.awt.Color(255, 255, 255)); jLabel1.setFont(new java.awt.Font("Dialog", 1, 18)); // NOI18N jLabel1.setForeground(new java.awt.Color(255, 255, 255)); jLabel1.setText("Iniciar Sesión"); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup() .addContainerGap() .addComponent(lblVolver) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel1) .addGap(144, 144, 144) .addComponent(lblLogo) .addContainerGap()) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lblLogo) .addComponent(jLabel1)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(lblVolver) .addGap(0, 0, Short.MAX_VALUE)) ); jLabel2.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N jLabel2.setText("Correo Electrónico"); txtCorreoElectronico.setFont(new java.awt.Font("Dialog", 0, 14)); // NOI18N txtCorreoElectronico.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)); jLabel3.setFont(new java.awt.Font("Dialog", 1, 14)); // NOI18N jLabel3.setText("Contraseña"); jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/candado.png"))); // NOI18N jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagenes/usuario.png"))); // NOI18N btnIniciarSesion.setBackground(new java.awt.Color(93, 64, 55)); btnIniciarSesion.setForeground(new java.awt.Color(255, 255, 255)); btnIniciarSesion.setText("Iniciar Sesión"); btnIniciarSesion.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnIniciarSesionMouseClicked(evt); } }); txtContrasena.setFont(new java.awt.Font("Dialog", 0, 14)); // NOI18N txtContrasena.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED)); txtContrasena.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { txtContrasenaActionPerformed(evt); } }); jLabel7.setForeground(new java.awt.Color(255, 0, 0)); jLabel7.setText("Recuerde que la contraseña debe contener 1 minuscula, 1 mayuscula, minimo 8 caracteres y 1 número"); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel4) .addGap(287, 287, 287)) .addGroup(jPanel3Layout.createSequentialGroup() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(39, 39, 39) .addComponent(jLabel7)) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(275, 275, 275) .addComponent(btnIniciarSesion)) .addGroup(jPanel3Layout.createSequentialGroup() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(146, 146, 146) .addComponent(jLabel6)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel5))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtContrasena, javax.swing.GroupLayout.PREFERRED_SIZE, 324, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtCorreoElectronico, javax.swing.GroupLayout.PREFERRED_SIZE, 324, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(280, 280, 280) .addComponent(jLabel3)) .addGroup(jPanel3Layout.createSequentialGroup() .addGap(256, 256, 256) .addComponent(jLabel2))) .addContainerGap(40, Short.MAX_VALUE)) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(82, 82, 82) .addComponent(jLabel2) .addGap(18, 18, 18) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel6) .addComponent(txtCorreoElectronico, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(21, 21, 21) .addComponent(jLabel3) .addGap(18, 18, 18) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel5) .addComponent(txtContrasena, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(19, 19, 19) .addComponent(jLabel4) .addGap(18, 18, 18) .addComponent(jLabel7) .addGap(34, 34, 34) .addComponent(btnIniciarSesion) .addGap(0, 70, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); pack(); }// </editor-fold>//GEN-END:initComponents private void lblVolverMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lblVolverMouseClicked VistaPrincipal principal = new VistaPrincipal(); principal.setVisible(true); dispose(); }//GEN-LAST:event_lblVolverMouseClicked private void txtContrasenaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtContrasenaActionPerformed // TODO add your handling code here: }//GEN-LAST:event_txtContrasenaActionPerformed private void btnIniciarSesionMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnIniciarSesionMouseClicked ModeloUsuario usuario = new ModeloUsuario(); usuario.setCorreo(txtCorreoElectronico.getText()); usuario.setContrasena(String.valueOf(txtContrasena.getPassword())); if (txtCorreoElectronico.getText().isEmpty() || String.valueOf(txtContrasena.getPassword()).isEmpty()) { JOptionPane.showMessageDialog(null, "Hay campos obligatorios sin llenar(*)", "INICIAR SESIÓN", JOptionPane.ERROR_MESSAGE); } else { boolean respuesta = controlador.iniciarSesion(usuario); if (respuesta == true) { JOptionPane.showMessageDialog(null, "Bienvenido a CoffeWine", "INICIAR SESIÓN", JOptionPane.INFORMATION_MESSAGE); VistaPrincipal principal = new VistaPrincipal(); principal.setVisible(true); this.dispose(); } else { if (respuesta == false) { JOptionPane.showMessageDialog(null, "Los campos ingresados son incorrectos", "INICIAR SESIÓN", JOptionPane.ERROR_MESSAGE); } } } }//GEN-LAST:event_btnIniciarSesionMouseClicked /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(VistaIniciarSesion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(VistaIniciarSesion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(VistaIniciarSesion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(VistaIniciarSesion.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new VistaIniciarSesion().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnIniciarSesion; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JLabel lblLogo; private javax.swing.JLabel lblVolver; private javax.swing.JPasswordField txtContrasena; private javax.swing.JTextField txtCorreoElectronico; // End of variables declaration//GEN-END:variables }
package hr.apps.cookies.mcpare.adapters; import android.content.Context; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentPagerAdapter; import android.util.SparseArray; import android.view.ViewGroup; import android.widget.Button; import hr.apps.cookies.mcpare.R; import hr.apps.cookies.mcpare.fragments.FragmentProsli; import hr.apps.cookies.mcpare.fragments.FragmentSljedeci; import hr.apps.cookies.mcpare.fragments.FragmentTrenutni; /** * Created by lmita_000 on 26.5.2015.. */ public class PagerAdapter extends FragmentPagerAdapter { String[] tabsTitles; Context context; SparseArray<Fragment> fragmenti; public PagerAdapter(FragmentManager fm, Context context) { super(fm); tabsTitles = context.getResources().getStringArray(R.array.tabs_titles); this.context = context; fragmenti = new SparseArray<Fragment>(); } @Override public Fragment getItem(int position) { Fragment fragment = null; switch (position){ case 0: fragment = new FragmentProsli(); break; case 1: fragment = new FragmentTrenutni(); break; case 2: fragment = new FragmentSljedeci(); break; } return fragment; } @Override public int getCount() { return 3; } @Override public CharSequence getPageTitle(int position) { //return super.getPageTitle(position); return tabsTitles[position]; } @Override public Object instantiateItem(ViewGroup container, int position) { //return super.instantiateItem(container, position); Fragment fragment = (Fragment) super.instantiateItem(container, position); fragmenti.put(position, fragment); return fragment; } @Override public void destroyItem(ViewGroup container, int position, Object object) { fragmenti.remove(position); super.destroyItem(container, position, object); } public Fragment getFragmentAtPosition(int position){ return fragmenti.get(position); } }
package model; import java.util.Scanner; public class FullTime extends Employee{ private int mWorkDay; public FullTime() { super(); } public FullTime(int mId, String mName, String mDateOfBirth, int mSalary, int mWorkDay) { super(mId, mName, mDateOfBirth, mSalary); this.mWorkDay = mWorkDay; } public int getmWorkDay() { return mWorkDay; } public void setmWorkDay(int mWorkDay) { this.mWorkDay = mWorkDay; } //override phuong thuc getmsalary() de chinh sua @Override public int getmSalary() { // TODO Auto-generated method stub return (mWorkDay * 1200000 + 800000); } //ham tra ve tien luong nhan vien @Override public void getSalary() { System.out.println("salary: "+getmSalary()); } @Override public void input(Scanner scanner) { // TODO Auto-generated method stub super.input(scanner); System.out.print("Work Day: "); mWorkDay = scanner.nextInt(); } //ham in ra thong tin nhan vien @Override public void showInfor() { System.out.println("=== Full Time ==="); System.out.println("id: "+getmId()); System.out.println("name: "+getmName()); System.out.println("date of birth: "+getmDateOfBirth()); System.out.println("work day: "+getmWorkDay()); getSalary(); } }
import com.itextpdf.html2pdf.ConverterProperties; import com.itextpdf.html2pdf.HtmlConverter; import org.junit.jupiter.api.Test; import java.io.*; public class TextConvertor { @Test public void testcItextSevenConvertor() throws Exception{ File pdfDest = new File("/Users/betwar/Documents/itext_output.pdf"); // pdfHTML specific code InputStream asInput = new ByteArrayInputStream(getHtml().getBytes()); ConverterProperties converterProperties = new ConverterProperties(); HtmlConverter.convertToPdf(asInput, new FileOutputStream(pdfDest), converterProperties); } public String getHtml(){ return "<html>\n" + "<head>\n" + "<title>Mobility and Transfer Assessment</title>\n" + "<style>" + getCss() + "</style>"+ "</head>\n" + "<body>\n" + "\u200B\n" + "<section class=\"gentle\">\n" + "\u200B\n" + "<h1><span>All Aged Care</span> <br />Mobility and Transfer Assessment</h1>\n" + "<p class=\"instructions\">(To be completed for relevant consumers on admission and as required)</p>\n" + "&nbsp;\n" + "<table border=\"1\" cellpadding=\"1\" cellspacing=\"1\" class=\"borderless\" style=\"width:100%;\">\n" + "<tbody>\n" + "<tr>\n" + "<td><strong>First Name:</strong> <span contenteditable=\"false\" th:if=\"${linkedclientdto.firstname != null && !#strings.isEmpty(linkedclientdto.firstname)}\" th:text=\"${linkedclientdto.firstname}\">[ linkedclientdto firstname ] </span></td>\n" + "<td><strong>Surname:</strong> <span contenteditable=\"false\" th:if=\"${linkedclientdto.lastname != null && !#strings.isEmpty(linkedclientdto.lastname)}\" th:text=\"${linkedclientdto.lastname}\">[ linkedclientdto lastname ] </span></td>\n" + "</tr>\n" + "<tr>\n" + "<td><strong>Date of Assessment:</strong></td>\n" + "<td><strong>Date of Birth:</strong> <span contenteditable=\"false\" th:if=\"${linkedclientdto.dateofbirth != null && !#strings.isEmpty(linkedclientdto.dateofbirth)}\" th:text=\"${linkedclientdto.dateofbirth}\">[ linkedclientdto dateofbirth ] </span></td>\n" + "</tr>\n" + "</tbody>\n" + "</table>\n" + "&nbsp; &nbsp;\n" + "\u200B\n" + "<table border=\"1\" cellpadding=\"1\" cellspacing=\"1\" style=\"width:100%;\">\n" + "<thead>\n" + "<tr>\n" + "<th scope=\"col\">Activity</th>\n" + "<th colspan=\"4\" scope=\"col\">Ability / Supports</th>\n" + "</tr>\n" + "</thead>\n" + "<tbody>\n" + "<tr>\n" + "<th rowspan=\"5\" scope=\"row\">Walking</th>\n" + "<th>Independent</th>\n" + "<td>Yes</td>\n" + "<td>No</td>\n" + "<td>&nbsp;</td>\n" + "</tr>\n" + "<tr>\n" + "<th scope=\"row\">Assistance required</th>\n" + "<td colspan=\"3\">&nbsp;</td>\n" + "</tr>\n" + "<tr>\n" + "<th scope=\"row\">No. of assistants:</th>\n" + "<td>One person</td>\n" + "<td>Two persons</td>\n" + "<td>&nbsp;</td>\n" + "</tr>\n" + "<tr>\n" + "<th rowspan=\"2\" scope=\"row\">Type of aid:</th>\n" + "<td>Walking stick</td>\n" + "<td>Wheeled frame</td>\n" + "<td>Frame</td>\n" + "</tr>\n" + "<tr>\n" + "<td>Wheelchair</td>\n" + "<td>Walk belt</td>\n" + "<td>Other ___________________</td>\n" + "</tr>\n" + "<tr>\n" + "<th rowspan=\"5\" scope=\"row\">Lying to sitting on edge of bed</th>\n" + "<th>Independent</th>\n" + "<td>Yes</td>\n" + "<td>No</td>\n" + "<td>&nbsp;</td>\n" + "</tr>\n" + "<tr>\n" + "<th scope=\"row\">Assistance required</th>\n" + "<td colspan=\"3\">&nbsp;</td>\n" + "</tr>\n" + "<tr>\n" + "<th scope=\"row\">No. of assistants:</th>\n" + "<td>One person</td>\n" + "<td>Two persons</td>\n" + "<td>&nbsp;</td>\n" + "</tr>\n" + "<tr>\n" + "<th rowspan=\"2\" scope=\"row\">Type of aid:</th>\n" + "<td>Walking stick</td>\n" + "<td>Wheeled frame</td>\n" + "<td>Frame</td>\n" + "</tr>\n" + "<tr>\n" + "<td>Wheelchair</td>\n" + "<td>Walk belt</td>\n" + "<td>Other ___________________</td>\n" + "</tr>\n" + "<tr>\n" + "<th rowspan=\"5\" scope=\"row\">Bed to bed/chair to bed</th>\n" + "<th>Independent</th>\n" + "<td>Yes</td>\n" + "<td>No</td>\n" + "<td>&nbsp;</td>\n" + "</tr>\n" + "<tr>\n" + "<th scope=\"row\">Assistance required</th>\n" + "<td colspan=\"3\">&nbsp;</td>\n" + "</tr>\n" + "<tr>\n" + "<th scope=\"row\">No. of assistants:</th>\n" + "<td>One person</td>\n" + "<td>Two persons</td>\n" + "<td>&nbsp;</td>\n" + "</tr>\n" + "<tr>\n" + "<th rowspan=\"2\" scope=\"row\">Type of aid:</th>\n" + "<td>Walking stick</td>\n" + "<td>Wheeled frame</td>\n" + "<td>Frame</td>\n" + "</tr>\n" + "<tr>\n" + "<td>Wheelchair</td>\n" + "<td>Walk belt</td>\n" + "<td>Other ___________________</td>\n" + "</tr>\n" + "<tr>\n" + "<th rowspan=\"5\" scope=\"row\">Toileting</th>\n" + "<th>Independent</th>\n" + "<td>Yes</td>\n" + "<td>No</td>\n" + "<td>&nbsp;</td>\n" + "</tr>\n" + "<tr>\n" + "<th scope=\"row\">Assistance required</th>\n" + "<td colspan=\"3\">&nbsp;</td>\n" + "</tr>\n" + "<tr>\n" + "<th scope=\"row\">No. of assistants:</th>\n" + "<td>One person</td>\n" + "<td>Two persons</td>\n" + "<td>&nbsp;</td>\n" + "</tr>\n" + "<tr>\n" + "<th rowspan=\"2\" scope=\"row\">Type of aid:</th>\n" + "<td>Walking stick</td>\n" + "<td>Wheeled frame</td>\n" + "<td>Frame</td>\n" + "</tr>\n" + "<tr>\n" + "<td>Wheelchair</td>\n" + "<td>Walk belt</td>\n" + "<td>Other ___________________</td>\n" + "</tr>\n" + "<tr>\n" + "<th rowspan=\"5\" scope=\"row\">Sitting to standing</th>\n" + "<td>&nbsp;</td>\n" + "<th>Independent</th>\n" + "<td>Yes</td>\n" + "<td>No</td>\n" + "<td>&nbsp;</td>\n" + "</tr>\n" + "<tr>\n" + "<th scope=\"row\">Assistance required</th>\n" + "<td colspan=\"3\">&nbsp;</td>\n" + "</tr>\n" + "<tr>\n" + "<th scope=\"row\">No. of assistants:</th>\n" + "<td>One person</td>\n" + "<td>Two persons</td>\n" + "<td>&nbsp;</td>\n" + "</tr>\n" + "<tr>\n" + "<th rowspan=\"2\" scope=\"row\">Type of aid:</th>\n" + "<td>Walking stick</td>\n" + "<td>Wheeled frame</td>\n" + "<td>Frame</td>\n" + "</tr>\n" + "<tr>\n" + "<td>Wheelchair</td>\n" + "<td>Walk belt</td>\n" + "<td>Other ___________________</td>\n" + "</tr>\n" + "<tr>\n" + "<th rowspan=\"5\" scope=\"row\">Positioning in bed</th>\n" + "<th>Independent</th>\n" + "<td>Yes</td>\n" + "<td>No</td>\n" + "<td>&nbsp;</td>\n" + "</tr>\n" + "<tr>\n" + "<th scope=\"row\">Assistance required</th>\n" + "<td colspan=\"3\">&nbsp;</td>\n" + "</tr>\n" + "<tr>\n" + "<th scope=\"row\">No. of assistants:</th>\n" + "<td>One person</td>\n" + "<td>Two persons</td>\n" + "<td>&nbsp;</td>\n" + "</tr>\n" + "<tr>\n" + "<th rowspan=\"2\" scope=\"row\">Type of aid:</th>\n" + "<td>Walking stick</td>\n" + "<td>Wheeled frame</td>\n" + "<td>Frame</td>\n" + "</tr>\n" + "<tr>\n" + "<td>Wheelchair</td>\n" + "<td>Walk belt</td>\n" + "<td>Other ___________________</td>\n" + "</tr>\n" + "<tr>\n" + "<th rowspan=\"5\" scope=\"row\">Showering</th>\n" + "<th>Independent</th>\n" + "<td>Yes</td>\n" + "<td>No</td>\n" + "<td>&nbsp;</td>\n" + "</tr>\n" + "<tr>\n" + "<th scope=\"row\">Assistance required</th>\n" + "<td colspan=\"3\">&nbsp;</td>\n" + "</tr>\n" + "<tr>\n" + "<th scope=\"row\">No. of assistants:</th>\n" + "<td>One person</td>\n" + "<td>Two persons</td>\n" + "<td>&nbsp;</td>\n" + "</tr>\n" + "<tr>\n" + "<th rowspan=\"2\" scope=\"row\">Type of aid:</th>\n" + "<td>Walking stick</td>\n" + "<td>Wheeled frame</td>\n" + "<td>Frame</td>\n" + "</tr>\n" + "<tr>\n" + "<td>Wheelchair</td>\n" + "<td>Walk belt</td>\n" + "<td>Other ___________________</td>\n" + "</tr>\n" + "</tbody>\n" + "</table>\n" + "&nbsp;\n" + "\u200B\n" + "<table border=\"1\" cellpadding=\"1\" cellspacing=\"1\" class=\"borderless\" style=\"width:100%;\">\n" + "<tbody>\n" + "<tr>\n" + "<th>Assessor&#39;s Signature: .........................................................................</td>\n" + "<th>Date: .........................................................................</td>\n" + "</tr>\n" + "</tbody>\n" + "</table>\n" + "\u200B\n" + "</section>\n" + "\u200B\n" + "</body>\n" + "</html>"; } public String getCss(){ return "body {\n" + "margin: 0.5in; \n" + "line-height: 140%;\n" + "}\n" + "* { \n" + "font-size: 13px;\n" + "font-family: Verdana, Arial, sans-serif;\n" + "}\n" + "div.title { \n" + "font-size: 26px;\n" + "line-height: 130%;\n" + "padding: 1em;\n" + "text-align: center;\n" + "font-weight: bold;\n" + "text-transform: uppercase;\n" + "border-top-style: double;\n" + "border-bottom-style: double;\n" + "}\n" + "h2 { \n" + "text-align: center;\n" + "font-size: 20px;\n" + "}\n" + "h2.subhead { \n" + "font-size: 13px;\n" + "}\n" + "\u200B\n" + "li, dt, dd { \n" + "margin-bottom: 1rem;\n" + "}\n" + "dt {\n" + "font-weight: bold;\n" + "}\n" + "table { \n" + "border: 1px solid black;\n" + "width: 100%;\n" + "border-collapse: collapse;\n" + "margin: 1em 0;\n" + "}\n" + "th, td {\n" + "border: 1px solid black;\n" + "text-align: left;\n" + "padding: 5px;\n" + "vertical-align: top;\n" + "}\n" + "\u200B\n" + "\u200B\n" + "\u200B\n" + "table.rows-only-bordered td { \n" + "border-bottom: 1px solid black;\n" + "border-left: 0;\n" + "border-right: 0;\n" + "}\n" + "\u200B\n" + "\u200B\n" + "/* Often instructions follow the document title */\n" + "\u200B\n" + ".instructions { \n" + "text-align: center;\n" + "font-size: 15px;\n" + "}\n" + ".centered { \n" + "text-align: center;\n" + "}\n" + "\u200B\n" + ".left { \n" + "text-align: left;\n" + "}\n" + "\u200B\n" + "\u200B\n" + "/* \n" + "Tables come in blue, black, lightgrey and darkgrey,\n" + "which each have different th colours.\n" + "*/\n" + "\u200B\n" + ".bluetable thead th { \n" + "background-color: #356091; \n" + "color: #FFF;\n" + "}\n" + "\u200B\n" + "/* Forgive me father for I have sinned... nesting tables inside other tables */\n" + ".gentle table table.borderless {\n" + "margin: 0;\n" + "}\n" + ".gentle table table.borderless th {\n" + "text-align: left;\n" + "vertical-align: top;\n" + "}\n" + "\n" + ".borderless, .borderless td, .borderless th { \n" + "border: 0;\n" + "padding-left: 0;\n" + "}\n" + "\u200B\n" + ".borderless th { \n" + "background: none;\n" + "}\n" + ".lightgreytable thead th { \n" + "background-color: #ccc;\n" + "}\n" + "\u200B\n" + ".darkgreytable th { \n" + "background-color: #333; \n" + "color: #FFF;\n" + "}\n" + "\u200B\n" + ".blacktable th { \n" + "background-color: #000; \n" + "color: #FFF;\n" + "}\n" + "\u200B\n" + "/* \n" + " \"Gentle\" sections (forms whose originals used pastel blues)\n" + " h1s are grey and blue.\n" + " tables have pastel blue headers which are centre-aligned except for the first in each row.\n" + "*/\n" + "\u200B\n" + ".gentle th { \n" + "background:#b5cde8;\n" + "text-align: center;\n" + "vertical-align: middle;\n" + "}\n" + "\u200B\n" + ".gentle table.borderless th {\n" + "background: none;\n" + "}\n" + "\u200B\n" + ".gentle h1 {\n" + "color: #4372c4;\n" + "text-transform: uppercase;\n" + "font-weight: normal;\n" + "font-size: 24px;\n" + "text-align: center;\n" + "line-height: 140%;\n" + "}\n" + ".gentle h1 span {\n" + "color: gray;\n" + "font-size: inherit;\n" + "}\n" + "\u200B\n" + ".gentle h2 {\n" + "font-size: 13px;\n" + "background: #b5cde8;\n" + "text-align: left;\n" + "padding: 2px 5px;\n" + "border-top: 1px solid black;\n" + "border-bottom: 1px solid black;\n" + "}\n" + "\u200B\n" + ".gentle h3 {\n" + "font-size: 13px;\n" + "font-style: italic;\n" + "margin-top: 20px;\n" + "}\n" + "\u200B\n" + "\u200B\n" + ".gentle .notice-block { \n" + "text-align: center;\n" + "font-weight: bold;\n" + "background: #b5cde8;\n" + "padding: 2px 5px;\n" + "border-top: 1px solid black;\n" + "border-bottom: 1px solid black;\n" + "}\n" + "\u200B\n" + ".note { \n" + "font-weight: normal; \n" + "font-size: 90%;\n" + "}\n" + "\u200B\n" + "\u200B\n" + "/* \n" + "These table have rowgroups too, so here are some widths \n" + "to maintain a bit of horizontal th consistency.\n" + "*/\n" + "\u200B\n" + "\u200B\n" + ".col_lvl1 { \n" + "width: 20%;\n" + "}\n" + ".col_lvl2 { \n" + "width: 15%;\n" + "}\n" + ".fillable {\n" + "border-bottom: 2px dotted black !important;\n" + "}"; } }
package com.GetpageSource; import java.util.concurrent.TimeUnit; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; public class Google_IdentifyAnElement_Livetech { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver","C:\\Users\\new\\eclipse-workspace\\BrowserAutomation\\DriverFiles\\chromedriver.exe"); WebDriver driver = null; driver=new ChromeDriver(); String url="http://google.com/"; driver.get(url); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); driver.manage().window().maximize(); String expected_Element="Gmail"; System.out.println("The expected element is:"+expected_Element); String actual_PageSource=driver.getPageSource(); System.out.println("The actual element is:"+actual_PageSource); if(actual_PageSource.contains(expected_Element)) { System.out.println("Element found-PASS"); } else { System.out.println("Element not found-FAIL"); } driver.close(); } }
package TestSuite; import org.testng.annotations.Test; import io.restassured.RestAssured; import io.restassured.response.Response; import static io.restassured.RestAssured.when; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertTrue; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; public class Tests { //Variables private static int successStatusCode = 200; private static String responseContentType = "JSON"; private static String repoName = "APITests"; private static String repoOwnerName = "venug0453"; private static String baseURI = "https://api.github.com/repos/" + repoOwnerName + "/" + repoName; //Get Response using the end point: "repository_url": "https://api.github.com/repos/{owner}/{repo}" public Response GetResponse() { RestAssured.baseURI = baseURI; Response response = when().get().then().extract().response(); return response; } @Test public void ValidateResponseStatusCode() { int statusCode = GetResponse().statusCode(); assertEquals(statusCode, successStatusCode); } @Test public void ValidateResponseContentType() { String contentType = GetResponse().getContentType(); assertTrue(contentType.toUpperCase().contains(responseContentType), "Content type is '" + contentType + "' which is not " + responseContentType); } @Test public void ValidateRepoName() { String repoNameResponse = GetResponse().jsonPath().getString("name").toString(); assertEquals(repoNameResponse, repoName); } @Test public void ValidateRepoFullName() { String repoNameResponse = GetResponse().jsonPath().getString("full_name").toString(); assertEquals(repoNameResponse, repoOwnerName + "/" + repoName); } @Test public void ValidateResponseDateHeaderFormat() { String responseTimeStamp = GetResponse().getHeader("Date"); Date date = new Date(); DateFormat df = new SimpleDateFormat("E, dd MMM yyyy HH:mm:ss z"); df.setTimeZone(TimeZone.getTimeZone("GMT")); Calendar calendar = Calendar.getInstance(); calendar.setTime(date); calendar.add(Calendar.SECOND, 1); String dateStr = df.format(date); String dateStr1 = df.format(calendar.getTime()); assertTrue((responseTimeStamp.equals(dateStr) || responseTimeStamp.equals(dateStr1)), "The 'Date' field under the response header is not as expected."); } @Test public void ValidateTimeStampsFormatUnderResponse() { Response response = GetResponse(); String responseCreatedAtTimeStamp = response.jsonPath().getString("created_at").toString(); String responseUpdatedAtTimeStamp = response.jsonPath().getString("updated_at").toString(); String responsePushedAtTimeStamp = response.jsonPath().getString("pushed_at").toString(); String matchPattern = "[\\d]{4}\\-[\\d]{2}\\-[\\d]{2}T[\\d]{2}:[\\d]{2}:[\\d]{2}Z"; assertTrue(responseCreatedAtTimeStamp.matches(matchPattern), "'created_at' field under the response is not in the expected format."); assertTrue(responseUpdatedAtTimeStamp.matches(matchPattern), "'updated_at' field under the response is not in the expected format."); assertTrue(responsePushedAtTimeStamp.matches(matchPattern), "'pushed_at' field under the response is not in the expected format."); } @Test public void ValidateResponseURLField() { String urlFieldResponse = GetResponse().jsonPath().getString("url").toString(); assertEquals(urlFieldResponse, baseURI, "Expected 'url' field <" + baseURI + "> but was <" + urlFieldResponse + ">."); } @Test public void ValidateOwnerLoginFromResponse() { String ownerLogin = GetResponse().jsonPath().getString("owner.login").toString(); assertEquals(ownerLogin, repoOwnerName, "Expected 'owner.login' field <" + repoOwnerName + "> but was <" + ownerLogin + ">."); } }
package com.zc.base.common.dao; import com.zc.base.orm.mybatis.paging.JqueryStylePaging; import org.apache.ibatis.annotations.Param; import java.io.Serializable; import java.util.List; public abstract interface BaseMapper<T extends AbstractDO, PK extends Serializable> { public abstract void deleteByPrimaryKey(PK paramPK); public abstract void insert(T paramT); public abstract void insertSelective(T paramT); public abstract T selectByPrimaryKey(PK paramPK); public abstract void updateByPrimaryKeySelective(T paramT); public abstract void updateByPrimaryKey(T paramT); public abstract List<T> queryByPaging(@Param("paging") JqueryStylePaging paramJqueryStylePaging, @Param("condition") T paramT); public abstract int getTotalCount(@Param("condition") T paramT); public abstract List<T> queryAllByCondition(@Param("condition") T paramT); }
package model; public class Paredao extends Som{ public Paredao(){ System.out.println("Paredao"); } }
/* * 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 bmiclient; import java.io.*; import java.net.*; import javafx.application.Application; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.ScrollPane; import javafx.scene.control.TextArea; import javafx.scene.control.TextField; import javafx.scene.control.Button; import javafx.scene.layout.BorderPane; import javafx.scene.layout.GridPane; import javafx.stage.Stage; /** * * @author emwhfm */ public class BMIClient extends Application { TextArea ta = null; TextField tf1 = null; TextField tf2 = null; // IO streams DataOutputStream toServer = null; BufferedReader bufReader = null; @Override public void start(Stage primaryStage) { tf1 = new TextField(); tf1.setEditable(true); tf1.setAlignment(Pos.BASELINE_RIGHT); tf2 = new TextField(); tf2.setEditable(true); tf2.setAlignment(Pos.BASELINE_RIGHT); Button btSend = new Button("Send"); btSend.setOnAction(e -> transceive()); GridPane topPane = new GridPane(); topPane.setAlignment(Pos.CENTER); topPane.setPadding(new Insets(11.5, 12.5, 13.5, 14.5)); topPane.setHgap(5.5); topPane.setVgap(5.5); topPane.add(new Label("Weight in pounds"), 0, 0); topPane.add(tf1, 1, 0); topPane.add(new Label("Height in inches"), 0, 1); topPane.add(tf2, 1, 1); topPane.add(btSend, 2, 1); BorderPane mainPane = new BorderPane(); mainPane.setPadding(new Insets(5, 5, 5, 5)); ta = new TextArea(); mainPane.setCenter(new ScrollPane(ta)); mainPane.setTop(topPane); // Create a scene and place it in the stage Scene scene = new Scene(mainPane, 450, 200); primaryStage.setTitle("BMI Client"); // Set the stage title primaryStage.setScene(scene); // Place the scene in the stage primaryStage.show(); // Display the stage connect(); } private void connect() { try { // Create a socket to connect to the server Socket socket = new Socket("localhost", 8000); // Create an input stream to receive data from the server DataInputStream fromServer = new DataInputStream(socket.getInputStream()); Reader reader = new InputStreamReader(fromServer); bufReader = new BufferedReader(reader); // Create an output stream to send data to the server toServer = new DataOutputStream(socket.getOutputStream()); } catch (IOException ex) { ta.appendText(ex.toString() + '\n'); } } private void transceive() { double weight = new Double(tf1.getText()); double height = new Double(tf2.getText()); ta.appendText("Weight: " + weight + '\n'); ta.appendText("Height: " + height + '\n'); try { toServer.writeDouble(weight); toServer.writeDouble(height); toServer.flush(); String answer = bufReader.readLine(); ta.appendText(answer + '\n'); } catch (IOException ex) { ta.appendText(ex.toString() + '\n'); } } /** * @param args the command line arguments */ public static void main(String[] args) { launch(args); } }
package com.esrinea.dotGeo.tracking.service.component.alert; import java.util.List; import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.esrinea.dotGeo.tracking.model.component.alert.entity.Alert; import com.esrinea.dotGeo.tracking.model.component.device.entity.Device; import com.esrinea.dotGeo.tracking.service.component.device.DeviceServiceTest; public class AlertServiceTest extends DeviceServiceTest { @Autowired private AlertService alertService; @Test public void testFindNonRetiredAlerts(){ Device device = deviceService.find(1, false); List<Alert> alerts = alertService.find(device.getDeviceType().getId(), false); Assert.assertNotNull(alerts); Assert.assertFalse(alerts.isEmpty()); } }
package io.mifos.reporting.api.v1.domain; public class Sample { private Object identifier; private Object payload; public Sample(){ super(); } public static Sample create(String xxxx, String yyy) { return new Sample(); } public void setIdentifier(Object identifier) { this.identifier = identifier; } public void setPayload(String payload) { this.payload = payload; } }
/** * Copyright 2016 EIS Co., Ltd. All rights reserved. */ package Java003; /** * @author 笹田 裕介 <br /> * 改行'*'表示 <br /> * 行ごとに'*'を1つずつ増やしながら表示する <br /> * 更新履歴 2016/2/20(更新者):笹田 裕介:新規作成 <br /> */ public class Test13 { /** * メインメソッド <br /> * '*'を増やしながら改行表示 <br /> * * @param args 実行時引数 */ public static void main( String[] args ) { // 行ごとに*を1つずつ増やしながら表示する for ( int i = 1; i <= 10; i++ ) { for ( int j = 1; j <= i; j++ ) { System.out.print( '*' ); } // 改行 System.out.println(); } } }
package me.levylin.easymemo.ui.main.dagger; import dagger.Component; import me.levylin.easymemo.AppComponent; import me.levylin.easymemo.ui.main.MainActivity; import me.levylin.easymemo.utils.dagger.ActivityScoped; /** * 主模块 * Created by LinXin on 2017/1/18 17:18. */ @ActivityScoped @Component(dependencies = AppComponent.class, modules = {MainModule.class}) public interface MainComponent { void inject(MainActivity activity); }
package com.alexfu.sqlitequerybuilder; public interface Select { public SelectFrom from(String table); }
package ch.mitti.kochkurve; import ch.aplu.turtle.*; public class TurtleTest { public TurtleTest() { Turtle tu = new Turtle(); // Turtle im Zentrum des Frames erzeugt tu.hideTurtle(); // Turtle unsichtbar tu.setX(50); // Turtle auf X= 100 setzen tu.setY(-50); // Turtle auf Y= -50 setzen tu.forward(10); // zeichne 10 Einheiten vorwärts tu.right(45); // drehe um 45 Grad nach rechts tu.forward(20); // zeichne 20 Einheiten vorwärts tu.left(90); // drehe 90 Grad nach links tu.back(100); // zeichne 100 Einheiten rückwärts tu.setPos(20,20); // Turtle auf X= 20, Y=20 setzen tu.forward(20); // zeichne 20 Einheiten vorwärts } /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub TurtleTest t = new TurtleTest(); } }
package ideablog.controller; import com.fasterxml.jackson.databind.ObjectMapper; import ideablog.aop.SystemControllerLog; import ideablog.model.Blog; import ideablog.service.IBlogService; import ideablog.utils.MyTime; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.List; import static ideablog.utils.Constant.HEADICONVIRTUALPATH; import static org.springframework.web.bind.annotation.RequestMethod.GET; import static org.springframework.web.bind.annotation.RequestMethod.POST; @Controller public class BlogManageController { @Resource private IBlogService blogService; @RequestMapping(value = "/blog_manage", method = GET) public String blogManage(){ return "blog_manage"; } @RequestMapping(value = "/showUserBlogs.do", method = POST)//获取用户博客 public void showUserBlogs(HttpSession session, HttpServletResponse response) throws IOException { response.setCharacterEncoding("UTF-8"); List<Blog> blogList = this.blogService.selectNewBlogsByUserId(Long.parseLong(session.getAttribute("userId").toString())); String respJson; ObjectMapper mapper = new ObjectMapper(); respJson = mapper.writeValueAsString(blogList); response.getWriter().write(respJson); response.getWriter().close(); } @RequestMapping(value = "/switchBlogStatus.do", method = POST)//切换博客发布状态 public void switchBlogStatus(HttpServletRequest request, HttpServletResponse response) throws IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); Boolean sw; sw = this.blogService.switchStatusById(Long.parseLong(request.getParameter("blogId")), Integer.parseInt(request.getParameter("status"))); if(sw) { System.out.println("博客发布状态切换成功!"); response.getWriter().write("博客发布状态切换成功!"); response.getWriter().close(); } else { System.out.println("博客发布状态切换失败!"); response.getWriter().write("博客发布状态切换失败!"); response.getWriter().close(); } } @RequestMapping(value = "/editBlogPage", method = GET)//编辑博客页面 public String toEditBlogPage(HttpSession session, HttpServletRequest request) throws UnsupportedEncodingException { request.setCharacterEncoding("UTF-8"); session.setAttribute("blogId", request.getParameter("blogId")); return "redirect:/edit_blog"; } @RequestMapping(value = "/edit_blog")//编辑博客页面 public String editBlogPage() { return "edit_blog"; } @RequestMapping(value = "/showBlogById.do", method = POST)//获取博客 public void showBlogById(HttpSession session, HttpServletResponse response) throws IOException { response.setCharacterEncoding("UTF-8"); Blog blog = this.blogService.selectBlogById(Long.parseLong(session.getAttribute("blogId").toString())); if(blog != null) { blog.setHeadIconPath(HEADICONVIRTUALPATH + blog.getUserId() + "_headIcon.png"); ObjectMapper mapper = new ObjectMapper(); String strJson = mapper.writeValueAsString(blog); response.getWriter().write(strJson); response.getWriter().close(); } } @RequestMapping(value = "/updateBlog.do", method = POST)//更新博客 public String updateBlog(HttpSession session, HttpServletRequest request) throws Exception { request.setCharacterEncoding("UTF-8"); Boolean update; update = this.blogService.updateBlogById(Long.parseLong(session.getAttribute("blogId").toString()), request.getParameter("blogtitle"), request.getParameter("blogtag"), request.getParameter("blogcontent"), MyTime.getMyTime()); if(update) { System.out.println("博客更新成功!"); request.setAttribute("status", "博客更新成功!"); } else { System.out.println("博客更新失败!"); request.setAttribute("status", "博客更新失败!"); } return "edit_blog"; } @RequestMapping(value = "/deleteBlog.do", method = POST)//删除博客 @SystemControllerLog(description = "删除博客") public void deleteBlog(HttpServletRequest request, HttpServletResponse response) throws IOException { request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); Boolean delete; delete = this.blogService.deleteBlogById(Long.parseLong(request.getParameter("blogId"))); if(delete) { System.out.println("博客删除成功!"); response.getWriter().write("博客删除成功!"); response.getWriter().close(); } else { System.out.println("博客删除失败!"); response.getWriter().write("博客删除失败!"); response.getWriter().close(); } } }
package com.framgia.fsalon.screen.booking; import android.content.Context; import android.databinding.BaseObservable; import android.databinding.Bindable; import android.databinding.DataBindingUtil; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.ViewGroup; import com.framgia.fsalon.BR; import com.framgia.fsalon.BaseRecyclerViewAdapter; import com.framgia.fsalon.R; import com.framgia.fsalon.data.model.BookingRender; import com.framgia.fsalon.databinding.ItemTimeBookingBinding; import java.util.List; /** * Created by MyPC on 20/07/2017. */ public class TimeBookingAdapter extends BaseRecyclerViewAdapter<BookingRender, TimeBookingAdapter .ViewHolder> { private List<BookingRender> mData; private BookingViewModel mViewModel; private int mSelectedPosition = -1; protected TimeBookingAdapter(@NonNull Context context, List<BookingRender> data, BookingViewModel viewModel) { super(context); mData = data; mViewModel = viewModel; } public BookingRender getItem(int position) { return position < 0 ? null : mData.get(position); } public void selectedPosition(int position) { if (position < 0) { return; } mSelectedPosition = position; notifyDataSetChanged(); } @Override public void onUpdatePage(List<BookingRender> data) { if (data == null) { return; } mData.addAll(data); notifyDataSetChanged(); } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { ItemTimeBookingBinding binding = DataBindingUtil.inflate(LayoutInflater.from(parent.getContext()), R.layout.item_time_booking, parent, false); return new ViewHolder(binding, mViewModel); } @Override public void onBindViewHolder(ViewHolder holder, int position) { holder.bindData(mData.get(position)); } @Override public int getItemCount() { return mData == null ? 0 : mData.size(); } public class ViewHolder extends RecyclerView.ViewHolder { private ItemTimeBookingBinding mBinding; private BookingViewModel mViewModel; public ViewHolder(ItemTimeBookingBinding binding, BookingViewModel viewModel) { super(binding.getRoot()); mBinding = binding; mViewModel = viewModel; } void bindData(BookingRender timeBooking) { if (timeBooking == null) { return; } ViewHolderModel model = new ViewHolderModel(timeBooking, mViewModel, getAdapterPosition(), mSelectedPosition == getAdapterPosition()); mBinding.setViewHolderModel(model); mBinding.executePendingBindings(); } } public class ViewHolderModel extends BaseObservable { private BookingRender mTimeBooking; private BookingViewModel mViewModel; private int mPosition; private boolean mIsSelected; public ViewHolderModel(BookingRender timeBooking, BookingViewModel viewModel, int position, boolean isSelected) { mTimeBooking = timeBooking; mViewModel = viewModel; mPosition = position; mIsSelected = isSelected; } @Bindable public BookingRender getTimeBooking() { return mTimeBooking; } public void setTimeBooking(BookingRender timeBooking) { mTimeBooking = timeBooking; notifyPropertyChanged(BR.timeBooking); } @Bindable public BookingViewModel getViewModel() { return mViewModel; } public void setViewModel(BookingViewModel viewModel) { mViewModel = viewModel; notifyPropertyChanged(BR.viewModel); } @Bindable public int getPosition() { return mPosition; } public void setPosition(int position) { mPosition = position; notifyItemChanged(BR.position); } @Bindable public boolean isSelected() { return mIsSelected; } public void setSelected(boolean selected) { mIsSelected = selected; notifyPropertyChanged(BR.selected); } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package system_monitor; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.ServerSocket; import java.net.Socket; import javax.swing.JLabel; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import java.util.Vector; import javax.swing.table.DefaultTableModel; import sun.jdbc.odbc.*; import java.sql.*; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import java.sql.Connection; import java.sql.DriverManager; public class ServerForm extends javax.swing.JFrame { private ServerSocket server; private int port =5050; Object id; ServerSocket orderupdate; public ServerForm() { initComponents(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jButton3 = new javax.swing.JButton(); jButton5 = new javax.swing.JButton(); TabPane = new javax.swing.JTabbedPane(); jScrollPane1 = new javax.swing.JScrollPane(); jTable1 = new javax.swing.JTable(); jScrollPane2 = new javax.swing.JScrollPane(); jTableOrderSend = new javax.swing.JTable(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { formWindowClosing(evt); } }); jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 18)); jLabel1.setText("Admin Home"); jButton3.setText("Cancel"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jButton5.setText("Refresh"); jButton5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton5ActionPerformed(evt); } }); TabPane.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { TabPaneMouseClicked(evt); } }); jTable1.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "User name", "Operation", "Date Time" } )); jScrollPane1.setViewportView(jTable1); TabPane.addTab("Hardware Moniitor", jScrollPane1); jTableOrderSend.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "user name", "process", "date time" } )); jScrollPane2.setViewportView(jTableOrderSend); TabPane.addTab("Software_monitor", jScrollPane2); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addGap(121, 121, 121) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 447, Short.MAX_VALUE) .addComponent(jButton5) .addGap(61, 61, 61) .addComponent(jButton3) .addGap(53, 53, 53)) .addComponent(TabPane, javax.swing.GroupLayout.DEFAULT_SIZE, 961, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(29, 29, 29) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jLabel1) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jButton3) .addComponent(jButton5))) .addGap(42, 42, 42) .addComponent(TabPane, javax.swing.GroupLayout.DEFAULT_SIZE, 456, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed this.dispose(); // TODO add your handling code here: }//GEN-LAST:event_jButton3ActionPerformed private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed try { DefaultTableModel dfm=(DefaultTableModel) jTableOrderSend.getModel(); ((DefaultTableModel)jTableOrderSend.getModel()).setNumRows(0); jTableOrderSend.setModel(dfm); Class.forName("com.mysql.jdbc.Driver"); String user = "root"; String password = "root"; Connection connect = DriverManager.getConnection( "jdbc:mysql://localhost:3306/system_monitor",user,password); String query = "select * from software_details"; if (connect!=null) { Statement stmt = connect.createStatement(); ResultSet rs; rs= stmt.executeQuery(query); while(rs.next()) { Vector v=new Vector(); v.addElement(rs.getString(1)); v.addElement(rs.getString(2)); v.addElement(rs.getString(3)); dfm.addRow(v); //System.out.println(jTable1.getSelectedRow()); // System.out.println( JTable1.getModel().getValueAt(1, 1)); } } } catch(Exception ex) { ex.printStackTrace(); } try { DefaultTableModel dfm=(DefaultTableModel) jTable1.getModel(); ((DefaultTableModel)jTable1.getModel()).setNumRows(0); jTable1.setModel(dfm); Class.forName("com.mysql.jdbc.Driver"); String user = "root"; String password = "root"; Connection connect = DriverManager.getConnection( "jdbc:mysql://localhost:3306/system_monitor",user,password); String query = "select * from hardware_monitor"; if (connect!=null) { Statement stmt = connect.createStatement(); ResultSet rs; rs= stmt.executeQuery(query); while(rs.next()) { Vector v=new Vector(); v.addElement(rs.getString(1)); v.addElement(rs.getString(2)); v.addElement(rs.getString(3)); dfm.addRow(v); //System.out.println(jTable1.getSelectedRow()); // System.out.println( JTable1.getModel().getValueAt(1, 1)); } } } catch(Exception e) { e.printStackTrace(); } }//GEN-LAST:event_jButton5ActionPerformed private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing // TODO add your handling code here: try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection connect1 = DriverManager .getConnection( "jdbc:odbc:Restaurent_dsn"); Statement st=connect1.createStatement(); st.executeUpdate("delete from order_final"); connect1.commit(); } catch(Exception ex) { ex.printStackTrace(); } try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection connect2 = DriverManager .getConnection( "jdbc:odbc:Restaurent_dsn"); Statement st1=connect2.createStatement(); st1.executeUpdate("delete from Order_Send"); connect2.commit(); } catch(Exception ex) { ex.printStackTrace(); } }//GEN-LAST:event_formWindowClosing private void TabPaneMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_TabPaneMouseClicked // TODO add your handling code here: try { DefaultTableModel dfm=(DefaultTableModel) jTableOrderSend.getModel(); ((DefaultTableModel)jTableOrderSend.getModel()).setNumRows(0); jTableOrderSend.setModel(dfm); Class.forName("com.mysql.jdbc.Driver"); String user = "root"; String password = "root"; Connection connect = DriverManager.getConnection( "jdbc:mysql://localhost:3306/system_monitor",user,password); String query = "select * from software_details"; if (connect!=null) { Statement stmt = connect.createStatement(); ResultSet rs; rs= stmt.executeQuery(query); while(rs.next()) { Vector v=new Vector(); v.addElement(rs.getString(1)); v.addElement(rs.getString(2)); v.addElement(rs.getString(3)); dfm.addRow(v); //System.out.println(jTable1.getSelectedRow()); // System.out.println( JTable1.getModel().getValueAt(1, 1)); } } } catch(Exception ex) { ex.printStackTrace(); } try { DefaultTableModel dfm=(DefaultTableModel) jTable1.getModel(); ((DefaultTableModel)jTable1.getModel()).setNumRows(0); jTable1.setModel(dfm); Class.forName("com.mysql.jdbc.Driver"); String user = "root"; String password = "root"; Connection connect = DriverManager.getConnection( "jdbc:mysql://localhost:3306/system_monitor",user,password); String query = "select * from hardware_monitor"; if (connect!=null) { Statement stmt = connect.createStatement(); ResultSet rs; rs= stmt.executeQuery(query); while(rs.next()) { Vector v=new Vector(); v.addElement(rs.getString(1)); v.addElement(rs.getString(2)); v.addElement(rs.getString(3)); dfm.addRow(v); //System.out.println(jTable1.getSelectedRow()); // System.out.println( JTable1.getModel().getValueAt(1, 1)); } } } catch(Exception e) { e.printStackTrace(); } }//GEN-LAST:event_TabPaneMouseClicked /** * @param args the command line arguments */ public static void main( String []arg) { java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ServerForm().setVisible(true); } }); } public void handleConnection() { System.out.println("Waiting for client message"); while(true) { try { Socket socket=server.accept(); new ConnectionHandlernew(socket); } catch (Exception e) { e.printStackTrace(); } } } // Variables declaration - do not modify//GEN-BEGIN:variables public static javax.swing.JTabbedPane TabPane; private javax.swing.JButton jButton3; private javax.swing.JButton jButton5; private javax.swing.JLabel jLabel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JScrollPane jScrollPane2; public static javax.swing.JTable jTable1; public static javax.swing.JTable jTableOrderSend; // End of variables declaration//GEN-END:variables public static void refresh_Admin_Table() { try { DefaultTableModel dfm=(DefaultTableModel) jTableOrderSend.getModel(); ((DefaultTableModel)jTableOrderSend.getModel()).setNumRows(0); jTableOrderSend.setModel(dfm); Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection connect = DriverManager .getConnection( "jdbc:odbc:Restaurent_dsn"); String query = "select * from Order_Send"; if (connect!=null) { Statement stmt = connect.createStatement(); ResultSet rs; rs= stmt.executeQuery(query); while(rs.next()) { Vector v=new Vector(); v.addElement(rs.getString(1)); v.addElement(rs.getString(2)); v.addElement(rs.getString(3)); v.addElement(rs.getString(4)); v.addElement(rs.getString(5)); v.addElement(rs.getString(6)); v.addElement(rs.getString(7)); dfm.addRow(v); //System.out.println(jTable1.getSelectedRow()); // System.out.println( JTable1.getModel().getValueAt(1, 1)); } } } catch(Exception ex) { ex.printStackTrace(); } try { DefaultTableModel dfm=(DefaultTableModel) jTable1.getModel(); ((DefaultTableModel)jTable1.getModel()).setNumRows(0); jTable1.setModel(dfm); Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection connect = DriverManager .getConnection( "jdbc:odbc:Restaurent_dsn"); String query = "select * from order_final"; if (connect!=null) { Statement stmt = connect.createStatement(); ResultSet rs; rs= stmt.executeQuery(query); while(rs.next()) { Vector v=new Vector(); v.addElement(rs.getString(1)); v.addElement(rs.getString(2)); v.addElement(rs.getString(3)); v.addElement(rs.getString(4)); v.addElement(rs.getString(5)); v.addElement(rs.getString(6)); v.addElement(rs.getString(7)); dfm.addRow(v); //System.out.println(jTable1.getSelectedRow()); // System.out.println( JTable1.getModel().getValueAt(1, 1)); } } } catch(Exception e) { e.printStackTrace(); } } } class ConnectionHandlernew implements Runnable { int time=0; public static Object[][] Data; private Socket socket; private BufferedReader input; String[] columnNames={ "Customer Name","Customer Table","Item Name","Item Quantity","Total Price" }; public ConnectionHandlernew(Socket socket) { this.socket=socket; Thread t=new Thread(this); t.start(); try{ t.sleep(1000);} catch(Exception e){} } public void run() { try { // DataInputStream dis=new DataInputStream (socket.getInputStream()); this.input=new BufferedReader(new InputStreamReader(this.socket.getInputStream())); String message=input.readLine(); String message_table_no=input.readLine(); String message_item_name=input.readLine(); String message_inst=input.readLine(); String message_quantity=input.readLine(); String message_total=input.readLine(); String selection=input.readLine(); String item_status="Order Pending"; Data=new Object[][]{ {message,message_table_no,message_item_name,message_inst,message_quantity,message_total} }; System.out.println("Cust Name :"+message); System.out.println("Cust Table: "+message_table_no); System.out.println("Item Name: "+message_item_name); System.out.println("Special Instruiction: "+message_inst); System.out.println("Item Quantity : "+message_quantity); System.out.println("Total Price : "+message_total); Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection connect1 = DriverManager .getConnection( "jdbc:odbc:Restaurent_dsn"); Statement st=connect1.createStatement(); st.executeUpdate("insert into order_final values ((SELECT ISNULL(MAX(Order_Id)+1,0) FROM dbo.order_final WITH(SERIALIZABLE, UPDLOCK)), '"+ message + "','"+ message_table_no+ "','"+ message_item_name +"','"+ message_quantity +"','"+ message_total +"','"+ message_inst +"','"+selection+"') "); connect1.commit(); int id=0; try { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:Restaurent_dsn"); Connection con2=DriverManager.getConnection("jdbc:odbc:Restaurent_dsn"); Statement st2=con.createStatement(); Statement st1=con2.createStatement(); //st.executeUpdate("insert into FeedBack_Details values('"+cust_name+"','"+feedback+"','"+rating+"')"); ResultSet rs1; ResultSet rs; rs1=st1.executeQuery("select Item_Name from order_final "); String item_name; while(rs1.next()) { item_name=rs1.getString("Item_Name"); rs= st2.executeQuery("select * from Time where Item_Name='"+item_name+"'"); while(rs.next()) { time=time+rs.getInt(2); //System.out.println(Table.getSelectedRow()); // System.out.println( Table.getModel().getValueAt(1, 1)); } } } catch(Exception e) { e.printStackTrace(); } OutputStream os=socket.getOutputStream(); OutputStreamWriter osw=new OutputStreamWriter(os); BufferedWriter bw=new BufferedWriter(osw); String time_temp=""+time; bw.write(time_temp); //String temp_id=""+id; //bw.write(temp_id); System.out.println("Time send to customer"); bw.flush(); input.close(); socket.close(); // Statement st1=connect1.createStatement(); /* st1.executeUpdate("insert into order_permanent values ( '"+ message + "','"+ message_table_no+ "','"+ message_item_name +"','"+ message_quantity +"','"+ message_total +"','"+ message_inst +"','"+selection+"') "); connect1.commit();*/ DefaultTableModel dfm=(DefaultTableModel) ServerForm.jTable1.getModel(); ((DefaultTableModel)ServerForm.jTable1.getModel()).setNumRows(0); ServerForm.jTable1.setModel(dfm); Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection connect = DriverManager .getConnection( "jdbc:odbc:Restaurent_dsn"); String query = "select * from order_final"; if (connect!=null) { Statement stmt = connect.createStatement(); ResultSet rs; rs= stmt.executeQuery(query); while(rs.next()) { Vector v=new Vector(); v.addElement(rs.getString(1)); v.addElement(rs.getString(2)); v.addElement(rs.getString(3)); v.addElement(rs.getString(4)); v.addElement(rs.getString(5)); v.addElement(rs.getString(6)); v.addElement(rs.getString(7)); v.addElement(rs.getString(8)); dfm.addRow(v); //System.out.println(jTable1.getSelectedRow()); // System.out.println( JTable1.getModel().getValueAt(1, 1)); } } } catch(Exception e) { e.printStackTrace(); } System.out.println("Waiting for client message"); } }
package StageConstructor; import trash.RoomObjectParent; public class CollisionsWorldLayer extends RoomObjectParent { private Grid grid; @Override public void start() { grid = new Grid(32, 32, 20, 20); addObject(grid); } }
package com.jyn.language.设计模式.三种工厂.工厂方法; /** * 奶茶 */ public abstract class Tea { private String name; private String price; public Tea(String name, String price) { this.name = name; this.price = price; } }
/* * Created on 08-Jun-2004 * Created by Paul Gardner * Copyright (C) 2004, 2005, 2006 Aelitis, All Rights Reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * AELITIS, SAS au capital de 46,603.30 euros * 8 Allee Lenotre, La Grille Royale, 78600 Le Mesnil le Roi, France. * */ package org.minicastle.jce.provider; /** * @author parg * */ import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.security.InvalidKeyException; import java.security.Key; import java.security.KeyFactorySpi; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import java.security.interfaces.DSAPrivateKey; import java.security.interfaces.DSAPublicKey; import java.security.interfaces.RSAPrivateCrtKey; import java.security.interfaces.RSAPrivateKey; import java.security.interfaces.RSAPublicKey; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; import java.security.spec.PKCS8EncodedKeySpec; import java.security.spec.RSAPrivateCrtKeySpec; import java.security.spec.RSAPrivateKeySpec; import java.security.spec.RSAPublicKeySpec; import java.security.spec.X509EncodedKeySpec; import javax.crypto.interfaces.DHPrivateKey; import javax.crypto.interfaces.DHPublicKey; import org.minicastle.asn1.ASN1Sequence; import org.minicastle.asn1.DERInputStream; import org.minicastle.asn1.x509.*; import org.minicastle.asn1.x9.X9ObjectIdentifiers; import org.minicastle.asn1.pkcs.PKCSObjectIdentifiers; import org.minicastle.asn1.pkcs.PrivateKeyInfo; import org.minicastle.jce.interfaces.ElGamalPrivateKey; import org.minicastle.jce.interfaces.ElGamalPublicKey; import org.minicastle.jce.spec.ECPrivateKeySpec; import org.minicastle.jce.spec.ECPublicKeySpec; import org.gudy.azureus2.core3.util.Debug; public abstract class JDKKeyFactory extends KeyFactorySpi { protected KeySpec engineGetKeySpec( Key key, Class spec) throws InvalidKeySpecException { if (spec.isAssignableFrom(PKCS8EncodedKeySpec.class) && key.getFormat().equals("PKCS#8")) { return new PKCS8EncodedKeySpec(key.getEncoded()); } else if (spec.isAssignableFrom(X509EncodedKeySpec.class) && key.getFormat().equals("X.509")) { return new X509EncodedKeySpec(key.getEncoded()); } else if (spec.isAssignableFrom(RSAPublicKeySpec.class) && key instanceof RSAPublicKey) { RSAPublicKey k = (RSAPublicKey)key; return new RSAPublicKeySpec(k.getModulus(), k.getPublicExponent()); } else if (spec.isAssignableFrom(RSAPrivateKeySpec.class) && key instanceof RSAPrivateKey) { RSAPrivateKey k = (RSAPrivateKey)key; return new RSAPrivateKeySpec(k.getModulus(), k.getPrivateExponent()); } else if (spec.isAssignableFrom(RSAPrivateCrtKeySpec.class) && key instanceof RSAPrivateCrtKey) { RSAPrivateCrtKey k = (RSAPrivateCrtKey)key; return new RSAPrivateCrtKeySpec( k.getModulus(), k.getPublicExponent(), k.getPrivateExponent(), k.getPrimeP(), k.getPrimeQ(), k.getPrimeExponentP(), k.getPrimeExponentQ(), k.getCrtCoefficient()); } throw new RuntimeException("not implemented yet " + key + " " + spec); } protected Key engineTranslateKey( Key key) throws InvalidKeyException { if (key instanceof RSAPublicKey) { return new JCERSAPublicKey((RSAPublicKey)key); } else if (key instanceof RSAPrivateCrtKey) { //return new JCERSAPrivateCrtKey((RSAPrivateCrtKey)key); } else if (key instanceof RSAPrivateKey) { //return new JCERSAPrivateKey((RSAPrivateKey)key); } else if (key instanceof DHPublicKey) { //return new JCEDHPublicKey((DHPublicKey)key); } else if (key instanceof DHPrivateKey) { //return new JCEDHPrivateKey((DHPrivateKey)key); } else if (key instanceof DSAPublicKey) { //return new JDKDSAPublicKey((DSAPublicKey)key); } else if (key instanceof DSAPrivateKey) { //return new JDKDSAPrivateKey((DSAPrivateKey)key); } else if (key instanceof ElGamalPublicKey) { //return new JCEElGamalPublicKey((ElGamalPublicKey)key); } else if (key instanceof ElGamalPrivateKey) { //return new JCEElGamalPrivateKey((ElGamalPrivateKey)key); } throw new InvalidKeyException("key type unknown"); } static PublicKey createPublicKeyFromDERStream( InputStream in) throws IOException { return createPublicKeyFromPublicKeyInfo( new SubjectPublicKeyInfo((ASN1Sequence)(new DERInputStream(in).readObject()))); } static PublicKey createPublicKeyFromPublicKeyInfo( SubjectPublicKeyInfo info) { AlgorithmIdentifier algId = info.getAlgorithmId(); if (algId.getObjectId().equals(PKCSObjectIdentifiers.rsaEncryption) || algId.getObjectId().equals(X509ObjectIdentifiers.id_ea_rsa)) { return new JCERSAPublicKey(info); } else if (algId.getObjectId().equals(X9ObjectIdentifiers.id_ecPublicKey)) { return new JCEECPublicKey(info); } else { throw new RuntimeException("algorithm identifier in key not recognised"); } } static PrivateKey createPrivateKeyFromDERStream( InputStream in) throws IOException { return createPrivateKeyFromPrivateKeyInfo( new PrivateKeyInfo((ASN1Sequence)(new DERInputStream(in).readObject()))); } /** * create a private key from the given public key info object. */ static PrivateKey createPrivateKeyFromPrivateKeyInfo( PrivateKeyInfo info) { AlgorithmIdentifier algId = info.getAlgorithmId(); /* if (algId.getObjectId().equals(PKCSObjectIdentifiers.rsaEncryption)) { return new JCERSAPrivateCrtKey(info); } else if (algId.getObjectId().equals(PKCSObjectIdentifiers.dhKeyAgreement)) { return new JCEDHPrivateKey(info); } else if (algId.getObjectId().equals(OIWObjectIdentifiers.elGamalAlgorithm)) { return new JCEElGamalPrivateKey(info); } else if (algId.getObjectId().equals(X9ObjectIdentifiers.id_dsa)) { return new JDKDSAPrivateKey(info); } else */ if (algId.getObjectId().equals(X9ObjectIdentifiers.id_ecPublicKey)) { return new JCEECPrivateKey(info); } else { throw new RuntimeException("algorithm identifier in key not recognised"); } } public static class EC extends JDKKeyFactory { String algorithm; public EC() throws NoSuchAlgorithmException { this("EC"); // PARG - bail if we're constructing an X509 cert for SSL as the BC SSL impl is old and doesn't have recent named curves // If we allow this to continue it borks constructing the EC public key and takes the whole SSL process down with // utimately a // Caused by: java.io.IOException: subject key, java.lang.NullPointerException // at sun.security.x509.X509Key.parse(X509Key.java:157) // at sun.security.x509.CertificateX509Key.<init>(CertificateX509Key.java:58) // at sun.security.x509.X509CertInfo.parse(X509CertInfo.java:688) // at sun.security.x509.X509CertInfo.<init>(X509CertInfo.java:152) try{ StackTraceElement[] elements = new Exception().getStackTrace(); boolean ssl = false; boolean x509 = false; for ( StackTraceElement elt: elements ){ String name = elt.getClassName() + "." + elt.getMethodName(); if ( name.contains( "SSLSocketFactory" ) || name.contains( "KeyStore.load" )){ ssl = true; }else if ( name.contains( "X509" )){ x509 = true; } } if( ssl && x509 ){ //Debug.out( "Hacking SSL EC" ); throw( new NoSuchAlgorithmException()); } }catch( NoSuchAlgorithmException e ){ throw( e ); }catch( Throwable e ){ Debug.out( e ); } } public EC( String algorithm) { this.algorithm = algorithm; } protected PrivateKey engineGeneratePrivate( KeySpec keySpec) throws InvalidKeySpecException { if (keySpec instanceof PKCS8EncodedKeySpec) { try { return JDKKeyFactory.createPrivateKeyFromDERStream( new ByteArrayInputStream(((PKCS8EncodedKeySpec)keySpec).getEncoded())); } catch (Exception e) { throw new InvalidKeySpecException(e.toString()); } } else if (keySpec instanceof ECPrivateKeySpec) { return new JCEECPrivateKey(algorithm, (ECPrivateKeySpec)keySpec); } throw new InvalidKeySpecException("Unknown KeySpec type."); } protected PublicKey engineGeneratePublic( KeySpec keySpec) throws InvalidKeySpecException { if (keySpec instanceof X509EncodedKeySpec) { try { return JDKKeyFactory.createPublicKeyFromDERStream( new ByteArrayInputStream(((X509EncodedKeySpec)keySpec).getEncoded())); } catch (Exception e) { throw new InvalidKeySpecException(e.toString()); } } else if (keySpec instanceof ECPublicKeySpec) { return new JCEECPublicKey(algorithm, (ECPublicKeySpec)keySpec); } throw new InvalidKeySpecException("Unknown KeySpec type."); } } public static class ECDSA extends EC { public ECDSA() { super("ECDSA"); } } }
package com.ipartek.formacion.nombreproyecto.enumeraciones; import java.util.Scanner; public enum Vaso { CHUPITO(100), TUBO(250), KATXI(999), ZURITO(200), KUBATA(400), COPA(120), TXIKITO(200); private int miliLitros; /** * Centimos */ private static final float PRECIO_MILILITRO = 1.5f; private Vaso(int milis) { this.miliLitros = milis; } public float calcularPrecio(){ return PRECIO_MILILITRO * miliLitros; } public String servir(){ return "Esta es su bebida "; } public static void mostrarListado(){ for (int i=0; i < Vaso.values().length; i++){ System.out.println( i + ". " + Vaso.values()[i] ); } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); mostrarListado(); System.out.println("Seleccione su recipiente"); int op = scanner.nextInt(); System.out.println("Ha seleccionado " + op); Vaso vasoSeleccionado = Vaso.values()[op]; System.out.println("Precio de su consumicion "); System.out.println( vasoSeleccionado.calcularPrecio()/100 + " €" ); } }
package com.tinygame.cmdhandler; import com.google.protobuf.GeneratedMessageV3; import io.netty.channel.ChannelHandlerContext; public interface ICmdHandler<TCmd extends GeneratedMessageV3> { /** * 处理指令 * */ void handler(ChannelHandlerContext ctx,TCmd msg); }
package realtime.bean; import java.math.BigDecimal; import com.alibaba.fastjson.annotation.JSONField; import realtime.bean.common.BaseStock; public class BaiduStock extends BaseStock { // 股票代码 private String stockCode; // 涨幅(要乘以100%) private BigDecimal increase; @JSONField(name = "STOCK_CODE") public String getStockCode() { return stockCode; } @JSONField(name = "STOCK_CODE") public void setStockCode(String stockCode) { this.stockCode = stockCode; } @JSONField(name = "INCREASE") public BigDecimal getIncrease() { return increase; } @JSONField(name = "INCREASE") public void setIncrease(BigDecimal increase) { this.increase = increase; } }
package edu.miu.utils; import edu.miu.model.Credit; import edu.miu.model.Movie; import edu.miu.model.ProductionCompany; import lombok.Getter; import java.util.Comparator; import java.util.List; import java.util.function.BiPredicate; import java.util.function.Function; import java.util.stream.Collectors; /** * @author Rimon Mostafiz */ public class InMemoryDatabase { private static final List<String[]> creditRows; private static final List<String[]> movieRows; private final static String CREDIT_FILE_NAME = "data/tmdb_5000_credits.csv"; private final static String MOVIE_FILE_NAME = "data/tmdb_5000_movies.csv"; static { creditRows = CSVFileReader.read(CREDIT_FILE_NAME); movieRows = CSVFileReader.read(MOVIE_FILE_NAME); } @Getter private List<Movie> movies; @Getter private List<Credit> credits; @Getter private List<ProductionCompany> allProductionCompany; private InMemoryDatabase() { initialize(); } public static InMemoryDatabase getInstance() { return Database.INSTANCE_HOLDER; } private void initialize() { initMovies(); initCredits(); //TODO: fix me //initProductionCompany(); } private void initProductionCompany() { allProductionCompany = movies.parallelStream() .flatMap(m -> m.getProductionCompanies().stream()) .collect(Collectors.toSet()) .stream() .sorted(Comparator.comparing((ProductionCompany::getId))) .collect(Collectors.toList()); BiPredicate<Movie, ProductionCompany> isProducedBy = (movie, pCompany) -> movie.getProductionCompanies() .stream() .filter(pc -> pc.getId().equals(pCompany.getId())).count() >= 1; Function<ProductionCompany, List<Movie>> movieByPc = company -> movies.parallelStream() .filter(movie -> isProducedBy.test(movie, company)) .collect(Collectors.toList()); allProductionCompany.forEach(pc -> pc.getMovieProduced().addAll(movieByPc.apply(pc))); } private void initMovies() { movies = movieRows.stream() .map(Movie::of) .collect(Collectors.toList()); } private void initCredits() { credits = creditRows.stream() .map(Credit::of) .collect(Collectors.toList()); } private static class Database { private static final InMemoryDatabase INSTANCE_HOLDER = new InMemoryDatabase(); } }
package com.cd.hrm.service.impl; import com.cd.hrm.domain.CourseType; import com.cd.hrm.mapper.CourseTypeMapper; import com.cd.hrm.service.ICourseTypeService; import com.baomidou.mybatisplus.service.impl.ServiceImpl; import org.springframework.stereotype.Service; /** * <p> * 课程目录 服务实现类 * </p> * * @author cd * @since 2019-09-01 */ @Service public class CourseTypeServiceImpl extends ServiceImpl<CourseTypeMapper, CourseType> implements ICourseTypeService { }
package com.dassa.service; import java.util.ArrayList; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.dassa.mapper.DriverBoardMapper; import com.dassa.vo.FaqPageData; import com.dassa.vo.FaqVO; import com.dassa.vo.NoticePageData; import com.dassa.vo.NoticeVO; import com.dassa.vo.QuestionPageData; import com.dassa.vo.QuestionVO; import com.dassa.vo.SearchNoticeVO; import com.dassa.vo.SearchQuestionVO; @Service("driverBoardService") public class DriverBoardService { @Resource private DriverBoardMapper driverBoardMapper; public NoticePageData selectNoticeList(int reqPage) throws Exception { // 페이지 당 게시물 수 int numPerPage = 5; // 총 게시물 수 구하기 int totalCount = driverBoardMapper.totalCount(); // 총 페이지 수 구하기 int totalPage = (totalCount%numPerPage== 0)?(totalCount/numPerPage):(totalCount/numPerPage)+1; // 요청 페이지의 시작 게시물 번호와 끝 게시물 번호 구하기 // 시작 게시물 번호 int start = (reqPage-1)*numPerPage + 1; int end = reqPage*numPerPage; ArrayList<NoticeVO> list = driverBoardMapper.selectNoticeList(start, end); // 페이지 네비 작성 String pageNavi = ""; // 페이지 네비의 수 int pageNaviSize = 5; // 페이지 번호 int pageNo = ((reqPage-1)/pageNaviSize)*pageNaviSize + 1; // 이전 버튼 생성 if (pageNo != 1) { pageNavi += "<li class='prev arrow'>"; pageNavi += "<a href='/driver/board/driverBoardList?reqPage=" + (pageNo-1) + "'>이전</a>"; pageNavi += "</li>"; } // 페이지 번호 버튼 생성 ( 1 2 3 4 5 ) int i = 1; while (!(i++ > pageNaviSize || pageNo > totalPage)) { // 둘 중 하나라도 만족하면 수행하지 않겠다 if (reqPage == pageNo) { pageNavi += "<li class='on'>"; pageNavi += "<a>" + pageNo + "</a>"; // 4페이지 상태에서 4페이지를 누를수가 없도록 하기 위해서 a태그 없애줌 pageNavi += "</li>"; } else { pageNavi += "<li class=''>"; pageNavi += "<a href='/driver/board/driverBoardList?reqPage=" + pageNo + "'>" + pageNo + "</a>"; pageNavi += "</li>"; } pageNo++; } // 다음 버튼 생성 if (pageNo <= totalPage) { pageNavi += "<li class='next arrow'>"; pageNavi += "<a href='/driver/board/driverBoardList?reqPage=" + pageNo + "'>다음</a>"; pageNavi += "</li>"; } NoticePageData pd = new NoticePageData(list, pageNavi); return pd; } //기사 공지사항 상세보기 public NoticeVO driverNoticeView(int noticeIndex) throws Exception{ return driverBoardMapper.driverNoticeView(noticeIndex); } //기사 faq리스트 public FaqPageData driverFaqList(int reqPage) throws Exception { //페이지 당 게시물 수 int numPerPage = 5; //총 게시물 수 구하기 int totalCount = driverBoardMapper.faqTotalCount(); //총 페이지 수 구하기 int totalPage = (totalCount%numPerPage==0)?(totalCount/numPerPage):(totalCount/numPerPage)+1; //요청 페이지의 시작 게시물 번호와 끝 게시물 번호 구하기 //시작 게시물 번호 int start = (reqPage-1)*numPerPage +1; int end = reqPage*numPerPage; System.out.println(start+"/"+end); ArrayList<FaqVO> list = driverBoardMapper.driverFaqList(start,end); //페이지 네비 작성 String pageNavi = ""; //페이지 네비의 수 int pageNaviSize = 5; //페이지 번호 int pageNo = ((reqPage-1)/pageNaviSize)*pageNaviSize+1; //이전 버튼 생성 if(pageNo !=1) { pageNavi += "<li class='prev arrow'>"; pageNavi += "<a href='/driver/board/faq/driverFaqList?reqPage="+(pageNo-1)+"'>이전</a>"; pageNavi += "</li>"; } //페이지 번호 버튼 생성 ( 1 2 3 4 5 ) int i = 1; while( !(i++>pageNaviSize || pageNo>totalPage) ) { //둘 중 하나라도 만족하면 수행하지 않겠다 if(reqPage == pageNo) { pageNavi += "<li class='on'>"; pageNavi += "<a>"+pageNo+"</a>"; //4페이지 상태에서 4페이지를 누를수가 없도록 하기 위해서 a태그 없애줌 pageNavi += "</li>"; }else { pageNavi += "<li class=''>"; pageNavi += "<a href='/driver/board/faq/driverFaqList?reqPage="+pageNo+"'>"+pageNo+"</a>"; pageNavi += "</li>"; } pageNo++; } //다음 버튼 생성 if(pageNo <= totalPage) { pageNavi += "<li class='next arrow'>"; pageNavi +="<a href='/driver/board/faq/driverFaqList?reqPage="+pageNo+"'>다음</a>"; pageNavi += "</li>"; } FaqPageData pd = new FaqPageData(list,pageNavi); return pd; } //기사 1:1문의 리스트 public QuestionPageData driverQuestionList(int reqPage) throws Exception { // 페이지 당 게시물 수 int numPerPage = 5; // 총 게시물 수 구하기 int totalCount = driverBoardMapper.questionTotalCount(); // 총 페이지 수 구하기 int totalPage = (totalCount % numPerPage == 0) ? (totalCount / numPerPage) : (totalCount / numPerPage) + 1; // 요청 페이지의 시작 게시물 번호와 끝 게시물 번호 구하기 // 시작 게시물 번호 int start = (reqPage - 1) * numPerPage + 1; int end = reqPage * numPerPage; System.out.println(start + "/" + end); ArrayList<QuestionVO> list = driverBoardMapper.driverQuestionList(start, end); // 페이지 네비 작성 String pageNavi = ""; // 페이지 네비의 수 int pageNaviSize = 5; // 페이지 번호 int pageNo = ((reqPage - 1) / pageNaviSize) * pageNaviSize + 1; // 이전 버튼 생성 if (pageNo != 1) { pageNavi += "<li class='prev arrow'>"; pageNavi += "<a href='/driver/board/question/driverQuestionList?reqPage=" + (pageNo - 1) + "'>이전</a>"; pageNavi += "</li>"; } // 페이지 번호 버튼 생성 ( 1 2 3 4 5 ) int i = 1; while (!(i++ > pageNaviSize || pageNo > totalPage)) { // 둘 중 하나라도 만족하면 수행하지 않겠다 if (reqPage == pageNo) { pageNavi += "<li class='on'>"; pageNavi += "<a>" + pageNo + "</a>"; // 4페이지 상태에서 4페이지를 누를수가 없도록 하기 위해서 a태그 없애줌 pageNavi += "</li>"; } else { pageNavi += "<li class=''>"; pageNavi += "<a href='/driver/board/question/driverQuestionList?reqPage=" + pageNo + "'>" + pageNo + "</a>"; pageNavi += "</li>"; } pageNo++; } // 다음 버튼 생성 if (pageNo <= totalPage) { pageNavi += "<li class='next arrow'>"; pageNavi += "<a href='/driver/board/question/driverQuestionList?reqPage=" + pageNo + "'>다음</a>"; pageNavi += "</li>"; } QuestionPageData pd = new QuestionPageData(list, pageNavi); return pd; } //1:1문의 상세보기 public QuestionVO driverQuestionView(int questionsIndex) throws Exception{ return driverBoardMapper.driverQuestionView(questionsIndex); } //1:1문의 삭제하기 public int driverQuestionDelete(int questionsIndex) throws Exception { // TODO Auto-generated method stub return driverBoardMapper.driverQuestionDelete(questionsIndex); } //1:1문의 작성하기 public int driverQuestionInsert(QuestionVO q) throws Exception { // TODO Auto-generated method stub return driverBoardMapper.driverQuestionInsert(q); } //기사 공지사항 제목 검색 public NoticePageData searchKeyword(int reqPage, SearchNoticeVO s) throws Exception{ int numPerPage = 5; int totalCount = driverBoardMapper.titleCount(s); System.out.println("서비스 토탈 : "+totalCount); int totalPage = (totalCount%numPerPage==0)?(totalCount/numPerPage):(totalCount/numPerPage)+1;; int start = (reqPage-1)*numPerPage+1;; int end = reqPage*numPerPage; s.setStart(start); s.setEnd(end); ArrayList<NoticeVO> list = driverBoardMapper.searchKeywordTitle(s); System.out.println("서비스-"+list.size()); String pageNavi = ""; int pageNaviSize = 5; int pageNo = ((reqPage-1)/pageNaviSize)*pageNaviSize+1; if(pageNo !=1) { pageNavi += "<li class='prev arrow'>"; pageNavi += "<a href='/driver/board/searchKeyword?reqPage="+(pageNo-1)+"&keyWord="+s.getKeyWord()+"'>이전</a>"; pageNavi += "</li>"; } //페이지 번호 버튼 생성 ( 1 2 3 4 5 ) int i = 1; while( !(i++>pageNaviSize || pageNo>totalPage) ) { //둘 중 하나라도 만족하면 수행하지 않겠다 if(reqPage == pageNo) { pageNavi += "<li class='on'>"; pageNavi += "<a>"+pageNo+"</a>"; //4페이지 상태에서 4페이지를 누를수가 없도록 하기 위해서 a태그 없애줌 pageNavi += "</li>"; }else { pageNavi += "<li class=''>"; pageNavi += "<a href='/driver/board/searchKeyword?reqPage="+pageNo+"&keyWord="+s.getKeyWord()+"'>"+pageNo+"</a>"; pageNavi += "</li>"; } pageNo++; } //다음 버튼 생성 if(pageNo <= totalPage) { pageNavi += "<li class='next arrow'>"; pageNavi +="<a href='/driver/board/searchKeyword?reqPage="+pageNo+"&keyWord="+s.getKeyWord()+"'>다음</a>"; pageNavi += "</li>"; pageNavi += "</li>"; } NoticePageData pd = new NoticePageData(list,pageNavi); return pd; } //문의 타입 검색 public QuestionPageData searchQuestionTitle(int reqPage, SearchQuestionVO s) throws Exception { int numPerPage = 5; int totalCount = driverBoardMapper.questionCount(s); System.out.println("서비스 토탈 : "+totalCount); int totalPage = (totalCount%numPerPage==0)?(totalCount/numPerPage):(totalCount/numPerPage)+1;; int start = (reqPage-1)*numPerPage+1;; int end = reqPage*numPerPage; s.setStart(start); s.setEnd(end); ArrayList<QuestionVO> list = driverBoardMapper.searchQuestionTitle(s); System.out.println("서비스-"+list.size()); String pageNavi = ""; int pageNaviSize = 5; int pageNo = ((reqPage-1)/pageNaviSize)*pageNaviSize+1; if(pageNo !=1) { pageNavi += "<li class='prev arrow'>"; pageNavi += "<a href='/driver/board/question/searchQuestion?reqPage="+(pageNo-1)+"&keyWord="+s.getKeyWord()+"'>이전</a>"; pageNavi += "</li>"; } //페이지 번호 버튼 생성 ( 1 2 3 4 5 ) int i = 1; while( !(i++>pageNaviSize || pageNo>totalPage) ) { //둘 중 하나라도 만족하면 수행하지 않겠다 if(reqPage == pageNo) { pageNavi += "<li class='on'>"; pageNavi += "<a>"+pageNo+"</a>"; //4페이지 상태에서 4페이지를 누를수가 없도록 하기 위해서 a태그 없애줌 pageNavi += "</li>"; }else { pageNavi += "<li class=''>"; pageNavi += "<a href='/driver/board/question/searchQuestion?reqPage="+pageNo+"&keyWord="+s.getKeyWord()+"'>"+pageNo+"</a>"; pageNavi += "</li>"; } pageNo++; } //다음 버튼 생성 if(pageNo <= totalPage) { pageNavi += "<li class='next arrow'>"; pageNavi +="<a href='/driver/board/question/searchQuestion?reqPage="+pageNo+"&keyWord="+s.getKeyWord()+"'>다음</a>"; pageNavi += "</li>"; } QuestionPageData pd = new QuestionPageData(list,pageNavi); return pd; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package josteo.infrastructure.repositories.TipoAnamnesi; import java.sql.*; import java.util.*; import josteo.infrastructure.helpers.*; import josteo.model.tipoAnamnesi.*; /** * * @author cristiano */ public class TipoAnamnesiRepository extends josteo.infrastructure.repositories.MySqlRepositoryBase<TipoAnamnesi> implements ITipoAnamnesiRepository { public TipoAnamnesiRepository(){ super(); this.EntityFactory = new TipoAnamnesiFactory(); } @Override public TipoAnamnesi FindBy(Object key){ StringBuilder sb = this.GetBaseQueryBuilder(); sb.append("WHERE LCV=0 AND ID="); sb.append(key); TipoAnamnesi entity = null; ResultSet rs; try { rs = this.ExecuteQuery(sb.toString()); if(rs.first()){ entity = this.EntityFactory.BuildEntity(rs); } else ConfigHelper.getInstance().WriteLog("Not TipoAnamnesi found by ID="+key.toString()); } catch(Exception exc) { System.out.println(exc.getMessage()); } return entity; } @Override public List<TipoAnamnesi> FindAll(){ List<TipoAnamnesi> list = new ArrayList<TipoAnamnesi>(); try { StringBuilder sb = this.GetBaseQueryBuilder(); sb.append("WHERE LCV=0"); ResultSet rs = this.ExecuteQuery(sb.toString()); while(rs.next()){ list.add(this.EntityFactory.BuildEntity(rs)); } } catch(Exception exc) { ConfigHelper.getInstance().WriteLog(exc.getMessage()); } return list; } @Override protected StringBuilder GetBaseQueryBuilder(){ StringBuilder sb = new StringBuilder(); sb.append("SELECT * FROM lkp_anamnesi "); return sb; } //#region Unit of Work Implementation @Override protected void PersistNewItem(TipoAnamnesi item){ crud(item, false); } @Override protected void PersistUpdatedItem(TipoAnamnesi item){ crud(item, false); } @Override protected void PersistDeletedItem(TipoAnamnesi item){ crud(item, true); } //#endregion private void crud(TipoAnamnesi item, boolean bDelete){ TipoAnamnesiCRUDBuilder crudB = new TipoAnamnesiCRUDBuilder(this.database); try { this.DoCrud(item, crudB, null); } catch(Exception exc) { ConfigHelper.getInstance().WriteLog(exc.getMessage()); } } }
/****************************************************************************** * __ * * <-----/@@\-----> * * <-< < \\// > >-> * * <-<-\ __ /->-> * * Data / \ Crow * * ^ ^ * * info@datacrow.net * * * * This file is part of Data Crow. * * Data Crow is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public * * License as published by the Free Software Foundation; either * * version 3 of the License, or any later version. * * * * Data Crow is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public * * License along with this program. If not, see http://www.gnu.org/licenses * * * ******************************************************************************/ package net.datacrow.core.modules; import java.util.Collection; import net.datacrow.console.ComponentFactory; import net.datacrow.console.components.DcComboBox; import net.datacrow.console.components.DcReferencesField; import net.datacrow.console.windows.itemforms.DcMinimalisticItemView; import net.datacrow.core.DcRepository; import net.datacrow.core.IconLibrary; import net.datacrow.core.modules.xml.XmlModule; import net.datacrow.core.objects.DcField; import net.datacrow.core.objects.DcObject; import net.datacrow.core.objects.DcProperty; import net.datacrow.util.DcImageIcon; /** * A property module is the simplest module type. <br> * Examples of property modules are the movie and music genres, the software category, * the storage media and the platforms. A property module will never show up in the * module bar. In fact it will not show up anywhere until used within another module. * Its existence depends on other modules.<br> * Property modules are solely used by reference fields. * * @see DcReferencesField * @see DcComboBox * * @author Robert Jan van der Waals */ public class DcPropertyModule extends DcModule { private static final long serialVersionUID = -1481435217423089270L; protected DcMinimalisticItemView form; /** * Creates a new module based on a XML definition. * @param module */ public DcPropertyModule(XmlModule xmlModule) { super(xmlModule); setServingMultipleModules(xmlModule.isServingMultipleModules()); } /** * Creates a new instance. * @param index The module index. * @param topModule Indicates if the module is a top module. Top modules are allowed * to be displayed in the module bar and can be enabled or disabled. * @param name The internal unique name of the module. * @param description The module description * @param objectName The name of the items belonging to this module. * @param objectNamePlural The plural name of the items belonging to this module. * @param tableName The database table name for this module. * @param tableShortName The database table short name for this module. */ public DcPropertyModule(int index, String name, String tableName, String tableShortName, String objectName, String objectNamePlural) { super(index, false, name, "", objectName, objectNamePlural, tableName, tableShortName); } public DcPropertyModule getInstance(int index, String name, String tableName, String tableShortName, String objectName, String objectNamePlural) { return new DcPropertyModule(index, name, tableName, tableShortName, objectName, objectNamePlural); } /** * Creates (if needed) the simple item view. */ public DcMinimalisticItemView getForm() { form = form == null ? new DcMinimalisticItemView(getIndex(), false) : form; return form; } @Override public boolean isTopModule() { return false; } @Override public boolean hasInsertView() { return false; } @Override public boolean hasSearchView() { return false; } @Override public boolean hasDependingModules() { return true; } @Override public int getDisplayFieldIdx() { return DcProperty._A_NAME; } /** * Retrieves the index of the field on which is sorted by default. * Always returns the name field. * @see DcProperty#_A_NAME */ @Override public int getDefaultSortFieldIdx() { return DcProperty._A_NAME; } @Override public void resetForms() { super.resetForms(); this.form = null; } /** * Initializes the simple item view. */ @Override public void initializeUI() {} @Override public int[] getSupportedViews() { return new int[] {}; } /** * Creates a new instance of an item belonging to this module. */ @Override public DcObject createItem() { return new DcProperty(getIndex()); } /** * Indicates if this module is allowed to be customized. * Always returns false. */ @Override public boolean isCustomFieldsAllowed() { return false; } @Override public int[] getMinimalFields(Collection<Integer> include) { return new int[] {DcObject._ID, DcProperty._A_NAME, DcProperty._B_ICON, DcProperty._C_ALTERNATIVE_NAMES}; } /** * Initializes the default fields. */ @Override protected void initializeFields() { super.initializeFields(); addField(new DcField(DcProperty._A_NAME, getIndex(), "Name", false, true, false, true, 255, ComponentFactory._SHORTTEXTFIELD, getIndex(), DcRepository.ValueTypes._STRING, "Name")); addField(new DcField(DcProperty._B_ICON, getIndex(), "Icon", false, true, false, false, 255, ComponentFactory._PICTUREFIELD, getIndex(), DcRepository.ValueTypes._ICON, "Icon")); addField(new DcField(DcProperty._C_ALTERNATIVE_NAMES, getIndex(), "Alternative Names", false, true, false, false, 4000, ComponentFactory._LONGTEXTFIELD, getIndex(), DcRepository.ValueTypes._STRING, "alternative_names")); getField(DcObject._ID).setEnabled(false); } @Override public DcImageIcon getIcon16() { return super.getIcon16() == null ? IconLibrary._icoModuleTypeProperty16 : super.getIcon16(); } @Override public DcImageIcon getIcon32() { return super.getIcon32() == null ? IconLibrary._icoModuleTypeProperty32 : super.getIcon32(); } /** * Returns the template module. * @return Always returns null. */ @Override public TemplateModule getTemplateModule() { return null; } @Override public boolean equals(Object o) { return (o instanceof DcPropertyModule ? ((DcPropertyModule) o).getIndex() == getIndex() : false); } }
package com.esrinea.dotGeo.tracking.model.component.resourceLiveFeed.entity; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.persistence.TableGenerator; import javax.persistence.Temporal; import javax.persistence.TemporalType; import com.esrinea.dotGeo.tracking.model.component.device.entity.Device; /** * The persistent class for the Tracking_Resource_LiveFeeds database table. * */ @Entity @Table(name = "Tracking_Resource_LiveFeeds") @NamedQuery(name = "ResourceLiveFeed.findByDevice", query = "SELECT r FROM ResourceLiveFeed r WHERE r.device.id = :deviceId") public class ResourceLiveFeed implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(name = "Resource_livefeeds_DBID") @TableGenerator(name = "resourceLiveFeed", table = "SEQUENCE_STORE", pkColumnName = "SEQ_NAME", pkColumnValue = "RESOURCE_LIVE_FEEDS", valueColumnName = "SEQ_VALUE", initialValue = 1, allocationSize = 1) @GeneratedValue(strategy = GenerationType.TABLE, generator = "resourceLiveFeed") private int id; @Column(name = "Device") @ManyToOne @JoinColumn(name = "Device_DBID") private Device device; @Temporal(TemporalType.TIMESTAMP) @Column(name = "FeedDateTime", nullable = false) private Date feedDateTime; @Column(name = "Heading", precision = 53) private double heading; @Column(name = "Speed") private int speed; @Column(name = "X_Coord", precision = 53) private double xCoord; @Column(name = "Y_Coord", precision = 53) private double yCoord; @Column(name = "Zone") private String zone; public ResourceLiveFeed() { } public ResourceLiveFeed(Device device, Date feedDateTime, double xCoord, double yCoord, int speed, double heading, String zone) { this.device = device; this.feedDateTime = feedDateTime; this.xCoord = xCoord; this.yCoord = yCoord; this.speed = speed; this.heading = heading; this.zone = zone; } public int getId() { return id; } public Device getDevice() { return device; } public void setDevice(Device device) { this.device = device; } public Date getFeedDateTime() { return feedDateTime; } public void setFeedDateTime(Date feedDateTime) { this.feedDateTime = feedDateTime; } public double getHeading() { return heading; } public void setHeading(double heading) { this.heading = heading; } public int getSpeed() { return speed; } public void setSpeed(int speed) { this.speed = speed; } public double getxCoord() { return xCoord; } public void setxCoord(double xCoord) { this.xCoord = xCoord; } public double getyCoord() { return yCoord; } public void setyCoord(double yCoord) { this.yCoord = yCoord; } public String getZone() { return zone; } public void setZone(String zone) { this.zone = zone; } @Override public String toString() { return "ResourceLiveFeed [id=" + id + ", device=" + device + ", feedDateTime=" + feedDateTime + ", heading=" + heading + ", speed=" + speed + ", xCoord=" + xCoord + ", yCoord=" + yCoord + ", zone=" + zone + "]"; } }
package com.siokagami.application.mytomato.model.inf; import android.content.Context; public interface MainPageModelInf { void getMainPageData(Context context); }
package com.qa.test; public class Welcome { }
package egovframework.usr.stu.std.controller; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import com.ziaan.course.SubjGongData; import com.ziaan.lcms.EduStartBean; import com.ziaan.system.StudyCountBean; import egovframework.com.cmm.EgovMessageSource; import egovframework.com.lcms.len.service.LearningService; import egovframework.usr.stu.std.service.StudyManageService; import egovframework.usr.stu.std.service.StudyNoticeService; @Controller public class StudyNoticeController { /** log */ protected static final Log log = LogFactory.getLog(StudyNoticeController.class); /** EgovMessageSource */ @Resource(name = "egovMessageSource") EgovMessageSource egovMessageSource; /** studyNoticeService */ @Resource(name = "studyNoticeService") StudyNoticeService studyNoticeService; /** studyManageService */ @Resource(name = "studyManageService") StudyManageService studyManageService; /** * 학습창 공지사항 리스트 * @param request * @param response * @param commandMap * @param model * @return * @throws Exception */ @RequestMapping(value="/usr/stu/std/userStudyNoticeList.do") public String noticePage(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{ setSummaryInfo(commandMap, model); // 요약정보 //공지 List list = studyNoticeService.selectListGong(commandMap); // 공지 model.addAttribute("selectList", list); //전체공지 List listall = studyNoticeService.selectListGongAll_H(commandMap); // 전체공지 model.addAttribute("selectListAll", listall); model.addAllAttributes(commandMap); return "usr/stu/std/userStudyNoticeList"; } /** * 학습창 공지사항 상세화면 * @param request * @param response * @param commandMap * @param model * @return * @throws Exception */ @RequestMapping(value="/usr/stu/std/userStudyNoticeView.do") public String noticeViewPage(HttpServletRequest request, HttpServletResponse response, Map<String, Object> commandMap, ModelMap model) throws Exception{ setSummaryInfo(commandMap, model); // 요약정보 Map data = studyNoticeService.selectViewGong(commandMap); model.addAttribute("selectGong", data); model.addAllAttributes(commandMap); return "usr/stu/std/userStudyNoticeView"; } public void setSummaryInfo(Map<String, Object> commandMap, ModelMap model) throws Exception{ if( commandMap.get("studyPopup") == null || commandMap.get("studyPopup").toString().equals("") ){ // 나의 진도율, 권장 진도율 double progress = Double.parseDouble(studyManageService.getProgress(commandMap)); double promotion = Double.parseDouble(studyManageService.getPromotion(commandMap)); model.addAttribute("progress", String.valueOf(progress)); model.addAttribute("promotion", String.valueOf(promotion)); // 학습정보 EduStartBean bean = EduStartBean.getInstance(); List dataTime = studyManageService.SelectEduTimeCountOBC(commandMap); // 학습시간,최근학습일,강의접근횟수 model.addAttribute("EduTime", dataTime); Map data2 = studyManageService.SelectEduScore(commandMap); model.addAttribute("EduScore", data2); // 강사정보 Map tutorInfo = studyManageService.getTutorInfo(commandMap); model.addAttribute("tutorInfo", tutorInfo); commandMap.put("p_grcode","N000001"); commandMap.put("p_class","1"); List list = studyManageService.selectListOrderPerson(commandMap); model.addAttribute("ReportInfo", list); // 총차시, 학습한 차시, 진도율, 과정구분 Map map = studyManageService.getStudyChasi(commandMap); model.addAttribute("datecnt", map.get("datecnt")); // 총차시 model.addAttribute("edudatecnt", map.get("edudatecnt")); // 학습한 차시 model.addAttribute("wstep", map.get("wstep")); // 진도율 } } }
package com.myacorn.dao; import javax.naming.*; import javax.sql.*; public class MySqlDatabase { private static DataSource mySqlDs = null; //hold the database object private static Context initialContext = null; //used to lookup the database connection in tomcat public static DataSource MySqlDataSource() throws Exception { if (mySqlDs != null) { return mySqlDs; } try { if (initialContext == null) { initialContext = new InitialContext(); } Context envContext = (Context) initialContext.lookup("java:comp/env"); mySqlDs = (DataSource) envContext.lookup("jdbc/sakila"); } catch (Exception e) { e.printStackTrace(); } return mySqlDs; } }
package hu.lamsoft.hms.androidclient.restapi.nutritionist.dto; import java.util.List; import hu.lamsoft.hms.androidclient.restapi.common.dto.BaseDTO; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper=true) public class BlogEntryDTO extends BaseDTO { private NutritionistDTO writer; private String title; private String preface; private String content; private List<BlogEntryKeyWordDTO> keyWords; }
import java.util.*; public class Singing { public int solve(int N, int low, int high, int[] pitch) { FlowNetwork flow = new FlowNetwork(); int bob = flow.source; int alice = flow.sink; int[] keys = new int[N + 1]; for(int i = 0; i < pitch.length; ++i) { if(keys[pitch[i]] == 0) { keys[pitch[i]] = flow.addVertex(); } } for(int i = 1; i < pitch.length; ++i) { if(pitch[i - 1] != pitch[i]) { flow.addEdge(keys[pitch[i -1]], keys[pitch[i]], 1); flow.addEdge(keys[pitch[i]], keys[pitch[i - 1]], 1); } } for(int i = 0; i < low; ++i) { if(keys[i] != 0) { flow.addEdge(bob, keys[i], 10000); } } for(int i = high + 1; i <= N; ++i) { if(keys[i] != 0) { flow.addEdge(keys[i], alice, 10000); } } return flow.maxFlow(); } private class FlowNetwork { private ArrayList<ArrayList<int[]>> graphList; private int source; private int sink; private FlowNetwork() { graphList = new ArrayList<ArrayList<int[]>>(); graphList.add(new ArrayList<int[]>()); source = 0; graphList.add(new ArrayList<int[]>()); sink = 1; } private int addVertex() { graphList.add(new ArrayList<int[]>()); return graphList.size() - 1; } private void addEdge(int u, int v, int w) { graphList.get(u).add(new int[] {v, w}); } private int maxFlow() { int[][] graph = new int[graphList.size()][graphList.size()]; for(int i = 0; i < graphList.size(); ++i) { for(int j = 0; j < graphList.get(i).size(); ++j) { graph[i][graphList.get(i).get(j)[0]] += graphList.get(i).get(j)[1]; } } return maxFlow(graph); } private int maxFlow(int[][] graph) { int flow = 0; int[][] remainingCapacity = new int[graph.length][graph.length]; boolean done = false; while(!done) { int[] path = new int[graph.length]; for(int i = 0; i < path.length; ++i) { path[i] = -1; } path[source] = -2; int[] capacity = new int[graph.length]; capacity[source] = Integer.MAX_VALUE; ArrayList<Integer> queue = new ArrayList<>(); queue.add(source); int capacityFound = -1; for(int i = 0; i < queue.size() && capacityFound == -1; ++i) { int node = queue.get(i); int[] edges = graph[node]; for(int j = 0; j < edges.length && capacityFound == -1; ++j) { if(0 < edges[j] - remainingCapacity[node][j] && path[j] == -1) { path[j] = node; capacity[j] = Math.min(capacity[node], edges[j] - remainingCapacity[node][j]); if(j != sink) { queue.add(j); } else { capacityFound = capacity[j]; } } } } if(capacityFound <= 0) { done = true; } else { flow += capacityFound; int node = sink; while(node != source) { int next = path[node]; remainingCapacity[next][node] += capacityFound; remainingCapacity[node][next] -= capacityFound; node = next; } } } return flow; } } }
package com.techelevator.exceptions; public class ReservationException extends RuntimeException { private static final long serialVersionUID = -4609441623691704492L; private String stringID; private Object[] objects; public ReservationException(String messageID, Object...objects) { super(messageID); this.stringID = messageID; this.objects = objects; } public String getID() { return stringID; } public Object[] getObjects() { return objects; } }
package com.huotn.bootjsp.bootjsp.pojo.wechat; /** * @Description: ImageMessage * * @Auther: leichengyang * @Date: 2019/4/30 0030 * @Version 1.0 */ /** * 图片消息 * */ public class ImageMessage extends BaseMessage { // 图片链接 private String PicUrl; public String getPicUrl() { return PicUrl; } public void setPicUrl(String picUrl) { PicUrl = picUrl; } }
package com.github.charlieboggus.sgl.graphics.g2d; import com.github.charlieboggus.sgl.core.Display; import com.github.charlieboggus.sgl.graphics.gl.GLTexture; import com.github.charlieboggus.sgl.utility.Color; import org.lwjgl.BufferUtils; import org.lwjgl.stb.STBImage; import org.lwjgl.system.MemoryStack; import java.nio.ByteBuffer; import java.nio.IntBuffer; import static org.lwjgl.opengl.GL11.*; import static org.lwjgl.opengl.GL12.GL_CLAMP_TO_EDGE; public class Texture { private GLTexture tex; private int width; private int height; float s0; float t0; float s1; float t1; public Texture(Texture texture) { this.width = texture.width; this.height = texture.height; this.s0 = 0.0f; this.t0 = 0.0f; this.s1 = 1.0f; this.t1 = 1.0f; this.tex = texture.tex; } public Texture(String file) { int width; int height; int components; ByteBuffer data; try (MemoryStack stack = MemoryStack.stackPush()) { IntBuffer wb = stack.mallocInt(1); IntBuffer hb = stack.mallocInt(1); IntBuffer cb = stack.mallocInt(1); STBImage.stbi_set_flip_vertically_on_load(false); data = STBImage.stbi_load(file, wb, hb, cb, 0); width = wb.get(0); height = hb.get(0); components = cb.get(0); } this.generateTexture(width, height, components, data); } public Texture(int width, int height) { ByteBuffer data = BufferUtils.createByteBuffer(width * height * 4); int i = 0; for (int y = 0; y < height; y++) { for (int x = 0; x < width; x++) { Color c = (x / 16) % 2 == 0 ? ((y / 16) % 2 == 0 ? Color.White : Color.Coral) : ((y / 16) % 2 == 0 ? Color.Coral : Color.White); data.put(i, (byte) c.redByte()); data.put(i + 1, (byte) c.greenByte()); data.put(i + 2, (byte) c.blueByte()); data.put(i + 3, (byte) c.alphaByte()); i += 4; } } this.generateTexture(width, height, 4, data); } public Texture(int width, int height, int components, ByteBuffer data) { this.generateTexture(width, height, components, data); } public void dispose() { this.tex.destroy(); } public int getWidth() { return this.width; } public int getHeight() { return this.height; } void bind() { this.tex.bind(); } void bind(int unit) { this.tex.bind(unit); } void unbind() { this.tex.unbind(); } float getS0() { return this.s0; } float getT0() { return this.t0; } float getS1() { return this.s1; } float getT1() { return this.t1; } private void generateTexture(int width, int height, int components, ByteBuffer data) { this.width = width; this.height = height; this.s0 = 0.0f; this.t0 = 0.0f; this.s1 = 1.0f; this.t1 = 1.0f; this.tex = new GLTexture(); this.tex.bind(); this.tex.uploadTextureData((components == 4) ? GL_RGBA8 : GL_RGB, width, height, (components == 4) ? GL_RGBA : GL_RGB, GL_UNSIGNED_BYTE, data); this.tex.generateMipmap(); this.tex.setWrap(GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE); this.tex.setFilter(Display.getFilterMode().getMinFilter(), Display.getFilterMode().getMagFilter()); if (Display.getFilterMode().isAnisotropic()) this.tex.setAnisotropicFilter(Display.getFilterMode().getSamples()); this.tex.unbind(); } }
package com.algorithm.tree; public class KthSmallest { static int times = 0; static int result = 0; public static int kthSmallest(TreeNode root, int k) { dfs(root,k); return result; } private static void dfs(TreeNode root, int k) { if(root == null){ return; } dfs(root.left,k); times ++; if(times == k){ result = root.val; } dfs(root.right,k); } public static void main(String[] args) { TreeNode treeNode = new TreeNode(3); treeNode.left = new TreeNode(1); treeNode.right = new TreeNode(4); treeNode.left.right = new TreeNode(2); kthSmallest(treeNode,1); } }
import programmering.*; public class MyImagingProgram { int area = 2; public static int[] copyArray(int[] originalArray){ int[] array = new int[originalArray.length]; for(int i = 0; i < originalArray.length; i++){ array[i] = originalArray[i]; } return array; } public static double GaussianFunction(double x, double variance){ return Math.exp(-Math.pow(x, 2.0) / (2.0*variance)); } public static double EuclidianDistance(int[] a, int[] b) { double sum = 0.0; for(int i = 0; i < a,length; i++){ sum += Math.pow(a[i] -b[i], 2.0); } return Math.sqrt(sum); } public static int[] iterateRGBArray(int[] array, int area){ int[] finishedRGB = new int[3]; for(int i = 0; i < array.length; i++){ finishedRGB[i] = array[i] * GaussianFunction() * GaussianFunction(); } return finishedRGB; } public static void mainFunc(int[] array, int i, int j, int area) { for(int x = i -area; x < i + area; x++) { for(int y = j - area; y < j + area; y++){ int index = Imaging.convert2DTo1D(x, y); int RGB[] = Imaging.getRGBArray(array[index]); iterateRGBArray(RGB, area); } } } public static void bilateralFilter(int area, int[] img) { for(int x = area; x < Imaging.currentImageWidth - area; x++) { for(int y = area; y < Imaging.getImgHeight(img) - area; y++){ int index = Imaging.convert2DTo1D(x, y); int RGB[] = mainFunc(img, x, y, area); } } } public static int[] calcRGBSum(int[] img, int i, int j){ int red= 0; int green = 0; int blue = 0; int RGB[] = new int[3]; for(int x = i -1; x < i +2; x++){ for(int y = j - 1; y < j + 2; y++){ int index = Imaging.convert2DTo1D(x, y); RGB = Imaging.getRGBArray(img[index]); red += RGB[0]; green += RGB[1]; blue += RGB[2]; } } RGB[0] = red/9; RGB[1] = green/9; RGB[2] = blue/9; return RGB; } public static void clamping(int[] RGB){ for(int i = 0; i <RGB.length; i++){ if(RGB[i] > 255){ RGB[i] = 255; } else if(RGB[i] < 0){ RGB[i] = 0; } } } public static void sharpenImage(double sharpness, int[] img){ int s = 32; int[] filterImg = copyArray(img); applyBoxBlur(1, filterImg); for(int x= 0; x < Imaging.currentImageWidth; x++){ for(int y= 0; y < Imaging.getImgHeight(img); y++){ int index = Imaging.convert2DTo1D(x, y); int oRGB[] = Imaging.getRGBArray(img[index]); int fRGB[] = Imaging.getRGBArray(filterImg[index]); oRGB[0] = oRGB[0] + (oRGB[0] - fRGB[0]) * s; oRGB[1] = oRGB[1] + (oRGB[1] - fRGB[1]) * s; oRGB[2] = oRGB[2] + (oRGB[2] - fRGB[2]) * s; clamping(oRGB); img[index] = Imaging.getIntColour(oRGB); //MANGLER Å IMPLEMENTERE SHARPNESS-PARAMETERET. FUNKER IKKE } } } public static void applyBoxBlur(int iterations, int[] img) { for(int i = 0; i < iterations; i++){ boxBlur(img); } } public static void boxBlur(int[] img){ for(int x= 1; x < Imaging.currentImageWidth - 1; x++){ for(int y= 1; y < Imaging.getImgHeight(img) -1; y++){ int index = Imaging.convert2DTo1D(x, y); int RGB[] = calcRGBSum(img, x, y); img[index] = Imaging.getIntColour(RGB); } } } public static void main(String[] args) { if(args.length < 1){ System.err.println("Please provide an image path"); } int[] img = Imaging.readImageFromFile(args[0]); if(img == null){ System.exit(-1); } //applyBoxBlur(32, img); //Har ikke funnet beste mengden iterasjoner for å fjerne støy. sharpenImage(4, img); Imaging.writeImageToFile(img, "outputS32.jpg", "jpg"); int s = 4 + (4 -2) * 4; //12 } }
package lab4; import java.util.Scanner; public class mainsv { public static void main(String[]args) { int roll; String hoten; int java,html,Css,Marketting,Sales; Scanner scanner =new Scanner(System.in); System.out.println(" 1.svIT"); System.out.println("2.svBiz"); roll = scanner.nextInt(); while(true) { switch(roll) { case 1: System.out.println("nhap ten"); hoten = scanner.nextLine(); System.out.println("nhap diem java"); java = scanner.nextInt(); System.out.println("nhap diem html"); html = scanner.nextInt(); System.out.println("nhap diem css"); Css = scanner.nextInt(); SinhVien svIT= new SinhvienIT(hoten,java,html,Css); svIT.getDiem(); svIT.getHocLuc(); svIT.xuat(); break; case 2: System.out.println("nhap ten"); hoten = scanner.nextLine(); System.out.println("nhap diem marktting"); Marketting = scanner.nextInt(); System.out.println("nhap diem Sales"); Sales = scanner.nextInt(); SinhVien svBiz= new SinhvienBiz(hoten,Marketting,Sales); svBiz.getDiem(); svBiz.getHocLuc(); svBiz.xuat(); break; default: break; } } } }
package jire.packet.build; import jire.packet.Packet; import jire.packet.PacketBuilder; import jire.packet.PacketRepresentation; import jire.packet.RSOutputStream; import jire.packet.reflective.BuildsPacket; import jire.packet.represent.MessagePacket; @BuildsPacket(MessagePacket.class) public final class MessagePacketBuilder implements PacketBuilder { @Override public Packet build(PacketRepresentation packetRep) { MessagePacket packet = (MessagePacket) packetRep; RSOutputStream output = new RSOutputStream(packet.getContent() .getBytes().length + 1); output.writeString(packet.getContent()); return new Packet(253, output.getData()); } }
package com.example.amalzoheir.newsapp; import android.app.Activity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import java.util.ArrayList; /** * Created by Amalzoheir on 12/18/2017. */ public class NewsInfoAdapter extends ArrayAdapter<NewsInfo> { public NewsInfoAdapter(Activity context, ArrayList<NewsInfo> newsInfos){ super(context,0,newsInfos); } @Override public View getView(int position,View convertView,ViewGroup parent) { View listItemView=convertView; if(listItemView==null){ listItemView= LayoutInflater.from(getContext()).inflate(R.layout.newsinfo_list_item,parent,false); } NewsInfo currentNewsInfo=getItem(position); TextView titleOfArticleView=(TextView)listItemView.findViewById(R.id.title_of_article); titleOfArticleView.setText(currentNewsInfo.getTitleOfArticle()); TextView nameOfSectionView=(TextView)listItemView.findViewById(R.id.name_of_section); nameOfSectionView.setText(currentNewsInfo.getNameOfSecction()); TextView webTitleView=(TextView)listItemView.findViewById(R.id.web_title); webTitleView.setText(currentNewsInfo.getWebTitle()); TextView webPublishingView=(TextView)listItemView.findViewById(R.id.web_publishing_date); webPublishingView.setText(currentNewsInfo.getpDate()); TextView authorNameView=(TextView)listItemView.findViewById(R.id.author_name); authorNameView.setText(currentNewsInfo.getAuthorName()); return listItemView; } }
package com.appsala.app.enuns; public enum TipoTopico { LOCAL, GLOBAL; }
package org.point85.domain.opc.da; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import org.openscada.opc.dcom.da.impl.OPCItemProperties; import org.openscada.opc.lib.da.browser.Branch; import org.openscada.opc.lib.da.browser.Leaf; import org.openscada.opc.lib.da.browser.TreeBrowser; public class OpcDaTreeBrowser { private final TreeBrowser treeBrowser; private final OPCItemProperties itemProperties; public OpcDaTreeBrowser(TreeBrowser browser, OPCItemProperties itemProperties) { this.treeBrowser = browser; this.itemProperties = itemProperties; } public TreeBrowser getTreeBrowser() { return this.treeBrowser; } public OpcDaTagTreeBranch browseBranches() throws Exception { Branch rootBranch = treeBrowser.browseBranches(); return new OpcDaTagTreeBranch(rootBranch); } public Collection<OpcDaTagTreeBranch> getAllBranches() throws Exception { OpcDaTagTreeBranch rootBranch = new OpcDaTagTreeBranch(treeBrowser.browse()); return getBranches(rootBranch); } public Collection<OpcDaTagTreeBranch> getBranches(OpcDaTagTreeBranch tagBranch) throws Exception { fillBranches(tagBranch); Collection<Branch> branches = tagBranch.getBranch().getBranches(); Collection<OpcDaTagTreeBranch> tagBranches = new ArrayList<>( branches.size()); for (Branch branch : branches) { OpcDaTagTreeBranch aBranch = new OpcDaTagTreeBranch(branch); tagBranches.add(aBranch); } return tagBranches; } private void fillBranches(OpcDaTagTreeBranch tagBranch) throws Exception { treeBrowser.fillBranches(tagBranch.getBranch()); } private void fillLeaves(OpcDaTagTreeBranch tagBranch) throws Exception { treeBrowser.fillLeaves(tagBranch.getBranch()); } public boolean isLastNode(OpcDaTagTreeBranch tagBranch) throws Exception { fillBranches(tagBranch); boolean isLast = tagBranch.isLast(); if (isLast) { fillLeaves(tagBranch); } return isLast; } public Collection<OpcDaBrowserLeaf> getLeaves(OpcDaTagTreeBranch tagBranch) { Collection<OpcDaBrowserLeaf> allLeaves = new ArrayList<>(); Branch branch = tagBranch.getBranch(); Collection<Leaf> leaves = branch.getLeaves(); for (Leaf leaf : leaves) { allLeaves.add(new OpcDaBrowserLeaf(leaf, itemProperties)); } return allLeaves; } private Branch findChildBranch(Branch parent, String name) throws Exception { Branch branch = null; Collection<Branch> children = parent.getBranches(); for (Branch child : children) { if (child.getName().equals(name)) { branch = child; this.getTreeBrowser().fillBranches(branch); break; } } return branch; } public OpcDaBrowserLeaf findTag(String pathName) throws Exception { String[] tokens = OpcDaBrowserLeaf.getPath(pathName); int len = tokens.length - 1; List<String> accessPath = new ArrayList<>(len); Collections.addAll(accessPath, tokens); return findTag(accessPath, tokens[len]); } public OpcDaBrowserLeaf findTag(List<String> branchNames, String leafName) throws Exception { OpcDaBrowserLeaf leafTag = null; // get root branch Branch next = browseBranches().getBranch(); // look for matching name at each level in the name space for (String branchName : branchNames) { Branch child = this.findChildBranch(next, branchName); if (child != null) { next = child; } } if (next != null) { TreeBrowser tb = this.getTreeBrowser(); tb.fillLeaves(next); Collection<Leaf> leaves = next.getLeaves(); for (Leaf leaf : leaves) { if (leaf.getName().equals(leafName)) { leafTag = new OpcDaBrowserLeaf(leaf, this.itemProperties); break; } } } return leafTag; } }
package pl.dkiszka.bank.account.services; /** * @author Dominik Kiszka {dominikk19} * @project bank-application * @date 26.04.2021 */ public class CommandGatewayException extends RuntimeException { public CommandGatewayException(String message) { super(message); } }