text
stringlengths
10
2.72M
/* * Copyright (c) 2015 ICM Uniwersytet Warszawski All rights reserved. * See LICENCE.txt file for licensing information. */ package pl.edu.icm.unity.server.authn; /** * Result of sandbox authn using a local facility. Wrapper of {@link AuthenticationResult}. * @author K. Benedyczak */ public class LocalSandboxAuthnContext implements SandboxAuthnContext { private AuthenticationResult authenticationResult; public LocalSandboxAuthnContext(AuthenticationResult authenticationResult) { this.authenticationResult = authenticationResult; } public AuthenticationResult getAuthenticationResult() { return authenticationResult; } }
package pop3; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.function.Consumer; import io.vavr.control.Try; import lombok.Data; import lombok.extern.slf4j.Slf4j; import pop3.command.CommandExecutor; import pop3.command.CommandParser; import pop3.command.POP3Command; import pop3.command.ServerResponse; import pop3.command.Session; @Data @Slf4j public class ClientHandler implements Runnable { private static final String WELCOME_MESSAGE = "POP3 server is start up"; private Socket socket; private DataOutputStream socketOutput; private Scanner socketInput; private InputStream socketInputStream; private String user; private SessionState sessionState; private boolean closeConnection = false; private Server server; private List<POP3Command> availableCommands; ClientHandler(Socket clientSocket, Server server) { this.socket = clientSocket; this.server = server; this.availableCommands = new ArrayList<>(); } @Override public void run() { try { socketInputStream = socket.getInputStream(); socketInput = new Scanner(socketInputStream); socketInput.useDelimiter(CommandParser.getLineEnd()); socketOutput = new DataOutputStream(socket.getOutputStream()); } catch (IOException e) { e.printStackTrace(); disconnect(); return; } sessionState = SessionState.AUTHORIZATION; sendGreeting(); while (!socket.isClosed() && !closeConnection && !Thread.interrupted()) { receiveCommand(); } disconnect(); } private void sendGreeting() { sendResponse(new ServerResponse(true, WELCOME_MESSAGE)); } private void sendResponse(ServerResponse response) { Try .run(() -> { socketOutput.write(response.buildResponse().getBytes(StandardCharsets.US_ASCII)); socketOutput.flush(); ServerEvent event = ServerEvent.of(EventType.SEND_RESPONSE, server.getCurrentTime()); event.addArgument(getClientAddress()); event.addArgument(response.buildResponse()); server.logEvent(event); }) .onFailure(ex -> disconnect()); } private void receiveCommand() { String command = Try .of(() -> socketInput.nextLine()).getOrElse(""); ServerEvent event = ServerEvent.of(EventType.RECEIVE_COMMAND, server.getCurrentTime()); event.addArgument(getClientAddress()); event.addArgument(command); server.logEvent(event); if (CommandParser.validate(command)) { CommandExecutor processor = getCommandProcessor(CommandParser.getCommandKeyword(command)); Session state = getClientSessionState(); state.setLastCommand(command); Consumer<ServerResponse> responseHandler = response -> { applyCommandChanges(state); sendResponse(response); }; Try .of(() -> processor.execute(state, server)) .onSuccess(responseHandler) .onFailure(ex -> { ServerResponse response = new ServerResponse(false, ex.getMessage()); responseHandler.accept(response); }); } else { sendResponse(CommandParser.getInvalidResponse()); } } private void disconnect() { server.logEvent(ServerEvent.of(EventType.DISCONNECT_CLIENT, getClientAddress(), server.getCurrentTime())); if (sessionState == SessionState.TRANSACTION) { server.getUserMailbox(user).unlock(); } Try .run(() -> { socketOutput.close(); socketInput.close(); if (!socket.isClosed()) { socket.close(); } }) .onFailure(ex -> log.error(ex.getMessage())); } public String getClientAddress() { return socket.getInetAddress().getHostAddress() + ":" + socket.getPort(); } private CommandExecutor getCommandProcessor(String commandKeyword) { return POP3Command.valueOf(commandKeyword).getCommandExecutor(); } private Session getClientSessionState() { return Session.builder() .user(user) .sessionState(sessionState) .closeConnection(closeConnection) .build(); } private void applyCommandChanges(Session state) { sessionState = state.getSessionState(); user = state.getUser(); closeConnection = state.isCloseConnection(); } }
package com.db.retail.service; import static org.mockito.Matchers.any; import static org.mockito.Mockito.when; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.db.retail.dao.ShopDao; import com.db.retail.domain.Address; import com.db.retail.domain.GeoDetails; import com.db.retail.domain.Shop; import com.db.retail.exception.ErrorCodes; import com.db.retail.exception.RetailSystemException; import com.db.retail.googleservice.client.GeoCodingClient; @RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest public class TestShopService { @InjectMocks @Autowired private IShopService shopService; @Mock private GeoCodingClient geoCodingClientMock; @Autowired private ShopDao shopDao; @Before public void setup() { MockitoAnnotations.initMocks(this); shopDao.deleteAll(); } @Test public void testAddShopWithValidData() { Shop shop = new Shop(); shop.setShopName("test name"); Address addr = new Address(); addr.setNumber("abc"); addr.setPostCode("ghj"); shop.setShopAddress(addr); when(geoCodingClientMock.getGeoDetails(any())).thenReturn(new GeoDetails(2.34, 5.23)); Shop oldShop = shopService.addOrReplaceShop(shop); Assert.assertEquals(2.34, shop.getShopGeoDetails().getLatitude(), 0); Assert.assertEquals(5.23, shop.getShopGeoDetails().getLongitude(), 0); Assert.assertNull(oldShop); Set<Shop> shopSet = shopDao.getAllShops(); Assert.assertEquals(1, shopSet.size()); Shop firstShop = shopSet.iterator().next(); Assert.assertEquals("test name", firstShop.getShopName()); Assert.assertEquals(2.34, firstShop.getShopGeoDetails().getLatitude(), 0); Assert.assertEquals(5.23, firstShop.getShopGeoDetails().getLongitude(), 0); } @Test public void testAddShopWithDuplicatedData() { Shop shop = new Shop(); shop.setShopName("test name"); Address addr = new Address(); addr.setNumber("abc"); addr.setPostCode("ghj"); shop.setShopAddress(addr); when(geoCodingClientMock.getGeoDetails(any())).thenReturn(new GeoDetails(2.34, 5.23)); Shop oldShop = shopService.addOrReplaceShop(shop); Shop shop1 = new Shop(); shop1.setShopName("test name"); when(geoCodingClientMock.getGeoDetails(any())).thenReturn(new GeoDetails(3.45, 4.56)); shop1.setShopAddress(addr); Shop oldShop1 = shopService.addOrReplaceShop(shop1); Assert.assertNull(oldShop); Assert.assertEquals(2.34, oldShop1.getShopGeoDetails().getLatitude(), 0); Assert.assertEquals(5.23, oldShop1.getShopGeoDetails().getLongitude(), 0); Assert.assertEquals(3.45, shop1.getShopGeoDetails().getLatitude(), 0); Assert.assertEquals(4.56, shop1.getShopGeoDetails().getLongitude(), 0); Set<Shop> shopSet = shopDao.getAllShops(); Assert.assertEquals(1, shopSet.size()); Shop firstShop = shopSet.iterator().next(); Assert.assertEquals("test name", firstShop.getShopName()); Assert.assertEquals(2.34, firstShop.getShopGeoDetails().getLatitude(), 0); Assert.assertEquals(5.23, firstShop.getShopGeoDetails().getLongitude(), 0); } @Test public void testAddShopWithTwoAddition() { Shop shop1 = new Shop(); shop1.setShopName("test name 1"); Address addr = new Address(); addr.setNumber("abc1"); addr.setPostCode("ghj1"); shop1.setShopAddress(addr); when(geoCodingClientMock.getGeoDetails(any())).thenReturn(new GeoDetails(2.34, 5.23)); Shop oldShop1 = shopService.addOrReplaceShop(shop1); Assert.assertNull(oldShop1); Assert.assertEquals(2.34, shop1.getShopGeoDetails().getLatitude(), 0); Assert.assertEquals(5.23, shop1.getShopGeoDetails().getLongitude(), 0); Shop shop2 = new Shop(); shop2.setShopName("test name 2"); Address addr2 = new Address(); addr2.setNumber("abc2"); addr2.setPostCode("ghj2"); shop2.setShopAddress(addr2); Shop oldShop2 = shopService.addOrReplaceShop(shop2); Assert.assertNull(oldShop2); Assert.assertEquals(2.34, shop2.getShopGeoDetails().getLatitude(), 0); Assert.assertEquals(5.23, shop2.getShopGeoDetails().getLongitude(), 0); Set<Shop> shopSet = shopDao.getAllShops(); Assert.assertEquals(2, shopSet.size()); } @Test(expected = RetailSystemException.class) public void testAddShopWithInValidData() { Shop shop = new Shop(); shop.setShopName("test name"); Address addr = new Address(); addr.setNumber("invalid address"); addr.setPostCode("invalid address"); shop.setShopAddress(addr); when(geoCodingClientMock.getGeoDetails(any())).thenThrow(new RetailSystemException(ErrorCodes.GEOCODE_FETCH_ERROR)); shopService.addOrReplaceShop(shop); } @Test(expected = RetailSystemException.class) public void testAddShopWithNullShopName() { Shop shop = new Shop(); Address addr = new Address(); addr.setNumber("some address"); addr.setPostCode("some address"); shop.setShopAddress(addr); shopService.addOrReplaceShop(shop); } @Test public void testAddDuplicateShopsWithConcurrentUsers() throws InterruptedException, ExecutionException { Shop shop1 = new Shop(); shop1.setShopName("test"); Address addr1 = new Address(); addr1.setNumber("some address1"); addr1.setPostCode("some address1"); shop1.setShopAddress(addr1); AddShopCallable callable1 = new AddShopCallable(shop1, shopDao); Shop shop2 = new Shop(); shop2.setShopName("test"); Address addr2 = new Address(); addr2.setNumber("some address2"); addr2.setPostCode("some address2"); shop2.setShopAddress(addr2); AddShopCallable callable2 = new AddShopCallable(shop2, shopDao); ExecutorService executor = Executors.newFixedThreadPool(2); Future<Shop> future1 = executor.submit(callable1); Future<Shop> future2 = executor.submit(callable2); Shop oldShop1 = future1.get(); Shop oldShop2 = future2.get(); Assert.assertTrue((null == oldShop1 && oldShop2 != null) || (null == oldShop2 && oldShop1 != null)); } @Test public void testAddUniqueShopsWithConcurrentUsers() throws InterruptedException, ExecutionException { Shop shop1 = new Shop(); shop1.setShopName("test1"); Address addr1 = new Address(); addr1.setNumber("some address1"); addr1.setPostCode("some address1"); shop1.setShopAddress(addr1); AddShopCallable callable1 = new AddShopCallable(shop1, shopDao); Shop shop2 = new Shop(); shop2.setShopName("test2"); Address addr2 = new Address(); addr2.setNumber("some address2"); addr2.setPostCode("some address2"); shop2.setShopAddress(addr2); AddShopCallable callable2 = new AddShopCallable(shop2, shopDao); ExecutorService executor = Executors.newFixedThreadPool(2); Future<Shop> future1 = executor.submit(callable1); Future<Shop> future2 = executor.submit(callable2); Shop oldShop1 = future1.get(); Shop oldShop2 = future2.get(); Assert.assertTrue(null == oldShop1 && null == oldShop2); } @Test public void testGetNearestShopWithValidData1() { Shop shop1 = new Shop(); shop1.setShopName("shop1"); Address addr1 = new Address(); addr1.setNumber("abc"); addr1.setPostCode("ghj"); shop1.setShopAddress(addr1); when(geoCodingClientMock.getGeoDetails(any())).thenReturn(new GeoDetails(18.5822452, 73.6914557)); //add shop1 shopService.addOrReplaceShop(shop1); Shop shop2 = new Shop(); shop2.setShopName("shop2"); Address addr2 = new Address(); addr2.setNumber("abc"); addr2.setPostCode("ghj"); shop2.setShopAddress(addr2); when(geoCodingClientMock.getGeoDetails(any())).thenReturn(new GeoDetails(17.5707615, 78.4339131)); //add shop2 shopService.addOrReplaceShop(shop2); Shop shop3 = new Shop(); shop3.setShopName("shop3"); Address addr3 = new Address(); addr3.setNumber("abc"); addr3.setPostCode("ghj"); shop3.setShopAddress(addr3); when(geoCodingClientMock.getGeoDetails(any())).thenReturn(new GeoDetails(12.9373056, 77.6064054)); //add shop3 shopService.addOrReplaceShop(shop3); Shop nearestShop = shopService.getNearestShop(new GeoDetails(12.937, 77.606)); Assert.assertEquals("shop3", nearestShop.getShopName()); } @Test public void testGetNearestShopWithValidData2() { Shop shop1 = new Shop(); shop1.setShopName("shop1"); Address addr1 = new Address(); addr1.setNumber("abc"); addr1.setPostCode("ghj"); shop1.setShopAddress(addr1); when(geoCodingClientMock.getGeoDetails(any())).thenReturn(new GeoDetails(18.5822452, 73.6914557)); //add shop1 shopService.addOrReplaceShop(shop1); Shop shop2 = new Shop(); shop2.setShopName("shop2"); Address addr2 = new Address(); addr2.setNumber("abc"); addr2.setPostCode("ghj"); shop2.setShopAddress(addr2); when(geoCodingClientMock.getGeoDetails(any())).thenReturn(new GeoDetails(17.5707615, 78.4339131)); //add shop2 shopService.addOrReplaceShop(shop2); Shop shop3 = new Shop(); shop3.setShopName("shop3"); Address addr3 = new Address(); addr3.setNumber("abc"); addr3.setPostCode("ghj"); shop3.setShopAddress(addr3); when(geoCodingClientMock.getGeoDetails(any())).thenReturn(new GeoDetails(12.9373056, 77.6064054)); //add shop3 shopService.addOrReplaceShop(shop3); Shop nearestShop = shopService.getNearestShop(new GeoDetails(18.5822, 73.6914)); Assert.assertEquals("shop1", nearestShop.getShopName()); } @Test public void testGetNearestShopWithValidData3() { Shop shop1 = new Shop(); shop1.setShopName("shop1"); Address addr1 = new Address(); addr1.setNumber("abc"); addr1.setPostCode("ghj"); shop1.setShopAddress(addr1); when(geoCodingClientMock.getGeoDetails(any())).thenReturn(new GeoDetails(18.5822452, 73.6914557)); //add shop1 shopService.addOrReplaceShop(shop1); Shop shop2 = new Shop(); shop2.setShopName("shop2"); Address addr2 = new Address(); addr2.setNumber("abc"); addr2.setPostCode("ghj"); shop2.setShopAddress(addr2); when(geoCodingClientMock.getGeoDetails(any())).thenReturn(new GeoDetails(17.5707615, 78.4339131)); //add shop2 shopService.addOrReplaceShop(shop2); Shop shop3 = new Shop(); shop3.setShopName("shop3"); Address addr3 = new Address(); addr3.setNumber("abc"); addr3.setPostCode("ghj"); shop3.setShopAddress(addr3); when(geoCodingClientMock.getGeoDetails(any())).thenReturn(new GeoDetails(12.9373056, 77.6064054)); //add shop3 shopService.addOrReplaceShop(shop3); Shop nearestShop = shopService.getNearestShop(new GeoDetails(17.570, 78.433)); Assert.assertEquals("shop2", nearestShop.getShopName()); } @Test(expected = RetailSystemException.class) public void testGetNearestShopWithoutANyShopInSystem() { shopService.getNearestShop(new GeoDetails(17.570, 78.433)); } @After public void tearDown() { shopDao.deleteAll(); } } class AddShopCallable implements Callable<Shop> { private Shop shop; private ShopDao shopDao; AddShopCallable(Shop shop,ShopDao shopDao){ this.shop=shop; this.shopDao=shopDao; } public Shop call() throws Exception { return shopDao.createNewOrOverrideExistingShop(shop); } }
package com.example.szupek.datepickerszupek; import android.content.Context; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.example.szupek.datepickerszupek.model.Wesele; public class dodaj_Activity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_dodaj_); TextView data_view = (TextView) findViewById(R.id.textView_dodaj); data_view.setText(getIntent().getStringExtra("Data_wybrana")); } public void DodajSzczegoluButton(View view) { TextView data = (TextView) findViewById(R.id.textView_dodaj); EditText miejscowosc = (EditText) findViewById(R.id.editText_miejscowosc); EditText lokal = (EditText) findViewById(R.id.editTextLokal); EditText imie = (EditText) findViewById(R.id.editImie); EditText nazwisko = (EditText) findViewById(R.id.editNazwisko); EditText uklon = (EditText) findViewById(R.id.editUklon); EditText godzinaUklonu = (EditText) findViewById(R.id.editgodzinaUklonu); EditText cena = (EditText) findViewById(R.id.editCena); EditText wyjazd = (EditText) findViewById(R.id.editGodzinaWyjazdu); EditText tel_mlody = (EditText) findViewById(R.id.edittelefonMlody); EditText tel_mloda = (EditText) findViewById(R.id.editTelefonMloda); //TODO Zrobić dodawanie notatek EditText notatki = (EditText) findViewById(R.id.editText_miejscowosc); String data1 = data.getText().toString(); String miejscowosc1 = miejscowosc.getText().toString(); String lokal1 = lokal.getText().toString(); String imie1 = imie.getText().toString(); String nazwisko1 = nazwisko.getText().toString(); String uklon1 = uklon.getText().toString(); String godzinaUklonu1 = godzinaUklonu.getText().toString(); String cena1 = cena.getText().toString(); String wyjazd1 = wyjazd.getText().toString(); String tel_mlody1 = tel_mlody.getText().toString(); String tel_mloda1 = tel_mloda.getText().toString(); String notatki1 = notatki.getText().toString(); Wesele wesele = new Wesele(data1,miejscowosc1,lokal1,imie1,nazwisko1,uklon1,godzinaUklonu1, cena1,wyjazd1,tel_mlody1,tel_mloda1,notatki1); DAO nowy = new DAO(new DBManager(this)); boolean dodalo = nowy.Dodaj_Wesele(wesele); if (dodalo = true) { Toast.makeText(dodaj_Activity.this, "Wesele dodano do bazy", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(this,dodaj_Activity2.class); intent.putExtra("dataUmowy",data1); startActivity(intent); }else { Toast.makeText(dodaj_Activity.this, "Błąd podczas dodawania do bazy", Toast.LENGTH_SHORT).show(); } } }
package com.radauer.mathrix; import static junit.framework.TestCase.assertNull; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import java.math.BigDecimal; import com.radauer.mathrix.types.GroupKeyFactory; import com.radauer.mathrix.types.GroupKeyFactoryImpl; import com.radauer.mathrix.types.RowTypeFactory; import com.radauer.mathrix.types.RowTypeFactoryImpl; /** * Utitility Methos for helping test the Mathrix */ public class MathrixTestHelper { private static RowTypeFactory rowTypeFactory = new RowTypeFactoryImpl(); private static GroupKeyFactory groupKeyFactory = new GroupKeyFactoryImpl(); public static Position createPosition(String groupCode, String rowKeyTypeCode, String value) { RowType rowType = rowTypeFactory.getRowTyp(rowKeyTypeCode); RowKey rowKey = new RowKey(rowType, ""); return new Position(getGroupKey(groupCode), rowKey, new BigDecimal(value)); } public static void testValue(String groupCode, String rowKeyTypeCode, String valueString, Mathrix mat) { RowType rowType = getRowType(rowKeyTypeCode); RowKey rowKey = new RowKey(rowType, ""); Position pos = mat.getPosition(getGroupKey(groupCode), rowKey); assertNotNull(pos); assertTrue(pos.getValue().compareTo(new BigDecimal(valueString)) == 0); } public static void testValueEmpty(String groupCode, String rowKeyTypeCode, Mathrix mat) { RowType rowType = getRowType(rowKeyTypeCode); RowKey rowKey = new RowKey(rowType, ""); Position pos = mat.getPosition(getGroupKey(groupCode), rowKey); BigDecimal value = pos == null ? null : pos.getValue(); assertNull(value); } public static RowType getRowType(String rowKeyTypeCode) { return rowTypeFactory.getRowTyp(rowKeyTypeCode); } public static RowKey getRowKey(String rowKeyTypeCode) { return new RowKey(getRowType(rowKeyTypeCode), ""); } public static RowType[] getRowTypes(String... typeCodes) { RowType[] result = new RowType[typeCodes.length]; for (int i = 0; i < typeCodes.length; i++) { result[i] = getRowType(typeCodes[i]); } return result; } public static GroupKey getGroupKey(String groupKeyCode) { return groupKeyFactory.getGroupKey(groupKeyCode); } public static GroupKey[] getGroupKeys(String... groupKeyCodes) { GroupKey[] result = new GroupKey[groupKeyCodes.length]; for (int i = 0; i < groupKeyCodes.length; i++) { result[i] = getGroupKey(groupKeyCodes[i]); } return result; } }
/* * 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 diseño; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; /** * * @author zabdy */ public class catalogoventa extends javax.swing.JInternalFrame { /** * Creates new form catalogoventa */ public catalogoventa() { initComponents(); catalogoventa(""); bloquear(); } String idtipoventa=""; /** * 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() { jPopupMenu1 = new javax.swing.JPopupMenu(); jMenuItem2 = new javax.swing.JMenuItem(); jMenuItem3 = new javax.swing.JMenuItem(); jPanel3 = new javax.swing.JPanel(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); txtdscventa = new javax.swing.JTextField(); jPanel2 = new javax.swing.JPanel(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jButton12 = new javax.swing.JButton(); jButton4 = new javax.swing.JButton(); jButton5 = new javax.swing.JButton(); jButton6 = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); tablaventas = new javax.swing.JTable(); txtbotonbuscar = new javax.swing.JTextField(); BuscarDato = new javax.swing.JButton(); jMenuBar1 = new javax.swing.JMenuBar(); jMenuItem2.setText("Modificar"); jMenuItem2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem2ActionPerformed(evt); } }); jPopupMenu1.add(jMenuItem2); jMenuItem3.setText("Eliminar"); jMenuItem3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem3ActionPerformed(evt); } }); jPopupMenu1.add(jMenuItem3); setBackground(new java.awt.Color(204, 0, 0)); setClosable(true); setIconifiable(true); setMaximizable(true); setResizable(true); setTitle("Catalogo de Venta"); jPanel3.setBackground(new java.awt.Color(204, 0, 0)); jPanel1.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jLabel1.setText("Descripcion de la Venta"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(32, 32, 32) .addComponent(txtdscventa, javax.swing.GroupLayout.PREFERRED_SIZE, 253, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtdscventa, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel2.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED)); jButton2.setText("Guardar Datos"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jButton3.setText("Actualizar"); jButton3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton3ActionPerformed(evt); } }); jButton12.setText("Consutar"); jButton12.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton12ActionPerformed(evt); } }); jButton4.setText("Nuevo"); jButton4.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton4ActionPerformed(evt); } }); jButton5.setText("Limpiar"); jButton5.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton5ActionPerformed(evt); } }); jButton6.setText("Salir"); jButton6.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton6ActionPerformed(evt); } }); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, 167, Short.MAX_VALUE) .addComponent(jButton12, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap() .addComponent(jButton4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton12) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton3) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton5) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jButton6) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); tablaventas.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { } )); tablaventas.setComponentPopupMenu(jPopupMenu1); jScrollPane1.setViewportView(tablaventas); BuscarDato.setText("Buscar"); BuscarDato.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { BuscarDatoActionPerformed(evt); } }); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 267, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGroup(jPanel3Layout.createSequentialGroup() .addComponent(txtbotonbuscar, javax.swing.GroupLayout.PREFERRED_SIZE, 193, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(BuscarDato, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel3Layout.createSequentialGroup() .addContainerGap() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(txtbotonbuscar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(BuscarDato)) .addGap(0, 14, Short.MAX_VALUE)) ); setJMenuBar(jMenuBar1); 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 void bloquear(){ txtdscventa.setEnabled(false); txtbotonbuscar.setEnabled(false); jButton2.setEnabled(false); jButton3.setEnabled(false); jButton4.setEnabled(true); jButton5.setEnabled(false); jButton6.setEnabled(true); jButton12.setEnabled(false); } void desbloquear(){ txtdscventa.setEnabled(true); txtbotonbuscar.setEnabled(true); jButton2.setEnabled(true); jButton3.setEnabled(true); jButton4.setEnabled(false); jButton5.setEnabled(true); jButton6.setEnabled(true); jButton12.setEnabled(true); } void limpiar(){ txtdscventa.setText(""); txtbotonbuscar.setText(""); } private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed // TODO add your handling code here: String desven; String sql=""; desven=txtdscventa.getText(); sql= "INSERT INTO cat_tipo_venta (DESC_TIPO_VENTA) VALUES (?)"; try { PreparedStatement psd = cn.prepareStatement(sql); psd.setString(1,desven); int n= psd.executeUpdate(); if (n>0){ JOptionPane.showMessageDialog(null, "REGISTRO GUARDADO CON EXITO"); } } catch (SQLException ex) { Logger.getLogger(usuario.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_jButton2ActionPerformed private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed // TODO add your handling code here: try { String VENTA= idtipoventa; String Descrip = txtdscventa.getText(); PreparedStatement psd = cn.prepareStatement("UPDATE cat_tipo_venta SET DESC_TIPO_VENTA='" + Descrip + "' WHERE ID_TIPO_VENTA= '" + VENTA + "'"); System.out.println(idtipoventa); int n = psd.executeUpdate(); System.out.println(n); if (n > 0) { JOptionPane.showMessageDialog(null, "Registro actualizado"); } else { JOptionPane.showMessageDialog(null, "No se pudo"); } catalogoventa(""); } catch (Exception e) { System.out.println(e.getMessage()); } }//GEN-LAST:event_jButton3ActionPerformed private void jButton12ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton12ActionPerformed // TODO add your handling code here: catalogoventa(""); }//GEN-LAST:event_jButton12ActionPerformed private void BuscarDatoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_BuscarDatoActionPerformed // TODO add your handling code here: catalogoventa(txtbotonbuscar.getText()); }//GEN-LAST:event_BuscarDatoActionPerformed private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed // TODO add your handling code here: desbloquear(); }//GEN-LAST:event_jButton4ActionPerformed private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed // TODO add your handling code here: this.dispose(); }//GEN-LAST:event_jButton6ActionPerformed private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed // TODO add your handling code here: limpiar(); }//GEN-LAST:event_jButton5ActionPerformed private void jMenuItem2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem2ActionPerformed // codigo de catalogo de tipo ventas: int fila = tablaventas.getSelectedRow(); if(fila>=0){ idtipoventa=(tablaventas.getValueAt(fila, 0).toString()); txtdscventa.setText(tablaventas.getValueAt(fila, 1).toString()); } else{ JOptionPane.showMessageDialog(null,"no seleciono fila"); } }//GEN-LAST:event_jMenuItem2ActionPerformed private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jMenuItem3ActionPerformed // TODO add your handling code here: int fila = tablaventas.getSelectedRow(); String cod=""; cod=tablaventas.getValueAt(fila, 0).toString(); try { PreparedStatement psd = cn.prepareStatement("DELETE FROM cat_tipo_venta WHERE ID_TIPO_VENTA ='"+cod+"'"); psd.executeUpdate(); catalogoventa(""); } catch (Exception e) { System.out.println(e); JOptionPane.showMessageDialog(null, "No Puedes Eliminar Esta FILA Hasta Borrar Sus Relaciones"); } }//GEN-LAST:event_jMenuItem3ActionPerformed void catalogoventa (String valor){ DefaultTableModel modelo= new DefaultTableModel(); modelo.addColumn("ID DE LA VENTA"); modelo.addColumn("DESCRIPCION DE LA VENTA"); tablaventas.setModel(modelo); String sql=""; if(valor.equals("")) { sql="SELECT * FROM cat_tipo_venta"; } else{ sql="SELECT * FROM cat_tipo_venta WHERE ID_TIPO_VENTA='"+valor+"'"; } String []datos = new String [2]; try { Statement st = cn.createStatement(); ResultSet rs = st.executeQuery(sql); while(rs.next()){ datos[0]=rs.getString(1); datos[1]=rs.getString(2); modelo.addRow(datos); } tablaventas.setModel(modelo); } catch (SQLException ex) { Logger.getLogger(COnsul.class.getName()).log(Level.SEVERE, null, ex); } } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton BuscarDato; private javax.swing.JButton jButton12; private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JButton jButton4; private javax.swing.JButton jButton5; private javax.swing.JButton jButton6; private javax.swing.JLabel jLabel1; private javax.swing.JMenuBar jMenuBar1; private javax.swing.JMenuItem jMenuItem2; private javax.swing.JMenuItem jMenuItem3; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPopupMenu jPopupMenu1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTable tablaventas; private javax.swing.JTextField txtbotonbuscar; private javax.swing.JTextField txtdscventa; // End of variables declaration//GEN-END:variables conecta cc=new conecta (); Connection cn=cc.conexion(); }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * * @author User */ public class Phone { String display; int battery, price; Phone(){ display = "5.5 Inch"; battery = 5400; price = 20000; } Phone(int battery,int price, String display){ this.display = display; this.battery = battery; this.price = price; } }
/* * Copyright (c) 2008-2019 Haulmont. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.haulmont.reports.util; import com.haulmont.reports.entity.BandDefinition; import com.haulmont.reports.entity.DataSet; import com.haulmont.reports.entity.DataSetType; import com.haulmont.reports.fixture.yml.YmlBandUtil; import com.haulmont.reports.testsupport.ReportsContextBootstrapper; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.core.io.ResourceLoader; import org.springframework.test.context.BootstrapWith; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import javax.inject.Inject; import java.io.IOException; import java.net.URISyntaxException; @RunWith(SpringJUnit4ClassRunner.class) @BootstrapWith(ReportsContextBootstrapper.class) public class DataSetFactoryTest { @Inject private DataSetFactory dataSetFactory; @Inject private ResourceLoader resourceLoader; @Test public void testDataSetEmptyCreation() throws URISyntaxException, IOException { BandDefinition bandDefinition = YmlBandUtil.bandFrom( resourceLoader.getResource("com/haulmont/reports/fixture/dataset-creation.yml").getFile()); Assert.assertNotNull(bandDefinition); DataSet dataSet = dataSetFactory.createEmptyDataSet(bandDefinition); Assert.assertEquals(DataSetType.GROOVY, dataSet.getType()); Assert.assertEquals(bandDefinition, dataSet.getBandDefinition()); } }
package com.qumla.domain.answer; import io.katharsis.resource.annotations.JsonApiIncludeByDefault; import io.katharsis.resource.annotations.JsonApiResource; import io.katharsis.resource.annotations.JsonApiToOne; import java.time.Instant; import java.time.LocalDate; import java.time.ZoneId; import com.qumla.domain.AbstractEntity; import com.qumla.domain.location.Country; import com.qumla.domain.location.Location; import com.qumla.domain.location.LocationData; import com.qumla.domain.question.Option; import com.qumla.domain.question.Question; @JsonApiResource(type="answerstatlocation") public class AnswerStatLocation extends AbstractEntity{ private static final long serialVersionUID = 3443442709351349082L; private Question question; @JsonApiIncludeByDefault @JsonApiToOne private Option option; @JsonApiIncludeByDefault @JsonApiToOne private LocationData location; @JsonApiToOne @JsonApiIncludeByDefault private Country country; private long count; private long total; private float percent; private Option top; private LocalDate firstdate; public AnswerStatLocation() { // TODO Auto-generated constructor stub } public boolean isSerialVersionUID(){ return true; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Question getQuestion() { return question; } public void setQuestion(Question question) { this.question = question; } public Option getOption() { return option; } public void setOption(Option option) { this.option = option; } public LocationData getLocation() { return location; } public void setLocation(LocationData location) { this.location = location; } public Country getCountry() { return country; } public void setCountry(Country country) { this.country = country; } public long getCount() { return count; } public void setCount(long count) { this.count = count; } public long getTotal() { return total; } public void setTotal(long total) { this.total = total; } public float getPercent() { return percent; } public void setPercent(float percent) { this.percent = percent; } public void copyFromAnswer(Answer a){ Question q=new Question(); q.setId(a.getQuestion()); this.setQuestion(q); //this.setAnswerDate(a.getCreateDt()); Country c=new Country(); c.setCode(a.getCountry()); this.setCountry(c); LocationData l=new LocationData(); l.setId(a.getLocation()); this.setLocation(l); Option o=new Option(); o.setId(a.getOption()); this.setOption(o); this.setFirstdate(Instant.ofEpochMilli(a.getCreateDt().getTime()).atZone(ZoneId.systemDefault()).toLocalDate()); } public LocalDate getFirstdate() { return firstdate; } public void setFirstdate(LocalDate firstdate) { this.firstdate = firstdate; } public Option getTop() { return top; } public void setTop(Option top) { this.top = top; } }
package com.taotao.search.controller; import com.taotao.common.pojo.SearchItemResult; import com.taotao.search.service.SearchService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @Controller public class SearcController { private final static Integer rows = 60;//行数s @SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection") @Autowired private SearchService searchService; @RequestMapping("/search") public String search(@RequestParam("q") String queryString, @RequestParam(defaultValue = "1") Integer page,Model model) throws Exception{ queryString = new String(queryString.getBytes("iso8859-1"),"utf-8"); SearchItemResult result = searchService.search(queryString,page,rows); //传递给界面 model.addAttribute("query",queryString); model.addAttribute("totalPages",result.getPageTotal()); model.addAttribute("itemList",result.getSearchList()); model.addAttribute("page",page); //返回逻辑视图 return "search"; } }
package com.eu.manage.service.impl; import com.eu.manage.dao.RoomutilizationDao; import com.eu.manage.entity.Roomutilization; import com.eu.manage.service.RoomutilizationService; import com.eu.manage.utils.PageUtil; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.List; import java.util.Map; @Service public class RoomutilizationServiceImpl implements RoomutilizationService { @Autowired RoomutilizationDao roomutilizationDao; @Override public List<Map<String, Object>> showRoomutilization(PageUtil pageUtil, Roomutilization roomutilization) { Map<String, Object> data = new HashMap<>(); data.put("start", (pageUtil.getCurrentIndex() - 1) * pageUtil.getPageSize()); data.put("size", pageUtil.getPageSize()); data.put("month", roomutilization.getMonth()); data.put("year", roomutilization.getYear()); data.put("type", roomutilization.getType()); pageUtil.setTotalSize(roomutilizationDao.selectTotalSize(roomutilization)); return roomutilizationDao.showRoomutilization(data); } @Override public void addRoomutilization(Roomutilization roomutilization) { roomutilizationDao.addRoomutilization(roomutilization); } @Override public List<Map<String, Object>> findRoomutilizationById(String id) { return roomutilizationDao.findRoomutilizationById(id); } @Override public void updateRoomutilization(Roomutilization roomutilization) { roomutilizationDao.updateRoomutilization(roomutilization); } @Override public void deleteRoomutilizationById(String id) { roomutilizationDao.deleteRoomutilizationById(id); } }
package tn.orange.secoure; import android.app.TabActivity; import android.content.Intent; import android.graphics.Color; import android.os.Bundle; import android.widget.TabHost; import android.widget.TabHost.TabSpec; public class Settings extends TabActivity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.settings_frame); final TabHost tabHost = getTabHost(); // Tab for Songs TabSpec songspec = tabHost.newTabSpec("Badge"); songspec.setIndicator("", getResources().getDrawable(R.drawable.badge)); Intent songsIntent = new Intent(this, PHS.class); songspec.setContent(songsIntent); // Tab for Photos TabSpec photospec = tabHost.newTabSpec("Contacts"); photospec.setIndicator("", getResources().getDrawable(R.drawable.contacts)); Intent photosIntent = new Intent(this, Contacts.class); photospec.setContent(photosIntent); tabHost.getTabWidget().setBackgroundColor(Color.parseColor("#FFFFFF")); tabHost.addTab(songspec); tabHost.addTab(photospec); // Adding photos tab setTabColor(tabHost); // Adding all TabSpec to TabHost } public static void setTabColor(TabHost tabhost) { for(int i=0;i<tabhost.getTabWidget().getChildCount();i++) { tabhost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#990000")); //unselected } tabhost.getTabWidget().getChildAt(tabhost.getCurrentTab()).setBackgroundColor(Color.parseColor("#990000")); // selected } }
import java.lang.reflect.Array; import java.util.Arrays; import java.util.List; import java.util.ArrayList; import java.util.Queue; import java.util.LinkedList; import java.util.Set; import java.util.HashSet; public class Tester { private static class Node { String val; List<Node> friends; Node(String theVal) { val = theVal; } @Override public String toString() { return "Node {" + val + "}"; } } public List<Node> findFriends(Node root) { if (root == null) { return new ArrayList<>(0); // default capacity is 10 } Set<Node> herFriends = new HashSet<>(root.friends); herFriends.add(root); Set<Node> newFriends = new HashSet<>(); Queue<Node> nodesToCheck = new LinkedList<>(); nodesToCheck.offer(root); int layer = 0; while (!nodesToCheck.isEmpty() && layer < 3) { int size = nodesToCheck.size(); for(int i = 0; i < size; i++) { Node curr = nodesToCheck.poll(); for (Node friend : curr.friends) { if (!herFriends.contains(friend) && !newFriends.contains(friend)) { newFriends.add(friend); } nodesToCheck.add(friend); } } layer++; } return new ArrayList<>(newFriends); } public static void main(String[] args) { Tester t = new Tester(); Node a = new Node("a"); Node b = new Node("b"); Node c = new Node("c"); Node d = new Node("d"); Node e = new Node("e"); Node f = new Node("f"); Node g = new Node("g"); a.friends = Arrays.asList(b, c, d, e); b.friends = Arrays.asList(f, g); c.friends = Arrays.asList(); d.friends = Arrays.asList(a, e); e.friends = Arrays.asList(a, d); f.friends = Arrays.asList(b); g.friends = Arrays.asList(b); System.out.println(t.findFriends(a)); } }
package simple_armors_mod; import com.google.common.collect.Multimap; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.client.renderer.texture.IconRegister; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.entity.Entity; import net.minecraft.entity.EntityLiving; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.SharedMonsterAttributes; import net.minecraft.entity.ai.attributes.AttributeModifier; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.EnumAction; import net.minecraft.item.EnumToolMaterial; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.item.ItemSword; import net.minecraft.potion.Potion; import net.minecraft.potion.PotionEffect; import net.minecraft.world.World; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class ItemPoisonedSword extends ItemSword{ public ItemPoisonedSword(int par1, EnumToolMaterial par2EnumToolMaterial, int material) { super(par1, par2EnumToolMaterial); this.setCreativeTab(null); this.setMaterialType(material); } private String iconPath; /* 0 = wood 1 = stone 2 = iron 3 = diamond 4 = gold */ private void setMaterialType(int type){ switch (type){ case 0: this.setUnlocalizedName("PoisonedWoodSword"); this.iconPath = "armory:PoisonedWoodSword"; break; case 1: this.setUnlocalizedName("PoisonedStoneSword"); this.iconPath = "armory:PoisonedStoneSword"; break; case 2: this.setUnlocalizedName("PoisonedIronSword"); this.iconPath = "armory:PoisonedIronSword"; break; case 3: this.setUnlocalizedName("PoisonedDiamondSword"); this.iconPath = "armory:PoisonedDiamondSword"; break; case 4: this.setUnlocalizedName("PoisonedGoldSword"); this.iconPath = "armory:PoisonedGoldSword"; break; case 5: this.setUnlocalizedName("PoisonedTinSword"); this.iconPath = "armory:PoisonedTinSword"; break; } } public void registerIcons(IconRegister icon){ this.itemIcon = icon.registerIcon(this.iconPath); } public boolean hasEffect(ItemStack stack){ return true; } public boolean hitEntity(ItemStack par1ItemStack, EntityLivingBase par2EntityLivingBase, EntityLivingBase par3EntityLivingBase){ par2EntityLivingBase.addPotionEffect(new PotionEffect(Potion.poison.id, 60, 2)); return true;} }
package de.wiltherr.ws2812fx.serial.entity.uint; public class UInt16 extends AbstractUInt { public static final int MAX_VALUE = 65535; public static final int BIT_SIZE = 16; public static final int BYTE_SIZE = 2; private byte[] bytes; UInt16(byte[] byteArray) { super(byteArray, Type.U_INT_16); bytes = byteArray; } UInt16(int uInt) { super(uInt, Type.U_INT_16); bytes = new byte[]{ (byte) (uInt >> 8), (byte) uInt}; } public static UInt16 valueOf(int uInt) { return new UInt16(uInt); } public boolean isValidUInt16(long uInt) { return isValidUInt(uInt); } @Override public long toLong() { return asInt(); } @Override public byte[] getBytes() { return bytes; } private int asInt() { //interpret bytes as unsigned 16 bit integer (BigEndian) return bytes[1] & 0xFF | (bytes[0] & 0xFF) << 8; } }
package algo3.fiuba.modelo.campo; import algo3.fiuba.modelo.excepciones.CampoNoPermiteColocarCartaExcepcion; import java.util.LinkedList; import java.util.List; public class ZonaCartas<T> { private List<T> cartas; private Integer limite; private T cartaNula; public ZonaCartas(Integer limite, T cartaNula) { this.limite = limite; this.cartas = new LinkedList<>(); this.cartaNula = cartaNula; for (int i = 0; i < this.limite; i++) { cartas.add(cartaNula); } } public void agregar(T carta) { if (this.tamanio() >= limite) throw new CampoNoPermiteColocarCartaExcepcion(String.format("No se puede tener más de %d cartas de ese tipo en el campo.", limite)); Integer indicePrimerCartaNula = 0; for (T c : cartas) { if (c.equals(cartaNula)) { break; } indicePrimerCartaNula++; } cartas.remove(cartaNula); cartas.add(indicePrimerCartaNula, carta); } public void remover(T carta) { Integer i = 0; for (T c : cartas) { if (carta.equals(c)) { cartas.add(i, cartaNula); break; } i++; } cartas.remove(carta); } public boolean contiene(T carta) { return cartas.contains(carta); } public boolean estaVacia() { return this.tamanio() == 0; } public Integer tamanio() { Integer tamanio = 0; for (T c : cartas) { if (!c.equals(cartaNula)) { tamanio++; } } return tamanio; } public List<T> getCartas() { return cartas; } }
package com.zhss.oa.auth.model; /** * 授权实体类 * @author zhonghuashishan * */ public class Authorization { private Long id; private Long employeeId; private Long roleId; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getEmployeeId() { return employeeId; } public void setEmployeeId(Long employeeId) { this.employeeId = employeeId; } public Long getRoleId() { return roleId; } public void setRoleId(Long roleId) { this.roleId = roleId; } }
//License /*** * Java Modbus Library (jamod) * Copyright (c) 2002-2004, jamod development team * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the author nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS ``AS * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. ***/ package net.wimpi.modbus.msg; //import java.io.EOFException; //import java.io.IOException; import net.wimpi.modbus.io.Transportable; /** * Interface defining a ModbusMessage. * * @author Dieter Wimberger * @version 1.2rc1 (09/11/2004) */ public interface ModbusMessage extends Transportable { /** * Sets the flag that marks this <tt>ModbusMessage</tt> as headless * (for serial transport). */ public void setHeadless(); /** * Returns the transaction identifier of this * <tt>ModbusMessage</tt> as <tt>int</tt>.<br> * The identifier is a 2-byte (short) non negative * integer value valid in the range of 0-65535. * <p> * @return the transaction identifier as <tt>int</tt>. */ public int getTransactionID(); /** * Returns the protocol identifier of this * <tt>ModbusMessage</tt> as <tt>int</tt>.<br> * The identifier is a 2-byte (short) non negative * integer value valid in the range of 0-65535. * <p> * @return the protocol identifier as <tt>int</tt>. */ public int getProtocolID(); /** * Returns the length of the data appended * after the protocol header. * <p> * @return the data length as <tt>int</tt>. */ public int getDataLength(); /** * Returns the unit identifier of this * <tt>ModbusMessage</tt> as <tt>int</tt>.<br> * The identifier is a 1-byte non negative * integer value valid in the range of 0-255. * <p> * @return the unit identifier as <tt>int</tt>. */ public int getUnitID(); /** * Returns the function code of this * <tt>ModbusMessage</tt> as <tt>int</tt>.<br> * The function code is a 1-byte non negative * integer value valid in the range of 0-127.<br> * Function codes are ordered in conformance * classes their values are specified in * <tt>net.wimpi.modbus.Modbus</tt>. * <p> * @return the function code as <tt>int</tt>. * * @see net.wimpi.modbus.Modbus */ public int getFunctionCode(); /** * Writes this <tt>ModbusMessage</tt> to the * given raw <tt>OutputStream</tt>. * <p> * @param out the <tt>OutputStream</tt> to write to. * * @throws Exception if it fails to write to * the given <tt>OutputStream</tt>. * @throws Exception if the stream ended * before all data has been written to it. * public void writeTo(OutputStream out) throws EOFException, IOException; */ /** * Returns the <i>raw</i> message as an array of * bytes. * <p> * @return the <i>raw</i> message as <tt>byte[]</tt>. * public byte[] getMessage(); */ /** * Returns the <i>raw</i> message as <tt>String</tt> * containing a hexadecimal series of bytes. * <br> * This method is specially for debugging purposes, * allowing to log the communication in a manner used * in the specification document. * <p> * @return the <i>raw</i> message as <tt>String</tt> * containing a hexadecimal series of bytes. * */ public String getHexMessage(); /** * Returns the total length this <tt>ModbusMessage</tt>. * <p> * @return the length as <tt>int</tt>. * public int length(); */ }//interface ModbusMessage
// ClosureParser // Author: Niko Pinnis // version 0.1 // License MIT package nip; //import com.sun.istack.internal.NotNull; public class ClosureParser { public static int countDepth(String string, String[] closures) { return countDepth(string, closures[0], closures[1]); } public static int countDepth(String string, String closureOpening, String closureClosing) { if (string == null || string.length() < 2) return 0; int firstOpening = string.indexOf(closureOpening); int lastClosing = string.lastIndexOf(closureClosing); if (firstOpening == -1 || lastClosing == -1) return 0; if (firstOpening >= lastClosing) return 0; StringBuffer s = new StringBuffer(string); int level = 0; while (parseShallow(String.valueOf(s), closureOpening, closureClosing).length() > 0) { s = new StringBuffer(parseShallow(String.valueOf(s), closureOpening, closureClosing)); level++; } return level; } public static String parseDeep(String string, String[] closures) { return parseDeep(string, closures[0], closures[1]); } public static String parseDeep(String string, String closureOpening, String closureClosing) { if (closureOpening == null || closureClosing == null) return ""; // if (string.equals(closureOpening + closureClosing)) return ""; StringBuilder s = new StringBuilder(string.trim()); int start = s.lastIndexOf(closureOpening); int end = s.indexOf(closureClosing); if (start == -1 || end == -1) return ""; if (start >= end) return ""; return s.substring(start + 1, end); } public static String parseShallow(String string, String[] closures) { return parseShallow(string, closures[0], closures[1]); } public static String parseShallow(String string, String closureOpening, String closureClosing) { if (closureOpening == null || closureClosing == null) return ""; // if(string.equals(closureOpening+closureClosing)) return ""; StringBuilder s = new StringBuilder(string.trim()); int start = s.indexOf(closureOpening); int end = s.lastIndexOf(closureClosing); if (start == -1 || end == -1) return ""; if(start >= end) return ""; return string.substring(start + 1, end); // return ""; } public static void main(String[] args) { System.out.println(parseShallow("{oneleveldeep}", "{", "}")); System.out.println(parseShallow("{two{level}deep}", "{", "}")); System.out.println(parseShallow("{three{le{v}el}deep}", "{", "}")); System.out.println("----------------------------------------------------------------------"); System.out.println(parseDeep("{oneleveldeep}", "{", "}")); System.out.println(parseDeep("{two{level}deep}", "{", "}")); System.out.println(parseDeep("{three{le{v}el}deep}", "{", "}")); System.out.println("-----------------------------------------------------------------------"); System.out.println(countDepth("{oneleveldeep}", "{", "}")); System.out.println(countDepth("{ }", "{", "}")); System.out.println("---------------------------------------------------------------------"); System.out.println(countDepth("{two{level}deep}", "{", "}")); System.out.println(countDepth("{{level}}", "{", "}")); System.out.println(countDepth("{two{level}two}", "{", "}")); System.out.println("---------------------------------------------------------------------"); System.out.println(countDepth("{three{le{v}el}deep}", "{", "}")); System.out.println("------------------------------------------------------------------------"); System.out.println(countDepth("{a{b{c{D}e}f}g}", "{", "}")); System.out.println("----------------------------------------------------------------------"); System.out.println(countDepth("{{{{{o7}}}}}", "{", "}")); } }
package se.ade.autoproxywrapper.config.model; import javafx.collections.ObservableList; import se.ade.autoproxywrapper.loopback.LoopBackConfig; import se.ade.autoproxywrapper.model.ForwardProxy; import java.util.ArrayList; import java.util.List; public class GsonConfig { private List<ForwardProxy> forwardProxies = new ArrayList<>(); private List<String> blockedHosts = new ArrayList<>(); private List<String> directModeHosts = new ArrayList<>(); private List<LoopBackConfig> loopBackConfigs = new ArrayList<>(); private int localPort; private boolean enabled = true; private boolean startMinimized; private boolean verboseLogging; private boolean blockedHostsEnabled; private boolean directModeHostsEnabled; public List<ForwardProxy> getForwardProxies() { return forwardProxies; } public List<String> getBlockedHosts() { return blockedHosts; } public List<String> getDirectModeHosts() { return directModeHosts; } public List<LoopBackConfig> getLoopBackConfigs() { return loopBackConfigs; } public void setForwardProxies(List<ForwardProxy> forwardProxies) { this.forwardProxies = forwardProxies; } public int getLocalPort() { return localPort; } public void setLocalPort(int localPort) { this.localPort = localPort; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public boolean isStartMinimized() { return startMinimized; } public void setStartMinimized(boolean startMinimized) { this.startMinimized = startMinimized; } public boolean isVerboseLogging() { return verboseLogging; } public void setVerboseLogging(boolean verboseLogging) { this.verboseLogging = verboseLogging; } public void setDirectModeHosts(List<String> items) { this.directModeHosts = items; } public void setBlockedHosts(List<String> blockedHosts) { this.blockedHosts = blockedHosts; } public boolean isBlockedHostsEnabled() { return blockedHostsEnabled; } public void setBlockedHostsEnabled(boolean blockedHostsEnabled) { this.blockedHostsEnabled = blockedHostsEnabled; } public boolean isDirectModeHostsEnabled() { return directModeHostsEnabled; } public void setDirectModeHostsEnabled(boolean directModeHostsEnabled) { this.directModeHostsEnabled = directModeHostsEnabled; } public void setLoopbackConfigs(ObservableList<LoopBackConfig> items) { this.loopBackConfigs = items; } }
package com.example.waymon.coolweather.util; /** * Created by Administrator on 2016/6/11 0011. */ public interface HttpCallbackListener { void onFinished(String response); void onError(Exception e); }
package gov.nih.mipav.view.renderer.J3D.surfaceview; import gov.nih.mipav.model.structures.*; import gov.nih.mipav.view.renderer.J3D.*; import javax.media.j3d.*; import javax.vecmath.*; /** * Used to generate a scene node item that that represents the rendering of the volume using texture maps. */ public class NodeVolumeTextureRender extends TransformGroup { //~ Static fields/initializers ------------------------------------------------------------------------------------- /** Used to represent undefined AXIS_*. */ private static final int AXIS_UNDEFINED = -1; /** Render volume YZ planes in order of increasing/decreasing X. Parameter to selectSlices method. */ private static final int AXIS_X = 0; /** Render volume ZX planes in order of increasing/decreasing Y. Parameter to selectSlices method. */ private static final int AXIS_Y = 1; /** Render volume XY planes in order of increasing/decreasing Z. Parameter to selectSlices method. */ private static final int AXIS_Z = 2; /** Render selected planes in order of increasing/decreasing coordinate. */ private static final int AXIS_INC = 0; /** DOCUMENT ME! */ private static final int AXIS_DEC = 1; //~ Instance fields ------------------------------------------------------------------------------------------------ /** Maximum voxel resolution of X, Y, Z. */ private float fMax; /** Voxel resolution in the X direction. */ private float fMaxX; /** Voxel resolution in the Y direction. */ private float fMaxY; /** Voxel resolution in the Z direction. */ private float fMaxZ; /** Max Dimension of X, Y, and Z. */ private int iDimMax; /** X Dimension. */ private int iDimX; /** Y Dimension. */ private int iDimY; /** Z Dimension. */ private int iDimZ; /** * This contains the childIndexOrder arrays for the axis' OrderedGroup, one for each possible way to slice the * volume (by axis and by direction). The first array loops over slice axis (AXIS_[XYZ] constants) and the second * array loops over direction (increasing or decreasing coordinate based on AXIS_INC or AXIS_DEC constant). the * third array contains the childIndexOrder array which has dimension equal to the number of samples in the volume * for the corresponding axis (X, Y, or Z). */ private final int[][][] m_aaaiOrderedGroupChildIndexOrder = new int[3][2][]; /** * The contents of each slice that can be rendered will be contained in an OrderedGroup node. An OrderedGroup is * chosen because it ensures the order which the nodes in the group are rendered. */ private final OrderedGroup[] m_akOrderedGroupNodeSlices = new OrderedGroup[3]; /** Render the slices by increasing or decreasing coordinate. */ private boolean m_bIncreasingOrder; /** * Keep track of which direction along the currently selected slicing axis has been selected for rendering the * slices. */ private int m_iAxisDirection = AXIS_UNDEFINED; /** Keep track of which axis has been currently selected for slicing the volume for rendering. */ private int m_iAxisSlice = AXIS_UNDEFINED; /** The same appearance properties used to render each slice. */ private Appearance m_kAppearance = new Appearance(); /** * This is the only node attached to the TransformGroup. This node is a container of OrderedGroups, one OrderedGroup * instance for each axis. Only one child node is selected at any time. */ private Switch m_kSwitch = new Switch(); //~ Constructors --------------------------------------------------------------------------------------------------- /** * Create the scene graph node for the rendering of the volume data, everything except the textures from the volume * data to be applied to the slices through the volume. * * @param image reference to the image volume (data and header information) the same description * parameters * @param kVolumeTexture VolumeTexture-derived instance which contains the texture properties. This description * parameters for the volume associated with this instance must match the parameters for * which this node and its geometry. */ public NodeVolumeTextureRender(ModelImage image, VolumeTexture kVolumeTexture) { super(); init(image, kVolumeTexture); } /** * Create the scene graph node for the rendering of the volume data, everything except the textures from the volume * data to be applied to the slices through the volume. * * @param image reference to the image volume (data and header information) the same description * parameters * @param kVolumeTexture VolumeTexture-derived instance which contains the texture properties. This description * parameters for the volume associated with this instance must match the parameters for * which this node and its geometry. * @param iAxis one of AXIS_X, AXIS_Y, or AXIS_Z which selects the axis of slicing * @param bIncreasingOrder true to select order of slices by increasing coordinate; false to select decreasing */ public NodeVolumeTextureRender(ModelImage image, VolumeTexture kVolumeTexture, int iAxis, boolean bIncreasingOrder) { super(); init(image, kVolumeTexture); selectSlices(iAxis, bIncreasingOrder); } //~ Methods -------------------------------------------------------------------------------------------------------- /** * Clean up memory of this class. */ public void dispose() { // System.out.println("NodeVolumeTextuerRender"); for (int iSliceX = 0; iSliceX < iDimX; ++iSliceX) { Shape3D kShape = (Shape3D) m_akOrderedGroupNodeSlices[AXIS_X].getChild(iSliceX); kShape.removeAllGeometries(); } m_akOrderedGroupNodeSlices[AXIS_X].removeAllChildren(); m_akOrderedGroupNodeSlices[AXIS_X] = null; for (int iSliceY = 0; iSliceY < iDimY; ++iSliceY) { Shape3D kShape = (Shape3D) m_akOrderedGroupNodeSlices[AXIS_Y].getChild(iSliceY); kShape.removeAllGeometries(); } m_akOrderedGroupNodeSlices[AXIS_Y].removeAllChildren(); m_akOrderedGroupNodeSlices[AXIS_Y] = null; for (int iSliceZ = 0; iSliceZ < iDimZ; ++iSliceZ) { Shape3D kShape = (Shape3D) m_akOrderedGroupNodeSlices[AXIS_Z].getChild(iSliceZ); kShape.removeAllGeometries(); } m_akOrderedGroupNodeSlices[AXIS_Z].removeAllChildren(); m_akOrderedGroupNodeSlices[AXIS_Z] = null; m_aaaiOrderedGroupChildIndexOrder[AXIS_X][AXIS_INC] = null; m_aaaiOrderedGroupChildIndexOrder[AXIS_X][AXIS_DEC] = null; m_aaaiOrderedGroupChildIndexOrder[AXIS_Y][AXIS_INC] = null; m_aaaiOrderedGroupChildIndexOrder[AXIS_Y][AXIS_DEC] = null; m_aaaiOrderedGroupChildIndexOrder[AXIS_Z][AXIS_INC] = null; m_aaaiOrderedGroupChildIndexOrder[AXIS_Z][AXIS_DEC] = null; m_kSwitch.removeAllChildren(); m_kSwitch = null; m_kAppearance.setTexture(null); m_kAppearance.setTexCoordGeneration(null); m_kAppearance.setTransparencyAttributes(null); m_kAppearance = null; } /** * Return which axis has been currently selected for slicing the volume for rendering. * * @return the current axis for slicing the volume for rendering. */ public int getAxisSlice() { return m_iAxisSlice; } /** * Return the increasing order flag. * * @return the increasing/decreasing slice order flag. */ public boolean getIncreasingOrder() { return m_bIncreasingOrder; } /** * Not used at the moment. Update the opacity from the relate opacity change slider * * @param iValue Opacity value from the opacity slider */ public void updateOpacity(int iValue) { System.out.println("NodeVolumeTextureRender.updateOpacity iValue = " + iValue); TransparencyAttributes tap = m_kAppearance.getTransparencyAttributes(); tap.setTransparency(1.0f - (iValue / 100.0f)); // 0 = Opaque } /** * Automatically call selectSlices with the correct axis (X, Y, or Z) and increasing/decreasing coordinate order * flag based on the specified view direction vector such that the slices are rendered back to front for the plane * which is most parallel to the view plane. * * @param kViewDir view direction vector in virtual world coordinates */ public void updateSlicing(Vector3d kViewDir) { // Get the transform from local coordinates of the texture // volume renderer node to virtual world coordinates. // This call should not result in the returned transformation // including the sample-to-local coordinate transform for the // the transformation set at this TransformGroup. Transform3D kTransform = new Transform3D(); try { getLocalToVworld(kTransform); } catch (RestrictedAccessException e) { } // What we actually need is the transform from view coordinates // to local coordinates. kTransform.invert(); // Convert the view direction vector to local coordinates. Vector3d kViewDirLocal = new Vector3d(); kTransform.transform(kViewDir, kViewDirLocal); // Determine which axis is most parallel to the viewing direction. // That would be the one which has the largest magnitude. // Then if the sign of that view vector for that axis is positive // (negative), then select the slices in decreasing (increasing) // order in order to get back to front rendering. double dMagX = Math.abs(kViewDirLocal.x); double dMagY = Math.abs(kViewDirLocal.y); double dMagZ = Math.abs(kViewDirLocal.z); if ((dMagX >= dMagY) && (dMagX >= dMagZ)) { selectSlices(AXIS_X, kViewDirLocal.x < 0.0); } else if ((dMagY >= dMagX) && (dMagY >= dMagZ)) { selectSlices(AXIS_Y, kViewDirLocal.y < 0.0); } else { selectSlices(AXIS_Z, kViewDirLocal.z < 0.0); } } /** * Automatically call selectSlices with the correct axis (X, Y, or Z) and increasing/decreasing coordinate order * flag based on the specified view direction vector such that the slices are rendered back to front for the plane * which is most parallel to the view plane. * * @param kViewTransform current view transform in virtual world coordinates */ public void updateView(Transform3D kViewTransform) { // Before projection, the viewing direction vector is (0,0,-1). // Transform this vector by the current viewing transform. Vector3d kViewDir = new Vector3d(); kViewTransform.transform(new Vector3d(0.0, 0.0, -1.0), kViewDir); // Get the transform from local coordinates of the texture // volume renderer node to virtual world coordinates. // This call should not result in the returned transformation // including the sample-to-local coordinate transform for the // the transformation set at this TransformGroup. Transform3D kTransform = new Transform3D(); try { getLocalToVworld(kTransform); } catch (RestrictedAccessException e) { } // What we actually need is the transform from view coordinates // to local coordinates. kTransform.invert(); // Convert the view direction vector to local coordinates. Vector3d kViewDirLocal = new Vector3d(); kTransform.transform(kViewDir, kViewDirLocal); // Determine which axis is most parallel to the viewing direction. // That would be the one which has the largest magnitude. // Then if the sign of that view vector for that axis is positive // (negative), then select the slices in decreasing (increasing) // order in order to get back to front rendering. double dMagX = Math.abs(kViewDirLocal.x); double dMagY = Math.abs(kViewDirLocal.y); double dMagZ = Math.abs(kViewDirLocal.z); if ((dMagX >= dMagY) && (dMagX >= dMagZ)) { selectSlices(AXIS_X, kViewDirLocal.x < 0.0); } else if ((dMagY >= dMagX) && (dMagY >= dMagZ)) { selectSlices(AXIS_Y, kViewDirLocal.y < 0.0); } else { selectSlices(AXIS_Z, kViewDirLocal.z < 0.0); } } /** * Used to call dispose of this class to clean up memory. * * @throws Throwable DOCUMENT ME! */ protected void finalize() throws Throwable { dispose(); super.finalize(); } /** * Initialize the scene graph node for the rendering of the volume data, everything except the textures from the * volume data to be applied to the slices through the volume. * * @param image reference to the image volume (data and header information) the same description * parameters * @param kVolumeTexture VolumeTexture-derived instance which contains the texture properties. This description * parameters for the volume associated with this instance must match the parameters for * which this node and its geometry. */ private void init(ModelImage image, VolumeTexture kVolumeTexture) { // Make note of the dimensions of each axis in the volume. iDimX = image.getExtents()[0]; iDimY = image.getExtents()[1]; iDimZ = image.getExtents()[2]; iDimMax = iDimX; /* Changed to iDim -1 so that the values are consistent with * VolumeTexture: */ fMaxX = (float) (iDimX - 1) * image.getFileInfo(0).getResolutions()[0]; fMaxY = (float) (iDimY - 1) * image.getFileInfo(0).getResolutions()[1]; fMaxZ = (float) (iDimZ - 1) * image.getFileInfo(0).getResolutions()[2]; fMax = fMaxX; if (fMaxY > fMax) { fMax = fMaxY; } if (fMaxZ > fMax) { fMax = fMaxZ; } if (iDimY > iDimMax) { iDimMax = iDimY; } if (iDimZ > iDimMax) { iDimMax = iDimZ; } iDimX = iDimMax; iDimY = iDimMax; iDimZ = iDimMax; // Setup the switch node which will contains the three axes // to slice the volume for rendering. Only one of these sets // of axis slices can be displayed at a time. Allow the // following items to be modified once the scene graph is compiled: // (1) the selected item in the switch node, and(2) the index order // in each each OrderedGroup (to allow for always rendering in // back to front order). Also, allow the children in the ordered // group to be read once the scene graph is compiled, and allow // the node to have its current local to virtual-world transform read. for (int iAxis = 0; iAxis < 3; ++iAxis) { m_akOrderedGroupNodeSlices[iAxis] = new OrderedGroup(); m_akOrderedGroupNodeSlices[iAxis].setCapability(OrderedGroup.ALLOW_CHILD_INDEX_ORDER_WRITE); m_akOrderedGroupNodeSlices[iAxis].setCapability(Group.ALLOW_CHILDREN_READ); m_akOrderedGroupNodeSlices[iAxis].setCapability(Group.ALLOW_CHILDREN_WRITE); m_akOrderedGroupNodeSlices[iAxis].setCapability(BranchGroup.ALLOW_DETACH); m_kSwitch.addChild(m_akOrderedGroupNodeSlices[iAxis]); } m_kSwitch.setWhichChild(Switch.CHILD_NONE); m_kSwitch.setCapability(Switch.ALLOW_SWITCH_WRITE); m_kSwitch.setCapability(Switch.ALLOW_CHILDREN_WRITE); m_kSwitch.setCapability(Switch.ALLOW_CHILDREN_READ); addChild(m_kSwitch); setCapability(Node.ALLOW_LOCAL_TO_VWORLD_READ); setCapability(Group.ALLOW_CHILDREN_READ); setCapability(Group.ALLOW_CHILDREN_WRITE); setCapability(TransformGroup.ALLOW_TRANSFORM_WRITE); // Allocate for the array to store the childIndex. // The last dimension will be sized based on the number of // samples in the volume for that axis. Then the array // will be filled in with the numbers 0,...,N-1 or // N-1,...,0 based on whether the direction is increasing // or decreasing. m_aaaiOrderedGroupChildIndexOrder[AXIS_X][AXIS_INC] = new int[iDimX]; m_aaaiOrderedGroupChildIndexOrder[AXIS_X][AXIS_DEC] = new int[iDimX]; m_aaaiOrderedGroupChildIndexOrder[AXIS_Y][AXIS_INC] = new int[iDimY]; m_aaaiOrderedGroupChildIndexOrder[AXIS_Y][AXIS_DEC] = new int[iDimY]; m_aaaiOrderedGroupChildIndexOrder[AXIS_Z][AXIS_INC] = new int[iDimZ]; m_aaaiOrderedGroupChildIndexOrder[AXIS_Z][AXIS_DEC] = new int[iDimZ]; // Appearance: RenderingAttributes // Do not waste time rendering when alpha is zero. RenderingAttributes kRenderingAttributes = new RenderingAttributes(); kRenderingAttributes.setAlphaTestValue(0.0f); kRenderingAttributes.setAlphaTestFunction(RenderingAttributes.GREATER); m_kAppearance.setRenderingAttributes(kRenderingAttributes); // Appearance: PolygonAttributes // Do not perform any backface/frontbace polygon culling // since we will want to render either side of a slice face. PolygonAttributes kPolygonAttributes = new PolygonAttributes(); kPolygonAttributes.setCullFace(PolygonAttributes.CULL_NONE); m_kAppearance.setPolygonAttributes(kPolygonAttributes); // Appearance: Material // Disable lighting so that the color information comes from // the texture maps. Material kMaterial = new Material(); kMaterial.setLightingEnable(false); m_kAppearance.setMaterial(kMaterial); // Appearance: TransparencyAttributes // Use blended transparency mode which has the default blending // operation set to alpha_src*src + (1-alpha_src)*dst. This works // only for back to front ordering. TransparencyAttributes kTransparencyAttr = new TransparencyAttributes(); kTransparencyAttr.setTransparency(1.0f); kTransparencyAttr.setTransparencyMode(TransparencyAttributes.BLENDED); kTransparencyAttr.setCapability(TransparencyAttributes.ALLOW_VALUE_WRITE); kTransparencyAttr.setCapability(TransparencyAttributes.ALLOW_MODE_WRITE); kTransparencyAttr.setCapability(TransparencyAttributes.ALLOW_BLEND_FUNCTION_WRITE); kTransparencyAttr.setSrcBlendFunction(TransparencyAttributes.BLEND_SRC_ALPHA); // Good kTransparencyAttr.setDstBlendFunction(TransparencyAttributes.BLEND_ONE_MINUS_SRC_ALPHA); // Good m_kAppearance.setTransparencyAttributes(kTransparencyAttr); m_kAppearance.setCapability(Appearance.ALLOW_TRANSPARENCY_ATTRIBUTES_READ); m_kAppearance.setCapability(Appearance.ALLOW_TRANSPARENCY_ATTRIBUTES_WRITE); // Appearance: TextureAttributes // Use Replace mode because we don't want to have to worry about // what color the slice is rendered as before the texture is // applied to it. TextureAttributes kTextureAttr = new TextureAttributes(); kTextureAttr.setTextureMode(TextureAttributes.REPLACE); m_kAppearance.setTextureAttributes(kTextureAttr); // Appearance: Texture // Allow the Texture attribute to be modified. m_kAppearance.setTexture(kVolumeTexture.getTexture()); m_kAppearance.setCapability(Appearance.ALLOW_TEXTURE_WRITE); // Appearance: (TexCoordGeneration) // Allow the TexCoordGeneration attribute to be modified. m_kAppearance.setTexCoordGeneration(kVolumeTexture.getTexCoordGeneration()); m_kAppearance.setCapability(Appearance.ALLOW_TEXGEN_WRITE); // These are the coordinate bounds of the volume double dX0 = -fMaxX / fMax; double dY0 = -fMaxY / fMax; double dZ0 = -fMaxZ / fMax; double dX1 = fMaxX / fMax; double dY1 = fMaxY / fMax; double dZ1 = fMaxZ / fMax; // Create the shapes (geometry and appearance) for each possible // axis of slicing the geometry. Each slice is generated // for the increasing order for the corresponding OrderedGroup. // The default ordering of the OrderedGroup (specified by setting // setChildIndexOrder(null)) must be used in order to insert into // the begining of the order for the decreasing OrderedGroup. // Fill in the childIndexOrder array for each axis/direction // combination. float offset = -fMaxX / fMax; float range = 2.0f * -offset; float incSliceAmt = range / iDimX; offset = offset + (incSliceAmt / 2.0f); for (int iSliceX = 0; iSliceX < iDimX; ++iSliceX) { QuadArray kGeometry = new QuadArray(4, QuadArray.COORDINATES | QuadArray.TEXTURE_COORDINATE_3); kGeometry.setCoordinate(0, new Point3d(offset, dY0, dZ0)); kGeometry.setCoordinate(1, new Point3d(offset, dY1, dZ0)); kGeometry.setCoordinate(2, new Point3d(offset, dY1, dZ1)); kGeometry.setCoordinate(3, new Point3d(offset, dY0, dZ1)); offset = offset + incSliceAmt; // Create the shape (geometry+appearance) for this slice. // Allow the appearance to be read. Shape3D kShape = new Shape3D(kGeometry, m_kAppearance); kShape.setCapability(Shape3D.ALLOW_APPEARANCE_READ); kShape.setCapability(Shape3D.ALLOW_APPEARANCE_WRITE); kShape.setCapability(Shape3D.ALLOW_GEOMETRY_WRITE); m_akOrderedGroupNodeSlices[AXIS_X].addChild(kShape); // Assign the slice index for increasing/decreasing order // which is used to achieve back-to-front ordering. m_aaaiOrderedGroupChildIndexOrder[AXIS_X][AXIS_INC][iSliceX] = iSliceX; m_aaaiOrderedGroupChildIndexOrder[AXIS_X][AXIS_DEC][iSliceX] = iDimX - 1 - iSliceX; } offset = -fMaxY / fMax; range = 2.0f * -offset; incSliceAmt = range / iDimY; offset = offset + (incSliceAmt / 2.0f); for (int iSliceY = 0; iSliceY < iDimY; ++iSliceY) { // Setup the geometry of the rectangular slice. QuadArray kGeometry = new QuadArray(4, QuadArray.COORDINATES | QuadArray.TEXTURE_COORDINATE_3); kGeometry.setCoordinate(0, new Point3d(dX0, offset, dZ0)); kGeometry.setCoordinate(1, new Point3d(dX0, offset, dZ1)); kGeometry.setCoordinate(2, new Point3d(dX1, offset, dZ1)); kGeometry.setCoordinate(3, new Point3d(dX1, offset, dZ0)); offset = offset + incSliceAmt; // Create the shape (geometry+appearance) for this slice. // Allow the appearance to be read. Shape3D kShape = new Shape3D(kGeometry, m_kAppearance); kShape.setCapability(Shape3D.ALLOW_APPEARANCE_READ); kShape.setCapability(Shape3D.ALLOW_APPEARANCE_WRITE); m_akOrderedGroupNodeSlices[AXIS_Y].addChild(kShape); // Assign the slice index for increasing/decreasing order // which is used to achieve back-to-front ordering. m_aaaiOrderedGroupChildIndexOrder[AXIS_Y][AXIS_INC][iSliceY] = iSliceY; m_aaaiOrderedGroupChildIndexOrder[AXIS_Y][AXIS_DEC][iSliceY] = iDimY - 1 - iSliceY; } offset = -fMaxZ / fMax; range = 2.0f * -offset; incSliceAmt = range / iDimZ; offset = offset + (incSliceAmt / 2.0f); for (int iSliceZ = 0; iSliceZ < iDimZ; ++iSliceZ) { QuadArray kGeometry = new QuadArray(4, QuadArray.COORDINATES | QuadArray.TEXTURE_COORDINATE_3); kGeometry.setCoordinate(0, new Point3d(dX0, dY0, offset)); kGeometry.setCoordinate(1, new Point3d(dX1, dY0, offset)); kGeometry.setCoordinate(2, new Point3d(dX1, dY1, offset)); kGeometry.setCoordinate(3, new Point3d(dX0, dY1, offset)); offset = offset + incSliceAmt; // Create the shape (geometry+appearance) for this slice. // Allow the appearance to be read. Shape3D kShape = new Shape3D(kGeometry, m_kAppearance); kShape.setCapability(Shape3D.ALLOW_APPEARANCE_READ); kShape.setCapability(Shape3D.ALLOW_APPEARANCE_WRITE); m_akOrderedGroupNodeSlices[AXIS_Z].addChild(kShape); // Assign the slice index for increasing/decreasing order // which is used to achieve back-to-front ordering. m_aaaiOrderedGroupChildIndexOrder[AXIS_Z][AXIS_INC][iSliceZ] = iSliceZ; m_aaaiOrderedGroupChildIndexOrder[AXIS_Z][AXIS_DEC][iSliceZ] = iDimZ - 1 - iSliceZ; } } /** * Select along which axis and in which direction slicing in the volume is to be performed. THIS METHOD SHOULD BE * MADE PRIVATE IN THE FINAL RELEASE. * * @param iAxis one of AXIS_X, AXIS_Y, or AXIS_Z which selects the axis of slicing * @param bIncreasingOrder true to select order of slices by increasing coordinate; false to select decreasing * * @throws java.lang.IllegalArgumentException DOCUMENT ME! */ private void selectSlices(int iAxis, boolean bIncreasingOrder) { // Select the axis of slices, but only change if the axis is // different. boolean bChangedAxis = false; switch (iAxis) { case AXIS_X: case AXIS_Y: case AXIS_Z: if (iAxis != m_iAxisSlice) { m_kSwitch.setWhichChild(iAxis); m_iAxisSlice = iAxis; bChangedAxis = true; } break; default: throw new java.lang.IllegalArgumentException("iAxis"); } m_bIncreasingOrder = bIncreasingOrder; // Select the ordering of the slices along that axis. // Only update if the direction along the same axis changed // or if the axis itself changed. int iAxisDir = AXIS_DEC; if (bIncreasingOrder) { iAxisDir = AXIS_INC; } // This needs to be done each time. // if (bChangedAxis || (iAxisDir != m_iAxisDirection)) { try { m_akOrderedGroupNodeSlices[iAxis].setChildIndexOrder(m_aaaiOrderedGroupChildIndexOrder[iAxis][iAxisDir]); m_iAxisDirection = iAxisDir; } catch (IllegalArgumentException e) { } // } } }
package com.example.hyunyoungpark.action; import android.app.DialogFragment; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; /** * Created by hyunyoungpark on 2017-07-27. */ public class DataTimePicker extends AppCompatActivity implements AdapterView.OnItemSelectedListener { Spinner spinner, spinner1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_timepicker); Spinner spinner = (Spinner) findViewById(R.id.sp_planets); spinner.setOnItemSelectedListener(this); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(DataTimePicker.this,R.array.planets_array, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); Button buttonTime = (Button) findViewById(R.id.buttonTime); Button buttonDate = (Button) findViewById(R.id.buttonDate); View.OnClickListener listener = new View.OnClickListener() { @Override public void onClick(View view) { switch (view.getId()) { case R.id.buttonTime: break; case R.id.buttonDate: break; } } }; buttonTime.setOnClickListener(listener); buttonDate.setOnClickListener(listener); } public void showDatePickerDialog(View view) { DialogFragment newFragment = new DatePickerFragment(); newFragment.show(getSupportFragmentManager(), "datePicker"); } @Override public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { } @Override public void onNothingSelected(AdapterView<?> adapterView) { } @Override public void onPointerCaptureChanged(boolean hasCapture) { } }
package com.himanshu.springboot2.foundation.context.setup; import com.himanshu.springboot2.foundation.context.PropertiesPostProcessor; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class TestPropertiesLoaderConfig extends PropertiesPostProcessor { public TestPropertiesLoaderConfig() { super("sample-app"); } @Bean public DummyObject getDummyObject() { return new DummyObject("sample bean String"); } }
package de.digitalstreich.Manufact.model.auth; import lombok.Getter; import lombok.Setter; import org.hibernate.annotations.CreationTimestamp; import org.hibernate.annotations.UpdateTimestamp; import javax.persistence.*; import java.sql.Date; import java.util.Set; @Entity @Table(name = "permissions") @Getter @Setter public class Permission { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Long id; @Column(name = "name") private String name; @ManyToMany(mappedBy = "permissions", fetch = FetchType.EAGER) private Set<Role> roles; @CreationTimestamp @Column(name = "created_at") private Date createdAt; @UpdateTimestamp @Column(name = "updated_at") private Date updatedAt; }
package com.bridgelabz.linkedlist; public class LinedListMain { public static void main(String[] args) { // Welcome message System.out.println("Welcome to linked list program"); LinkedList<Integer> myLinkedList = new LinkedList<Integer>(); // To append elements myLinkedList.append(56); myLinkedList.append(30); myLinkedList.append(40); myLinkedList.append(70); //Linked list before sorting myLinkedList.printLinkedList(); //To sort the list myLinkedList.sortList(); System.out.println(); System.out.println("List after sorting"); myLinkedList.printLinkedList(); } }
package net.lantrack.framework.sysbase.service.imp; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.lantrack.framework.core.entity.BaseEntity; import net.lantrack.framework.core.entity.PageEntity; import net.lantrack.framework.core.lcexception.ServiceException; import net.lantrack.framework.core.service.BaseDao; import net.lantrack.framework.core.service.PageService; import net.lantrack.framework.core.util.DateUtil; import net.lantrack.framework.core.util.IdGen; import net.lantrack.framework.springplugin.PropertyPlaceholder; import net.lantrack.framework.sysbase.dao.SysOfficeTreeMapper; import net.lantrack.framework.sysbase.entity.SysOfficeTree; import net.lantrack.framework.sysbase.entity.SysOfficeTreeExample; import net.lantrack.framework.sysbase.entity.SysUser; import net.lantrack.framework.sysbase.model.office.OfficeModel; import net.lantrack.framework.sysbase.service.SysOfficeTreeService; import net.lantrack.framework.sysbase.util.UserUtil; import net.lantrack.framework.sysbase.util.http.SsoApiUtil; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.google.common.collect.Lists; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; /** * 组织机构树形表 * @date 2019年3月12日 */ @Service("sysOfficeTreeServiceImpl") public class SysOfficeTreeServiceImpl extends BaseTreeService implements SysOfficeTreeService{ @Autowired protected SysOfficeTreeMapper sysOfficeTreeMapper; @Autowired protected PageService pageService; @Autowired protected BaseDao baseDao; /** * 添加组织机构 * @param entity SysOffice类型 * @return entity SysOffice类型,含已生成的主键id */ @Override public SysOfficeTree save(SysOfficeTree entity) throws ServiceException { try { boolean repeat = validateRepeat("", entity.getpId(), entity.gettName()); if(repeat) { throw new ServiceException("当前名称已存在"); } //新添加的默认在后边追加 if(entity.getoSort()==null) { entity.setoSort(getMaxSortByPid(entity.getpId())); } SysOfficeTree parent = queryById(entity.getpId()); if(parent!=null) { entity.setpName(parent.gettName()); //拼接pids和fullname String fullName = parent.gettName(); if(StringUtils.isNotBlank(parent.getFullName())) { fullName = parent.getFullName() + "," + entity.gettName(); } String parentIds = parent.getId(); if(StringUtils.isNotBlank(parent.getpIds())) { parentIds = parent.getpIds() + "," + parent.getId(); } entity.setFullName(fullName); entity.setpIds(parentIds); } entity.setId(IdGen.uuid()); this.sysOfficeTreeMapper.insertSelective(entity); return entity; } catch (Exception e) { throw printException(e); } } /** * 修改组织机构 * @param entity SysOffice类型 * @return entity SysOffice类型 */ @Override public SysOfficeTree update(SysOfficeTree entity) throws ServiceException { try { boolean repeat = validateRepeat(entity.getId(), entity.getpId(), entity.gettName()); if(repeat) { throw new ServiceException("当前名称已存在"); } SysOfficeTree parent = queryById(entity.getpId()); if(parent!=null) { entity.setpName(parent.gettName()); //拼接pids和fullname String fullName = parent.gettName(); if(StringUtils.isNotBlank(parent.getFullName())) { fullName = parent.getFullName() + "_" + entity.gettName(); } String parentIds = parent.getId(); if(StringUtils.isNotBlank(parent.getpIds())) { parentIds = parent.getpIds() + "," + parent.getId(); } entity.setFullName(fullName); entity.setpIds(parentIds); } entity.setCreateBy(null); entity.setCreateDate(null); this.sysOfficeTreeMapper.updateByPrimaryKeySelective(entity); return entity; } catch (Exception e) { throw printException(e); } } /** * 根据id获取指定组织机构 * @param id String类型 * @return 组织机构记录 SysOffice类型 */ @Override public SysOfficeTree queryById(Object id) { if (id == null || StringUtils.isBlank(id.toString())) { throw new ServiceException("id can not be null or empty!"); } return this.sysOfficeTreeMapper.selectByPrimaryKey(id.toString()); } /** * 根据id删除指定组织机构 * @param id * @param update_by 删除者 ( 逻辑删除用) * @param ifLogic 是否启用逻辑删除 true逻辑,false物理 */ @Override public void deleteById(Object id, String update_by, boolean ifLogic) throws ServiceException { if (id == null || StringUtils.isBlank(id.toString())) { throw new ServiceException("id can not be null or empty!"); } if (ifLogic) { // 逻辑删除 SysOfficeTree entity = new SysOfficeTree(); entity.setCreateDate(null); entity.setUpdateBy(update_by); entity.setDelFlag(BaseEntity.YES); entity.setId(id.toString()); this.sysOfficeTreeMapper.updateByPrimaryKeySelective(entity); } else { // 物理删除 this.sysOfficeTreeMapper.deleteByPrimaryKey(id.toString()); } } @Override public void deleteByIds(String ids, String update_by, boolean ifLogic) throws ServiceException { if (StringUtils.isBlank(ids)) { throw new ServiceException("id can not be null or empty!"); } String[] split = ids.split(","); // 添加条件 SysOfficeTreeExample example = new SysOfficeTreeExample(); SysOfficeTreeExample.Criteria cr = example.createCriteria(); List<String> idList = new ArrayList<String>(); if (split.length > 0) { for(int i=0; i<split.length; i++) { idList.add(split[i]); } } cr.andIdIn(idList); if (!ifLogic) { // 物理删除 this.sysOfficeTreeMapper.deleteByExample(example); } else { // 此处用逻辑删除 SysOfficeTree entity = new SysOfficeTree(); entity.setCreateDate(null); entity.setUpdateBy(update_by); entity.setDelFlag(BaseEntity.YES); this.sysOfficeTreeMapper.updateByExampleSelective(entity, example); } } @Override public void getPage(SysOfficeTree entity, PageEntity pageentity) { try { this.pageService.getPage(pageentity.getPerPageCount(), pageentity.getCurrentPage()); List<OfficeModel> result = this.sysOfficeTreeMapper.getOfficeListPage(pageentity, entity); pageentity.setContent(result); } catch (Exception e) { throw printException(e); } } @Override public void getPageRe(SysOfficeTree entity, PageEntity pageentity) { } @Override public void deleteByIdsRe(String ids, String update_by) throws ServiceException { } @Override public List<SysOfficeTree> getAll(SysOfficeTree entity) { SysOfficeTreeExample example = new SysOfficeTreeExample(); SysOfficeTreeExample.Criteria cr = example.createCriteria(); cr.andDelFlagEqualTo("0"); try { return this.sysOfficeTreeMapper.selectByExample(example); } catch (Exception e) { this.logger.error("sysOfficeServiceImp getAll has Error:",e); throw new ServiceException("获取全部组织机构时发生异常"); } } /* 获取树结构根据父id * @see net.lantrack.framework.sysbase.service.SysMenuService#getTreeByPid(java.lang.Integer) */ @Override public List<OfficeModel> getTreeByPid(String pid) throws ServiceException { List<SysOfficeTree> list = sysOfficeTreeMapper.queryByPid(pid); if (list != null) { if ("area".equals(pid)) { list.add(sysOfficeTreeMapper.selectByPrimaryKey(pid)); } ArrayList<OfficeModel> tree = Lists.newArrayListWithExpectedSize(list.size()); for(SysOfficeTree office : list){ OfficeModel m = new OfficeModel(); m.setId(office.getId()); m.setParentId(office.getpId()); m.setOfficeName(office.gettName()); tree.add(m); } return tree; } return null; } /** * 获取当前登录用户只自己所能见到的组织机构树 */ @Override public List<OfficeModel> getCurrentOfficeTree() { List<OfficeModel> list = new ArrayList<OfficeModel>(); SysUser cUser = UserUtil.getUser(); String officeId = null; if (cUser!=null&&StringUtils.isNotBlank(officeId = cUser.getOfficeId())) { //当前机构 SysOfficeTree office = this.queryById(officeId); list.add(turnOfficeToModel(office)); //parentIs包含当前机构id的子机构 SysOfficeTreeExample example = new SysOfficeTreeExample(); SysOfficeTreeExample.Criteria cr = example.createCriteria(); cr.andPIdsLike("%"+officeId+"%"); List<SysOfficeTree> sysList = sysOfficeTreeMapper.selectByExample(example); for(SysOfficeTree sysOffice : sysList){ list.add(turnOfficeToModel(sysOffice)); } } return list; } private OfficeModel turnOfficeToModel(SysOfficeTree office) { OfficeModel m = new OfficeModel(); m.setId(office.getId()); m.setParentId(office.getpId()); m.setOfficeName(office.gettName()); m.setSort(office.getoSort()); return m; } @Override public String extractOfficeFromSso(String sn) throws Exception { String responseStr = "", rmg = ""; try { responseStr = SsoApiUtil.getInstance().getBasicDataList(PropertyPlaceholder.getProperty("sso.service")+PropertyPlaceholder.getProperty("sso.extractOfficeUrl")+"?sn="+sn); JsonParser parser = new JsonParser(); JsonObject jo = (JsonObject) parser.parse(responseStr); JsonArray jsonArray = jo.get("result").getAsJsonArray(); List<SysOfficeTree> list = new ArrayList<SysOfficeTree>(); for (int i=0; i<jsonArray.size(); i++) { JsonElement element = jsonArray.get(i); JsonObject jobt = (JsonObject) parser.parse(element.toString()); SysOfficeTree sysOffice = new SysOfficeTree(); sysOffice.setId(jobt.get("id").toString().substring(1, jobt.get("id").toString().length()-1));//id sysOffice.setpName("null".equals(jobt.get("parent_name").toString()) ? null : jobt.get("parent_name").toString().substring(1, jobt.get("parent_name").toString().length()-1));//parent_name sysOffice.setpId(jobt.get("parent_id").toString().substring(1, jobt.get("parent_id").toString().length()-1));//parent_id sysOffice.setpIds(jobt.get("parent_ids").toString().substring(1, jobt.get("parent_ids").toString().length()-1));//parent_ids sysOffice.settName(jobt.get("name").toString().substring(1, jobt.get("name").toString().length()-1));//name sysOffice.setoSort("null".equals(jobt.get("sort").toString()) ? "0" : jobt.get("sort").toString()); sysOffice.setoAddress(jobt.get("address")==null || "null".equals(jobt.get("address").toString()) ? null : jobt.get("address").toString().substring(1, jobt.get("address").toString().length()-1)); sysOffice.setCreateBy(UserUtil.getCurrentUser()); sysOffice.setUpdateBy(UserUtil.getCurrentUser()); sysOffice.setRemarks(jobt.get("remarks")==null || "null".equals(jobt.get("remarks").toString()) ? null : jobt.get("remarks").toString().substring(1, jobt.get("remarks").toString().length()-1)); list.add(sysOffice); } List<SysOfficeTree> localList = this.getAllLocalOfficeList(); if ((localList != null && localList.size() == 0) || localList == null) { // sysOfficeTreeMapper.insertList(list); rmg = "全量同步"+list.size()+"条组织机构数据成功"; System.out.println(DateUtil.getDateTime()+rmg); } else { // 通过循环区分出哪些是需要新增的、哪些是需要修改的、哪些是需要删除的、哪些是原封不动的 Map<String, List<SysOfficeTree>> map = separateCrudOffice(list, localList); List<SysOfficeTree> insertList = map.get("insertList"); List<SysOfficeTree> deleteList = map.get("deleteList"); List<SysOfficeTree> updateList = map.get("updateList"); List<SysOfficeTree> nochangeList = map.get("nochangeList"); if (insertList != null && insertList.size() > 0) { // sysOfficeTreeMapper.insertList(insertList); } if (deleteList != null && deleteList.size() > 0) { for (SysOfficeTree office : deleteList) { sysOfficeTreeMapper.updateByPrimaryKeySelective(office); } } if (updateList != null && updateList.size() > 0) { for (SysOfficeTree office : updateList) { sysOfficeTreeMapper.updateByPrimaryKeySelective(office); } } if (nochangeList != null && nochangeList.size() > 0) { for (SysOfficeTree office : nochangeList) { sysOfficeTreeMapper.updateByPrimaryKeySelective(office); } } if (insertList!=null && deleteList!=null && updateList!=null && nochangeList!=null) { rmg = "组织机构同步结果为:新增"+insertList.size()+"条,更新"+updateList.size()+"条,删除"+deleteList.size()+"条,未变化的为"+nochangeList.size()+"条"; System.out.println(DateUtil.getDateTime()+rmg); } } // 同步成功后延后12个小时再将新增(0)和修改(2)都置为不变(3),再将删除(1)的del_flag置为1 new Thread(new DelayResetOfficeTreeThread(sysOfficeTreeMapper)).start(); } catch (Exception e) { e.printStackTrace(); } return rmg; } /** * 获取本地所有的组织机构集合 * @return list List<SysOffice>类型 */ public List<SysOfficeTree> getAllLocalOfficeList() { SysOfficeTreeExample example = new SysOfficeTreeExample(); return this.sysOfficeTreeMapper.selectByExample(example); } /** * 区分出哪些是需要新增的、哪些是需要修改的、哪些是需要删除的、哪些是原封不动的行政区域 * @param source 从单点登录系统抽取的全部SysOffice集合 * @param target 本地系统目前数据里的全部SysOffice集合 * @return */ public Map<String, List<SysOfficeTree>> separateCrudOffice(List<SysOfficeTree> source, List<SysOfficeTree> target) { Map<String, List<SysOfficeTree>> map = new HashMap<String, List<SysOfficeTree>>(); List<SysOfficeTree> insertList = new ArrayList<SysOfficeTree>();//新增的list List<SysOfficeTree> deleteList = new ArrayList<SysOfficeTree>();//删除的list List<SysOfficeTree> updateList = new ArrayList<SysOfficeTree>();//修改的list List<SysOfficeTree> nochangeList = new ArrayList<SysOfficeTree>();//没变的list List<SysOfficeTree> updateAndNochangeList = new ArrayList<SysOfficeTree>();//交集中源头的list List<SysOfficeTree> updateAndNcTargetList = new ArrayList<SysOfficeTree>();//交集中目的端list if (source == null || target == null) { return map; } // 分离出两个list的交集,即两边都有的sourceList for (int i = 0; i < source.size(); i++) { SysOfficeTree sourceOffice = source.get(i); for (int j = 0; j < target.size(); j++) { SysOfficeTree targetOffice = target.get(j); if (targetOffice.getId().equals(sourceOffice.getId())) { updateAndNochangeList.add(sourceOffice); updateAndNcTargetList.add(targetOffice); } } } // 再分离出需要新增的list for (int i = 0; i < source.size(); i++) { SysOfficeTree sourceOffice = source.get(i); String sourceId = sourceOffice.getId(); boolean isInsert = true; for (int j = 0; j < updateAndNochangeList.size(); j++) { SysOfficeTree tempOffice = updateAndNochangeList.get(j); if (sourceId.equals(tempOffice.getId())) { isInsert = false; break; } } if (isInsert) { // 同步标记 0新增 // sourceOffice.setSyncFlag("0"); sourceOffice.setStand1("0"); insertList.add(sourceOffice); } } map.put("insertList", insertList); // 再分离出需要删除的list for (int i = 0; i < target.size(); i++) { SysOfficeTree targetOffice = target.get(i); String sourceId = targetOffice.getId(); boolean isDelete = true; for (int j = 0; j < updateAndNochangeList.size(); j++) { SysOfficeTree tempOffice = updateAndNochangeList.get(j); if (sourceId.equals(tempOffice.getId())) { isDelete = false; } } if (isDelete && !"1".equals(targetOffice.getStand1())) { // 同步标记 1删除 // targetOffice.setSyncFlag("1"); targetOffice.setStand1("1"); deleteList.add(targetOffice); } } map.put("deleteList", deleteList); // 最后分离出需要修改的list和没有任何变化的list,都可以是需要修改的list for (int i = 0; i < updateAndNochangeList.size(); i++) { SysOfficeTree sourceOffice = updateAndNochangeList.get(i); boolean isChanged = true; for (int j = 0; j < updateAndNcTargetList.size(); j++) { SysOfficeTree targetOffice = updateAndNcTargetList.get(j); if ((sourceOffice.getId()!=null && sourceOffice.getId().equals(targetOffice.getId())) && (sourceOffice.getpId()!=null && sourceOffice.getpId().equals(targetOffice.getpId())) && (sourceOffice.getpId()!=null && sourceOffice.getpId().equals(targetOffice.getpId())) && ((sourceOffice.gettName()!=null && sourceOffice.gettName().equals(targetOffice.gettName())) || (sourceOffice.gettName()==null && targetOffice.gettName()==null)) ) { // 同步标记 3不变 // sourceOffice.setSyncFlag("3"); sourceOffice.setStand1("3"); nochangeList.add(sourceOffice); isChanged = false; } } if (isChanged) { // 同步标记 2修改 // sourceOffice.setSyncFlag("2"); sourceOffice.setStand1("2"); updateList.add(sourceOffice); } } map.put("updateList", updateList); map.put("nochangeList", nochangeList); return map; } /** * 根据传入的officeId获取其子孙后代所有的officeIds(含自己) * @param officeId 当前传入的机构id * @return officeIds 以逗号拼接的所有下属机构ids */ @Override public String getAllSubOfficeids(String officeId, boolean hasSingleQuote) { StringBuffer ids = new StringBuffer(""); // 先把自己的id拼进去 if (!ids.toString().contains(officeId)) { if (hasSingleQuote) { ids.append("'").append(officeId).append("'"); } else { ids.append(officeId); } } List<OfficeModel> list = this.sysOfficeTreeMapper.queryChildrenByPid(officeId); if (list != null && list.size() > 0) { for (OfficeModel office : list) { if (office != null && StringUtils.isNotBlank(office.getId()) && !ids.toString().contains(office.getId())) { if (hasSingleQuote) { ids.append(",").append("'").append(office.getId()).append("'"); } else { ids.append(",").append(office.getId()); } } } } return ids.toString(); } public boolean validateRepeat(String id,String pid, String nodeName) { SysOfficeTreeExample example = new SysOfficeTreeExample(); SysOfficeTreeExample.Criteria cr = example.createCriteria(); cr.andPIdEqualTo(pid); cr.andTNameEqualTo(nodeName); List<SysOfficeTree> list = this.sysOfficeTreeMapper.selectByExample(example); if(list!=null&&list.size()>0) { SysOfficeTree office = list.get(0); if(!office.getId().equals(id)) { return true; } } return false; } //查看当前部门下最大排序号 private String getMaxSortByPid(String pid) { String sortl = "0"; String sql = "select max(o_sort) as o_sort from sys_office_tree where p_id = '"+pid+"'"; Map<String, Object> sortMap = this.baseDao.querySingleMap(sql); Object o_sort = sortMap.get("o_sort"); if(o_sort!=null&&StringUtils.isNotBlank(o_sort.toString())) { sortl = (Long.valueOf(o_sort.toString())+1)+""; } return sortl; } @Override public String getTableName() { return " sys_office_tree "; } } //延迟一段时间后再重置同步标识位为不变 class DelayResetOfficeTreeThread implements Runnable { private SysOfficeTreeMapper sysOfficeTreeMapper; public DelayResetOfficeTreeThread(SysOfficeTreeMapper sysOfficeTreeMapper) { this.sysOfficeTreeMapper = sysOfficeTreeMapper; } @Override public void run() { try { /** * 12小时=1000*60*60*12毫秒 * 1分钟=1000*60毫秒 * 延迟重置同步标识位 */ Thread.sleep(1000*30); resetNoChangeFlag(); resetDelFlag(); System.out.println("延后30s同步标记重置完成"); } catch (InterruptedException e) { e.printStackTrace(); } } /** * 同步成功后延迟将新增(0)和修改(2)都置为不变(3) */ private void resetNoChangeFlag() { SysOfficeTree record = new SysOfficeTree(); record.setStand1("3"); SysOfficeTreeExample example = new SysOfficeTreeExample(); SysOfficeTreeExample.Criteria cr = example.createCriteria(); List<String> values = new ArrayList<String>(); values.add("0"); values.add("2"); cr.andStand1In(values); sysOfficeTreeMapper.updateByExampleSelective(record, example); } /** * 同步成功后延迟将删除(1)的del_flag置为1,即逻辑删除 */ private void resetDelFlag() { SysOfficeTree record = new SysOfficeTree(); SysOfficeTreeExample example = new SysOfficeTreeExample(); SysOfficeTreeExample.Criteria cr = example.createCriteria(); record.setStand1("1"); record.setDelFlag("1"); cr.andStand1EqualTo("1"); sysOfficeTreeMapper.updateByExampleSelective(record, example); } }
/* * Copyright (C) 2015 Adrien Guille <adrien.guille@univ-lyon2.fr> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package main.java.fr.ericlab.sondy.algo.eventdetection.edcow; import org.apache.commons.math3.stat.descriptive.rank.Median; //////////////////////////////////////////////////////////////////////////////// // This file is part of SONDY. // // // // SONDY is free software: you can redistribute it and/or modify // // it under the terms of the GNU General Public License as published by // // the Free Software Foundation, either version 3 of the License, or // // (at your option) any later version. // // // // SONDY 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 SONDY. If not, see <http://www.gnu.org/licenses/>. // //////////////////////////////////////////////////////////////////////////////// /** * @author yue HE, Falitokiniaina RABEARISON, Département Informatique et Statistiques, Université Lumière Lyon 2 * @author Adrien GUILLE, Laboratoire ERIC, Université Lumière Lyon 2 */ public class EDCoWThreshold { public double mad(double [] autoCorrelationValues){ double [] tempTable = new double[autoCorrelationValues.length]; Median m = new Median(); double medianValue = m.evaluate(autoCorrelationValues); for(int i=0 ; i<autoCorrelationValues.length ;i++){ tempTable[i] = Math.abs(autoCorrelationValues[i] - medianValue); } return m.evaluate(tempTable); //return the median of tempTable, the equation (13) in the paper } public double theta1(double [] autoCorrelationValues, double gama){ Median m = new Median(); return (m.evaluate(autoCorrelationValues) + (gama * mad(autoCorrelationValues))); } public double[] transformMatrix(double [][] matrix){ int a = matrix[0].length * matrix.length; double[] vector = new double[a]; int v=0; for(int i=0; i<matrix.length; i++){ for(int j=0; j<matrix[0].length; j++){ vector[v] = matrix[i][j]; v++; } } return vector; } public double theta2(double [][] crossCorrelationValues, double gama){ double[] vecCrossCorrelation = transformMatrix(crossCorrelationValues); Median m = new Median(); return (m.evaluate(vecCrossCorrelation) + (gama * mad(vecCrossCorrelation))); } }
/* * ### Copyright (C) 2008 Michael Fuchs ### * ### All Rights Reserved. ### * * Author: Michael Fuchs * E-Mail: michael.fuchs@unico-group.com * URL: http://www.michael-a-fuchs.de */ package org.dbdoclet.tidbit.action; import java.awt.event.ActionEvent; import org.dbdoclet.tidbit.Tidbit; import org.dbdoclet.tidbit.application.action.AbstractTidbitAction; import org.dbdoclet.tidbit.perspective.Perspective; public class ActionOpenPerspective extends AbstractTidbitAction { private static final long serialVersionUID = 1L; private final Perspective perspective; private final Tidbit application; public ActionOpenPerspective(Tidbit application, Perspective perspective) { super(perspective, perspective.getLocalizedName(), perspective.getIcon()); this.application = application; this.perspective = perspective; } @Override public void action(ActionEvent event) throws Exception { try { if (application != null && perspective != null) { application.openPerspective(perspective); } } finally { finished(); } } }
package com.restapi.model; import org.bson.types.ObjectId; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; import java.util.ArrayList; import java.util.List; @Document(collection = "myGoals") public class MyGoals { private List<String> goals; private String autor; @Id private ObjectId id; public MyGoals(List<String> goals, String autor) { this.goals = new ArrayList<String>(); this.goals = goals; this.autor = autor; } public List<String> getGoals() { return goals; } public void setGoals(List<String> goals) { this.goals = goals; } public String getAutor() { return autor; } public void setAutor(String autor) { this.autor = autor; } public ObjectId getId() { return id; } public void setId(ObjectId id) { this.id = id; } }
package swiss.kamyh.elo.tools; import swiss.kamyh.elo.enumerate.GroupItemType; import swiss.kamyh.elo.gui.Item; import swiss.kamyh.elo.gui.ItemArmor; import java.util.ArrayList; /** * Created by Vincent on 06.06.2016. */ public class GroupItem { private final int max; private int number; private GroupItemType type; private ArrayList<ItemArmor> items; public GroupItem(GroupItemType type, int max) { this.type = type; this.max = max; this.number = 0; this.items = new ArrayList<>(); } public void incr() { this.number++; } public void decr() { this.number--; } public int getMax() { return max; } public int getNumber() { return number; } public GroupItemType getType() { return type; } public void addItem(ItemArmor item) { this.items.add(item); } public boolean canRemove() { return this.number > 0; } public boolean canAdd() { return this.number < this.max; } @Override public String toString() { switch (this.getType()) { case SOWRD: return "Sword"; case AXE: return "Axe"; case HELMET: return "Helmet"; case CHESTPLAT: return "Chestplat"; case LEGIN: return "Legin"; case BOOTS: return "Boots"; case COMPOS: return "Consomable"; case VARIOUS: return "Divers"; case BLOCK: return "Block"; case POTIONS: return "Potions"; } return null; } public ArrayList<ItemArmor> getItems() { return items; } }
package meli.tmr.solarsystem.models; import meli.tmr.solarsystem.exceptions.SolarSystemException; import java.util.ArrayList; import java.util.List; public class SolarSystem { private List<Planet> planets; public SolarSystem(){ setPlanets(new ArrayList<>()); } public SolarSystem(List<Planet> planets) throws SolarSystemException { if(planets == null || planets.size() != 3) throw new SolarSystemException("Se esperan tres planetas"); setPlanets(planets); } public List<Planet> getPlanets() { return planets; } public void setPlanets(List<Planet> planets) { this.planets = planets; } public void addPlanet(Planet planet){ if(getPlanets() != null && getPlanets().size() == 3) throw new SolarSystemException("El sistema solar ya contiene tres planetas"); getPlanets().add(planet); } public void advanceOneDay() { getPlanets().forEach(p -> p.advanceOneDay()); } }
package com.niranjan.hibernate.DAO; import java.util.Set; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import com.niranjan.hibernate.DTO.AddressDTO; import com.niranjan.hibernate.DTO.EmployeeDTO; import com.niranjan.hibernate.util.HibernateUtil; public class EmployeeDAO { SessionFactory factory=HibernateUtil.getFactory(); public void createEmployeeAndAddress(EmployeeDTO employeeDTO,Set<AddressDTO> addresses){ System.out.println("createEmployeeAndAddress method started..."); Session session=factory.openSession(); Transaction tx=session.beginTransaction(); try{ //session.persist(addresses); //employeeDTO.setAddresses(addresses); session.save(employeeDTO); tx.commit(); }catch(HibernateException e){ e.printStackTrace(); tx.rollback(); }finally{ session.close(); } System.out.println("createEmployeeAndAddress method ended..."); } public void getEmployeeAndAdress(Long id) { System.out.println("getEmployeeAndAdress started..."); Session session=factory.openSession(); try{ AddressDTO dto=session.get(AddressDTO.class, id); System.out.println(dto); System.out.println("employeee------>"); System.out.println(dto.getEmployee()); }catch(HibernateException e){ e.printStackTrace(); }finally{ session.close(); } System.out.println("getEmployeeAndAdress ended..."); } }
/* * 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 DAO; import databases.koneksi; import enkapsulasi.enkapsulasiDaftarTiket; import implement.implementDaftarTiket; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; /** * * @author ASUS */ public class DaftarTiketDAO extends Parent implements implementDaftarTiket { private List<enkapsulasiDaftarTiket> List; @Override public boolean delete(String idtiket) { try { String sql = "delete from loket where id_tiket='" + idtiket + "'"; Connection conn = (Connection) koneksi.koneksiDB(); PreparedStatement stmt = conn.prepareStatement(sql); stmt.execute(); return true; } catch (Exception e) { messageFailed(e.getMessage()); return false; } } @Override public List<enkapsulasiDaftarTiket> search(String idtiket) { List = new ArrayList<enkapsulasiDaftarTiket>(); try { com.mysql.jdbc.Connection conn = (com.mysql.jdbc.Connection) koneksi.koneksiDB(); Statement stmt = conn.createStatement(); ResultSet result = stmt.executeQuery("select penumpang.nik, penumpang.nama, loket.id_tiket, datakereta.kode_kereta, datakereta.jurusan, datakereta.keberangkatan, datakereta.nomor_kursi from penumpang, loket, datakereta where penumpang.nik= loket.nik and loket.kode_kereta=datakereta.kode_kereta;" ); while (result.next()) { enkapsulasiDaftarTiket user = new enkapsulasiDaftarTiket(); user.setIdtiket(result.getString("id_tiket")); user.setNik(result.getString("nik")); user.setNama(result.getString("nama")); user.setKodekereta(result.getString("kode_kereta")); user.setJurusan(result.getString("jurusan")); user.setKeberangkatan(result.getString("keberangkatan")); user.setNomorkursi(result.getString("nomor_kursi")); List.add(user); } return List; } catch (Exception e) { messageFailed(e.getMessage()); return null; } } public List<enkapsulasiDaftarTiket> getAllDaftarTiket(){ List = new ArrayList<enkapsulasiDaftarTiket>(); try { com.mysql.jdbc.Connection conn = (com.mysql.jdbc.Connection) koneksi.koneksiDB(); Statement stmt = conn.createStatement(); ResultSet result = stmt.executeQuery("select penumpang.nik, penumpang.nama, loket.id_tiket, datakereta.kode_kereta, datakereta.jurusan, datakereta.keberangkatan, datakereta.nomor_kursi from penumpang, loket, datakereta where penumpang.nik= loket.nik and loket.kode_kereta=datakereta.kode_kereta;" ); while (result.next()) { enkapsulasiDaftarTiket user = new enkapsulasiDaftarTiket(); user.setIdtiket(result.getString("id_tiket")); user.setNik(result.getString("nik")); user.setNama(result.getString("nama")); user.setKodekereta(result.getString("kode_kereta")); user.setJurusan(result.getString("jurusan")); user.setKeberangkatan(result.getString("keberangkatan")); user.setNomorkursi(result.getString("nomor_kursi")); List.add(user); } return List; } catch (SQLException e) { messageFailed(e.getMessage()); return null; } } }
package basics; import java.util.Scanner; public class Profile { public static void main(String[] args) { Scanner s = new Scanner(System.in); System.out.print("NAME : "); String m = s.nextLine(); System.out.print("College : "); String n = s.nextLine(); System.out.print("De : "); String o = s.nextLine(); System.out.print("Dep : "); String p = s.nextLine(); System.out.println(m); System.out.println(n); System.out.println(o); System.out.println(p); } }
package com.niit.project.radiom.activity; import com.niit.project.radiom.R; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; public class WinActivity extends Activity { private Button backToMain; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_win); backToMain = (Button) findViewById(R.id.backToMain); backToMain.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub Intent intent = new Intent(); intent.setClass(WinActivity.this, MainActivity.class); WinActivity.this.startActivity(intent); WinActivity.this.finish(); } }); } }
package com.wsy.controller; import com.jfinal.aop.Before; import com.jfinal.aop.Clear; import com.jfinal.core.Controller; import com.jfinal.ext.interceptor.GET; import com.jfinal.ext.interceptor.POST; import com.jfinal.kit.Kv; import com.jfinal.kit.PropKit; import com.jfinal.kit.StrKit; import com.wsy.interceptor.AuthInterceptor; import com.wsy.model.biz.Result; import com.wsy.service.UserService; import com.wsy.util.Constant; import com.wsy.util.ResultFactory; import com.wsy.util.TokenUtil; /** * the controller witch relationship on user * Created by Lenovo on 2017/10/13. */ public class UserController extends Controller{ private UserService userService = new UserService(); /** * 登录 */ @Clear({GET.class, AuthInterceptor.class}) @Before(POST.class) public void login() { Result result = ResultFactory.createResult(Constant.ResultCode.LEAK_PARAM); if (StrKit.notBlank(getPara("userName")) && StrKit.notBlank(getPara("password"))) { result = userService.logIn(getPara("userName"), getPara("password")); } if (result.getCode() == Constant.ResultCode.SUCCESS) { Kv kv = ((Kv) result.getData()); setCookie("token", TokenUtil.generateToken(kv.getInt("id"), kv.getStr("userName")), PropKit.getInt("token.timeout"), true); } else { removeCookie("token"); } renderJson(result); } /** * 获取用户信息(基本信息,资源信息) */ public void getUserInfo() { renderJson(userService.getUserInfo(getSessionAttr("userId"))); } /** * 修改密码 */ @Clear(GET.class) @Before(POST.class) public void modifyPassword() { String oldPass = getPara("oldPass"); String newPass = getPara("newPass"); Integer userId = getSessionAttr("userId"); renderJson(userService.modifyPassword(userId, oldPass, newPass)); } /** * 登出 */ @Clear(GET.class) @Before(POST.class) public void logout() { TokenUtil.delUserToken(getSessionAttr("userId")); removeSessionAttr("userId"); removeCookie("token"); renderJson(ResultFactory.success(null)); } }
package edu.hm.vss.client; import edu.hm.vss.userInterface.IUserInterface; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; /** * implementation of the userinterface. * Adds, remove philosohpers and plates, after that a setup rebuilt is started. */ public class UserInterface extends UnicastRemoteObject implements IUserInterface { private Client client; public UserInterface() throws RemoteException { super(); } public UserInterface(Client client) throws RemoteException { super(); this.client = client; System.out.println("UserInterface constructor"); } @Override public void removePhilosopher(boolean hungry) throws RemoteException { client.stopAll(); if(hungry) { client.setNumberOfHungryPhilosophers(client.getNumberOfHungryPhilosophers() > 0 ? client.getNumberOfHungryPhilosophers()-1 : 0); client.getAllEatCounts().remove(client.getAllEatCounts().size()-1); } else { client.getAllEatCounts().remove(0); int i = 0; Map<Integer, Integer> newEatcounts = new ConcurrentHashMap<>(); for(Map.Entry<Integer, Integer> eCount : client.getAllEatCounts().entrySet()) { newEatcounts.put(eCount.getKey()-1, eCount.getValue()); } client.setAllEatCounts(newEatcounts); } client.setNumberOfPhilosophers(client.getNumberOfPhilosophers() > 0 ? client.getNumberOfPhilosophers()-1 : 0); client.startAgain(); } @Override public void addPhilosopher(boolean hungry) throws RemoteException { client.stopAll(); if(hungry) { client.setNumberOfHungryPhilosophers(client.getNumberOfHungryPhilosophers()+1); } client.setNumberOfPhilosophers(client.getNumberOfPhilosophers()+1); client.startAgain(); } @Override public void removePlate() throws RemoteException { client.stopAll(); client.setNumberOfPlaces(client.getNumberOfPlaces() > 2 ? client.getNumberOfPlaces() - 1 : 2); client.startAgain(); } @Override public void addPlate() throws RemoteException { client.stopAll(); client.setNumberOfPlaces(client.getNumberOfPlaces()+1); client.startAgain(); } }
package com.sample.myapplication.network.service.client; import com.sample.myapplication.BuildConfig; import com.sample.myapplication.network.RestCall; import com.sample.myapplication.network.RestRequest; import com.sample.myapplication.network.base.BaseRestClient; import com.sample.myapplication.network.service.api.FlickrImagesApi; import com.sample.myapplication.network.service.event.FlickrImagesResponseEvent; import com.sample.myapplication.network.service.interceptor.NetworkSleepInterceptor; import java.util.concurrent.TimeUnit; import okhttp3.OkHttpClient; import okhttp3.logging.HttpLoggingInterceptor; import retrofit2.Call; import retrofit2.Retrofit; import retrofit2.converter.gson.GsonConverterFactory; public class FlickrImagesRestClient extends BaseRestClient { private static final String BASE_URL = "https://api.flickr.com"; private static final String API_URL = BASE_URL + "/"; private static final int TIMEOUT = 10; private static final int SLEEP_TIMEOUT = 5; private static final boolean USE_SLEEP_INTERCEPTOR = false; private static final FlickrImagesRestClient INSTANCE = new FlickrImagesRestClient(); private Retrofit mRetrofit; private FlickrImagesApi mFlickrImagesApi; private RestCall mFlickrImagesApiRestCall; /** * Singleton instance of {@link FlickrImagesRestClient}. * * @return instance of {@link FlickrImagesRestClient}. */ public static FlickrImagesRestClient getInstance() { return INSTANCE; } /** * Singleton construct. */ private FlickrImagesRestClient() { OkHttpClient.Builder okHttpClientBuilder = new OkHttpClient.Builder(); okHttpClientBuilder.connectTimeout(TIMEOUT, TimeUnit.SECONDS); if (BuildConfig.DEBUG) { HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(); httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BASIC); okHttpClientBuilder .addInterceptor(httpLoggingInterceptor); } //simulate long running request if (USE_SLEEP_INTERCEPTOR) { NetworkSleepInterceptor networkSleepInterceptor = new NetworkSleepInterceptor( SLEEP_TIMEOUT, TimeUnit.SECONDS); okHttpClientBuilder .addInterceptor(networkSleepInterceptor); } mRetrofit = new Retrofit.Builder() .baseUrl(API_URL) .addConverterFactory(GsonConverterFactory.create()) .client(okHttpClientBuilder.build()) .build(); mFlickrImagesApi = mRetrofit.create(FlickrImagesApi.class); } /** * Invoke getWeather via {@link Call} request. * * @param text of Api. * @param per_page of Api. * @param page of Api. */ public void getFlickrImages(String text, int per_page, int page) { Call apiWeatherCall = mFlickrImagesApi.getFlickrImages( text, String.valueOf(per_page), String.valueOf(page)); RestRequest restRequest = new RestRequest.Builder() .call(apiWeatherCall) .baseResponseEvent(new FlickrImagesResponseEvent()) .useStickyIntent(true) .build(); mFlickrImagesApiRestCall = call(restRequest); } /** * Cancel of getWeather {@link Call} request. */ public void cancelFlickrImagesRestCall() { cancelCall(mFlickrImagesApiRestCall); } }
package com.birivarmi.birivarmiapp.dto; public class CategoryStatsDto { private String categoryId; private String numItems; public String getCategoryId() { return categoryId; } public void setCategoryId(String categoryId) { this.categoryId = categoryId; } public String getNumItems() { return numItems; } public void setNumItems(String numItems) { this.numItems = numItems; } }
package android.support.v4.os; import android.support.annotation.RestrictTo; import android.support.annotation.RestrictTo.Scope; import java.util.Locale; @RestrictTo({Scope.LIBRARY_GROUP}) final class LocaleHelper { LocaleHelper() { } static Locale forLanguageTag(String str) { int i = 2; int i2 = 0; int i3 = 1; String[] split; if (str.contains("-")) { split = str.split("-"); if (split.length > i) { return new Locale(split[i2], split[i3], split[i]); } if (split.length > i3) { return new Locale(split[i2], split[i3]); } if (split.length == i3) { return new Locale(split[i2]); } } else if (!str.contains("_")) { return new Locale(str); } else { split = str.split("_"); if (split.length > i) { return new Locale(split[i2], split[i3], split[i]); } if (split.length > i3) { return new Locale(split[i2], split[i3]); } if (split.length == i3) { return new Locale(split[i2]); } } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("Can not parse language tag: ["); stringBuilder.append(str); stringBuilder.append("]"); throw new IllegalArgumentException(stringBuilder.toString()); } static String toLanguageTag(Locale locale) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append(locale.getLanguage()); String country = locale.getCountry(); if (!(country == null || country.isEmpty())) { stringBuilder.append("-"); stringBuilder.append(locale.getCountry()); } return stringBuilder.toString(); } }
import java.applet.Applet; import java.awt.Checkbox; import java.awt.CheckboxGroup; import java.awt.Color; import java.awt.TextField; import java.awt.event.ItemEvent; import java.awt.event.ItemListener; public class EventOnRadioButton1 extends Applet { CheckboxGroup obj=new CheckboxGroup(); Checkbox c1,c2,c3,c4; TextField t1; @Override public void init() { setSize(800,500); c1=new Checkbox("Red",false,obj); c2=new Checkbox("Green",false,obj); c3=new Checkbox("yellow",false,obj); c4=new Checkbox("Cyan",false,obj); t1=new TextField(10); add(t1);add(c1);add(c2);add(c3);add(c4); c1.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { t1.setText("red"); setBackground(Color.red); } }); c2.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { t1.setText("green"); setBackground(Color.green); } }); c3.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { t1.setText("yellow"); setBackground(Color.yellow); } }); c4.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { t1.setText("cyan"); setBackground(Color.cyan); } }); } }
package com.example.cardapio; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; public class MainActivity extends AppCompatActivity { public static final String TITULO = "com.example.cardapio.TITULO"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void abrirBebidas(View v) { Intent intentProdutos = new Intent(this, ProdutosActivity.class); intentProdutos.putExtra(TITULO,"Bebidas"); startActivity(intentProdutos); } public void abrirHamburguers(View v) { Intent intentProdutos = new Intent(this, ProdutosActivity.class); intentProdutos.putExtra(TITULO,"Hamburguers"); startActivity(intentProdutos); } public void abrirSobremesas(View v) { Intent intentProdutos = new Intent(this, ProdutosActivity.class); intentProdutos.putExtra(TITULO,"Sobremesas"); startActivity(intentProdutos); } public void abrirPasteis(View v) { Intent intentProdutos = new Intent(this, ProdutosActivity.class); intentProdutos.putExtra(TITULO,"Pastéis"); startActivity(intentProdutos); } }
import edu.smu.tspell.wordnet.Synset; import edu.smu.tspell.wordnet.SynsetType; import edu.smu.tspell.wordnet.WordNetDatabase; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.util.*; public class SentimentAnalysis { Map<String,ArrayList<String>> emotionMap=new HashMap<>() ; HashMap<String,Float> emoticonMap = new HashMap<>() ; HashMap<String,Float> phrasePolarityMap = new HashMap<>(); WordNetDatabase database = WordNetDatabase.getFileInstance() ; public void initialize() throws FileNotFoundException, XMLStreamException { readSecondary(); //loads the file of secondary emotions inside emotionMap map findSynonyms(); //finds secondary emotions synonyms using WordNet readEmoticons(); //loads the file of emoticons in emoticonMap map readXML(); //loads the Sentic Net XML file into phrasePolarityMap } public HashMap<String,Float> calculateSentiment(String tweet){ HashMap<String,Integer> primaryCount = new HashMap<>(); //sinaisthima => Plithos Sinaisthimatikwn lexewn gia to sinaisthima HashMap<String,Float> sentimentScore = new HashMap<>(); ArrayList<String> tokens = createAllCombinationsOfConsecutiveStrings(tweet); int countSentimentTokens = 0; //plithos sinaisthimatikwn lexewn tou tweet String primarySentiment = ""; for (String token : tokens){ Float polarity = new Float(0); //initialize the polarity if(emoticonMap.containsKey(token)){ //if its an emoticon primarySentiment = containsSecondary(token); //takes the primary Sentiment updatePrimaryCount(primarySentiment,primaryCount); //updates the count for this primary sentiment polarity = emoticonMap.get(token); //takes the polarity of the emoticon updatePolarity(primarySentiment,polarity,sentimentScore); //updates the polarity of the primary sentiment countSentimentTokens++; } else if(phrasePolarityMap.containsKey(token)){ String stemmedToken = stemWord(token); if((primarySentiment = containsSecondary(stemmedToken))!=null) { //if its contained polarity = phrasePolarityMap.get(token); updatePolarity(primarySentiment,polarity,sentimentScore); updatePrimaryCount(primarySentiment,primaryCount); //updates the count for this primary sentiment countSentimentTokens++; } else if((primarySentiment = containsSecondary(token))!=null) { polarity = phrasePolarityMap.get(token); updatePolarity(primarySentiment,polarity,sentimentScore); updatePrimaryCount(primarySentiment,primaryCount); //updates the count for this primary sentiment countSentimentTokens++; } } } calculateSentimentScore(primaryCount,sentimentScore,countSentimentTokens); //calculates the overall score for each primary sentiment return sentimentScore; } public void calculateSentimentScore(HashMap<String,Integer> primaryCount , HashMap<String,Float> sentimentScore, int countSentimentTokens){ for(String aKey : sentimentScore.keySet()){ sentimentScore.put(aKey, sentimentScore.get(aKey)/ new Float(primaryCount.get(aKey)) ); } for(String aKey : sentimentScore.keySet()){ sentimentScore.put(aKey, sentimentScore.get(aKey)/ new Float(countSentimentTokens) ); } } /** * Method that updates the count of tokens for each primary sentiment * @param primary * @param primaryCount */ public void updatePrimaryCount(String primary,HashMap<String,Integer> primaryCount){ if(primaryCount.containsKey(primary)){ //if its already contained Integer oldCount = new Integer(primaryCount.get(primary)); primaryCount.put(primary,oldCount+1); //we just add it } else{ //if its the first time primaryCount.put(primary,1); //initialize it } } /** * Method that updates the primary sentiment score * @param primary * @param polarity * @param sentimentScore */ public void updatePolarity(String primary,Float polarity,HashMap<String,Float> sentimentScore){ if(sentimentScore.containsKey(primary)){ //if the primary sentiment already exists Float oldPolarity = new Float(sentimentScore.get(primary)); //get the secondary sentimentScore.put(primary, Math.abs(oldPolarity)+Math.abs(polarity) ); //add the new polarity } else { sentimentScore.put(primary,Math.abs(polarity)); } } public void readSecondary() throws FileNotFoundException { Scanner scan = new Scanner(new File("secondary_emotions.txt")); scan.useDelimiter("\n"); while (scan.hasNext()) { String next = scan.next(); ArrayList<String> aList = new ArrayList<>(); for (String emotion : next.split("\t")) { aList.add(emotion); } String key; if (emotionMap.size() == 0) { key = "anger"; } else if (emotionMap.size() == 1) { key = "disgust"; } else if (emotionMap.size() == 2) { key = "fear"; } else if (emotionMap.size() == 3) { key = "joy"; } else if (emotionMap.size() == 4) { key = "sadness"; } else { key = "surprise"; } // System.out.println("Tha valw gia key " + key + " to " + aList); emotionMap.put(key, aList); } } /** * * @param token * @return null if the secondary does not exist or the primary sentiment if it exists */ public String containsSecondary(String token){ for(Map.Entry entry : emotionMap.entrySet()){ ArrayList<String> list = new ArrayList<> ((ArrayList<String>) entry.getValue()); if (list.contains(token)){ return (String) entry.getKey(); } } return null; //if its not included in any primary sentiment , return null } public Boolean containsSecondaryForSpecificSentiment(String token,String sentiment){ ArrayList<String> list = emotionMap.get(sentiment); if (list.contains(token)){ return true; } else{ return false; } } public void findSynonyms(){ System.setProperty("wordnet.database.dir", "/usr/local/WordNet-3.0/dict"); Iterator it=emotionMap.entrySet().iterator() ; while(it.hasNext()) { Map.Entry entry=(Map.Entry)it.next() ; String key=(String)entry.getKey() ; ArrayList<String> Synonyms=new ArrayList<>() ; ArrayList<String> values=emotionMap.get(key); Synonyms.addAll(values); for(String aValue:values) { String wordForm = aValue ; Synset[] synsetAdjectives = database.getSynsets(wordForm,SynsetType.ADJECTIVE); if (synsetAdjectives.length > 0) { for (int i = 0; i < synsetAdjectives.length; i++) { String[] wordForms = synsetAdjectives[i].getWordForms(); for (int j = 0; j < wordForms.length; j++) { if(!Synonyms.contains(wordForms[j])){ Synonyms.add(wordForms[j]); } } } } Synset[] synsetNouns = database.getSynsets(wordForm,SynsetType.NOUN); if (synsetNouns.length > 0) { for (int i = 0; i < synsetNouns.length; i++) { String[] wordForms = synsetNouns[i].getWordForms(); for (int j = 0; j < wordForms.length; j++) { if(!Synonyms.contains(wordForms[j])){ Synonyms.add(wordForms[j]); } } } } Synset[] synsetVerbs = database.getSynsets(wordForm,SynsetType.VERB); if (synsetVerbs.length > 0) { for (int i = 0; i < synsetVerbs.length; i++) { String[] wordForms = synsetVerbs[i].getWordForms(); for (int j = 0; j < wordForms.length; j++) { if(!Synonyms.contains(wordForms[j])){ Synonyms.add(wordForms[j]); } } } } } ArrayList<String> newList = new ArrayList<>(); for(String word : Synonyms){ String temp = stemWord(word); newList.add(temp); } entry.setValue(newList) ; } } public String stemWord(String word){ PorterStemmer s = new PorterStemmer(); s.add(word.toCharArray(),word.length()); // for(char ch : word.toCharArray()){ // s.add(ch); // } s.stem(); return s.toString(); } public void readEmoticons() throws FileNotFoundException { Scanner scanPolarity = new Scanner(new File("emoticons.txt")); for (int i=0;i<4;i++) scanPolarity.next(); while (scanPolarity.hasNext()) { String primary = scanPolarity.next(); Float posPolarity = Float.parseFloat(scanPolarity.next()); //gets the positive polarity Float negPolarity = Float.parseFloat(scanPolarity.next()); //gets the negative polarity String emoticon = scanPolarity.next(); //gets the emoticon emoticonMap.put(emoticon, posPolarity - negPolarity); ArrayList<String> values =emotionMap.get(primary) ; values.add(emoticon); emotionMap.put(primary, values); } } public void readXML() throws FileNotFoundException, XMLStreamException { XMLInputFactory inputFactory = XMLInputFactory.newInstance(); XMLStreamReader reader = inputFactory.createXMLStreamReader(new FileReader("./senticnet3.rdf.xml")); Float polarity; String phrase = ""; while(reader.hasNext()){ int eventtype = reader.next(); switch (eventtype){ case XMLStreamReader.START_ELEMENT: String elementName = reader.getLocalName(); if (elementName == "text"){ phrase = reader.getElementText(); } else if (elementName == "polarity"){ polarity = Float.parseFloat( reader.getElementText() ); phrasePolarityMap.put(phrase,polarity); } } } } /** * Creates all the possible combinations of consective strings * @param str * @return */ public ArrayList<String> createAllCombinationsOfConsecutiveStrings(String str){ ArrayList<String> allCombinations = new ArrayList<>(); String[] words = str.split(" "); allCombinations.addAll(Arrays.asList(words)); for (int i=0; i < words.length; i++) { String temp = new String(words[i]); for(int j=i+1;j<words.length;j++){ temp = temp.concat(" "+words[j]); allCombinations.add(temp); } } return allCombinations; } public void testingHashMap(Map<String,ArrayList<String>> map){ for(Map.Entry entry : map.entrySet()){ System.out.println("============== KEY => "+entry.getKey()+" =============="); for (String str : (ArrayList<String>)entry.getValue()){ System.out.println(str); } } } public void testingPolarityMap(){ System.out.println(phrasePolarityMap.size()); for(Map.Entry entry : phrasePolarityMap.entrySet()){ String key = (String) entry.getKey(); Float pol = (Float) entry.getValue(); System.out.println(key+" =========> "+pol); } } }
package com.example.acer.slt_lite.adapter; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.util.Base64; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.example.acer.slt_lite.R; import com.example.acer.slt_lite.constant.Constant; import com.example.acer.slt_lite.model.Product; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; public class ProductAdapter extends BaseAdapter { private static final String TAG = "ProductAdapter"; private List<Product> products = new ArrayList<Product>(); private final Context context; public ProductAdapter(Context context) { this.context = context; } public void updateProducts(List<Product> products) { this.products.addAll(products); notifyDataSetChanged(); } @Override public int getCount() { return products.size(); } @Override public Product getItem(int position) { return products.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { TextView tvName; TextView tvPrice; ImageView ivImage; if (convertView == null) { convertView = LayoutInflater.from(context) .inflate(R.layout.adapter_product, parent, false); tvName = (TextView) convertView.findViewById(R.id.tvProductName); tvPrice = (TextView) convertView.findViewById(R.id.tvProductPrice); ivImage = (ImageView) convertView.findViewById(R.id.ivProductImage); convertView.setTag(new ViewHolder(tvName, tvPrice, ivImage)); } else { ViewHolder viewHolder = (ViewHolder) convertView.getTag(); tvName = viewHolder.tvProductName; tvPrice = viewHolder.tvProductPrice; ivImage = viewHolder.ivProductImage; } final Product product = getItem(position); tvName.setText(product.getName()); tvPrice.setText(Constant.CURRENCY+ String.valueOf(product.getPrice().setScale(2, BigDecimal.ROUND_HALF_UP))); Log.d(TAG, "Context package name: " + context.getPackageName()); String s=product.getImageName(); byte decodedString1 [] = Base64.decode(s, Base64.DEFAULT | Base64.NO_WRAP); Bitmap bitmapd = BitmapFactory.decodeByteArray(decodedString1, 0,decodedString1.length); Bitmap b=Bitmap.createScaledBitmap(bitmapd, 300, 300, false); ivImage.setImageBitmap(b); return convertView; } private static class ViewHolder { public final TextView tvProductName; public final TextView tvProductPrice; public final ImageView ivProductImage; public ViewHolder(TextView tvProductName, TextView tvProductPrice, ImageView ivProductImage) { this.tvProductName = tvProductName; this.tvProductPrice = tvProductPrice; this.ivProductImage = ivProductImage; } } }
package io.nuls.base.api.provider.dex.facode; import io.nuls.base.api.provider.BaseReq; import java.math.BigInteger; public class CoinTradingReq extends BaseReq { private String address; private String password; private int quoteAssetChainId; private int quoteAssetId; private int baseAssetChainId; private int baseAssetId; private int scaleQuoteDecimal; private int scaleBaseDecimal; private BigInteger minQuoteAmount; private BigInteger minBaseAmount; public CoinTradingReq() { } public CoinTradingReq(String address, String password, int quoteAssetChainId, int quoteAssetId, int baseAssetChainId, int baseAssetId, int scaleQuoteDecimal, int scaleBaseDecimal, BigInteger minQuoteAmount, BigInteger minBaseAmount) { this.address = address; this.password = password; this.quoteAssetChainId = quoteAssetChainId; this.quoteAssetId = quoteAssetId; this.baseAssetChainId = baseAssetChainId; this.baseAssetId = baseAssetId; this.scaleQuoteDecimal = scaleQuoteDecimal; this.scaleBaseDecimal = scaleBaseDecimal; this.minQuoteAmount = minQuoteAmount; this.minBaseAmount = minBaseAmount; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public int getQuoteAssetChainId() { return quoteAssetChainId; } public void setQuoteAssetChainId(int quoteAssetChainId) { this.quoteAssetChainId = quoteAssetChainId; } public int getQuoteAssetId() { return quoteAssetId; } public void setQuoteAssetId(int quoteAssetId) { this.quoteAssetId = quoteAssetId; } public int getBaseAssetChainId() { return baseAssetChainId; } public void setBaseAssetChainId(int baseAssetChainId) { this.baseAssetChainId = baseAssetChainId; } public int getBaseAssetId() { return baseAssetId; } public void setBaseAssetId(int baseAssetId) { this.baseAssetId = baseAssetId; } public int getScaleQuoteDecimal() { return scaleQuoteDecimal; } public void setScaleQuoteDecimal(int scaleQuoteDecimal) { this.scaleQuoteDecimal = scaleQuoteDecimal; } public int getScaleBaseDecimal() { return scaleBaseDecimal; } public void setScaleBaseDecimal(int scaleBaseDecimal) { this.scaleBaseDecimal = scaleBaseDecimal; } public BigInteger getMinQuoteAmount() { return minQuoteAmount; } public void setMinQuoteAmount(BigInteger minQuoteAmount) { this.minQuoteAmount = minQuoteAmount; } public BigInteger getMinBaseAmount() { return minBaseAmount; } public void setMinBaseAmount(BigInteger minBaseAmount) { this.minBaseAmount = minBaseAmount; } }
package com.legend.rmi.quickstart.server; import com.legend.rmi.quickstart.common.Constants; import com.legend.rmi.quickstart.common.ZooKeeperUtils; import org.apache.zookeeper.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InterruptedIOException; import java.net.MalformedURLException; import java.rmi.Naming; import java.rmi.Remote; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.util.concurrent.CountDownLatch; /** * Created by allen on 6/28/16. */ public class ServiceProvider { private static final Logger LOG = LoggerFactory.getLogger(ServiceProvider.class); // 用于等待SyncConnected事件触发后,继续执行当前线程 private CountDownLatch latch = new CountDownLatch(1); /** * 发布RMI服务,并将将RMI地址注册到ZooKeeper中 * @param remote * @param host * @param port */ public void publish(Remote remote, String host, int port) { String url = this.publishService(remote, host, port); // 发布RMI服务,并返回RMI地址 this.registService(url); // 将RMI地址注册到ZooKeeper中 } /** * 发布RMI服务 * @param remote * @param host * @param port * @return */ private String publishService(Remote remote, String host, int port) { String url = null; try { url = String.format("rmi://%s:%d/%s", host, port, remote.getClass().getName()); LocateRegistry.createRegistry(port); Naming.rebind(url, remote); LOG.info("Publish rmi service (url: {})", url); } catch (MalformedURLException ex) { LOG.error("Publish service with error", ex); } catch (RemoteException ex) { LOG.error("Publish service with error", ex); } return url; } /** * 注册RMI地址到ZooKeeper中 * @param url */ private void registService(String url) { if (url == null) { return; } // Connect ZooKeeper zk = ZooKeeperUtils.connectZooKeeper(this.latch); // 连接ZooKeeper服务器,并返回ZooKeeper对象 // Regist internal this.registServiceInternal(zk, url); // 创建ZNode并将RMI地址放入ZNode上 } /** * 将RMI地址注册到ZooKeeper上 * @param zk * @param url */ private void registServiceInternal(ZooKeeper zk, String url) { if (zk == null || url == null || url.trim().length() == 0) { return; } try { byte[] data = url.getBytes(); String path = zk.create(Constants.ZK_PROVIDER_PATH, data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL_SEQUENTIAL); // 创建一个临时且有序的ZNode节点 } catch (KeeperException ex) { LOG.error("Regist with error: ", ex); } catch (InterruptedException ex) { LOG.error("Regist with error: ", ex); } } }
/* * ################################################################ * * ProActive Parallel Suite(TM): The Java(TM) library for * Parallel, Distributed, Multi-Core Computing for * Enterprise Grids & Clouds * * Copyright (C) 1997-2010 INRIA/University of * Nice-Sophia Antipolis/ActiveEon * Contact: proactive@ow2.org or contact@activeeon.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; version 3 of * the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * If needed, contact us to obtain a release under GPL Version 2 * or a different license than the GPL. * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * ################################################################ * $$PROACTIVE_INITIAL_DEV$$ */ package org.ow2.proactive.scheduler.ext.scilab.worker; import org.objectweb.proactive.api.PAActiveObject; import org.objectweb.proactive.core.util.wrapper.BooleanWrapper; import org.objectweb.proactive.utils.OperatingSystem; import org.ow2.proactive.scheduler.common.task.TaskResult; import org.ow2.proactive.scheduler.ext.matsci.common.exception.InvalidNumberOfParametersException; import org.ow2.proactive.scheduler.ext.matsci.common.exception.InvalidParameterException; import org.ow2.proactive.scheduler.ext.matsci.worker.MatSciWorker; import org.ow2.proactive.scheduler.ext.matsci.worker.util.MatSciEngineConfigBase; import org.ow2.proactive.scheduler.ext.scilab.common.PASolveScilabGlobalConfig; import org.ow2.proactive.scheduler.ext.scilab.common.PASolveScilabTaskConfig; import org.ow2.proactive.scheduler.ext.scilab.common.exception.ScilabInitializationException; import org.ow2.proactive.scheduler.ext.scilab.common.exception.ScilabInitializationHanged; import org.ow2.proactive.scheduler.ext.scilab.common.exception.ScilabTaskException; import org.ow2.proactive.scheduler.ext.scilab.worker.util.ScilabEngineConfig; import org.scilab.modules.javasci.Scilab; import org.scilab.modules.types.ScilabBoolean; import org.scilab.modules.types.ScilabType; import java.io.*; import java.net.URI; import java.net.UnknownHostException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; /** * An active object which handles the interaction between the ScilabTask and a local Scilab engine * * @author The ProActive Team */ public class AOScilabWorker implements Serializable, MatSciWorker { /** */ private static final long serialVersionUID = 31L; /** The ISO8601 for debug format of the date that precedes the log message */ private static final SimpleDateFormat ISO8601FORMAT = new SimpleDateFormat("yyyy-MM-dd HH:mm:sss"); private static String HOSTNAME; private static OperatingSystem os; private static char fs; static { try { HOSTNAME = java.net.InetAddress.getLocalHost().getHostName(); os = OperatingSystem.getOperatingSystem(); fs = os.fileSeparator(); } catch (UnknownHostException e) { } } static String nl = System.getProperty("line.separator"); /** * script executed to initialize the task (input parameter) */ private String inputScript = null; /** * Main script to be executed */ private ArrayList<String> mainscriptLines = new ArrayList<String>(); /** * Configuration of Scilab (paths) */ private ScilabEngineConfig engineConfig; /** * The scilab engine */ private org.scilab.modules.javasci.Scilab engine = null; private boolean initialized = false; private boolean initErrorOccured = false; private Throwable initError = null; /** * Definition of user-functions */ private String functionName = null; /** * Name of this ProActive Node */ private String nodeName = null; /** * System tmp dir */ static File tmpDir = new File(System.getProperty("java.io.tmpdir")); /** * */ private File tmpDirNode = null; /** For debug purpose */ private PrintWriter outDebugWriter; File localSpace; File tempSubDir; private PASolveScilabGlobalConfig paconfig = null; private PASolveScilabTaskConfig taskconfig; public AOScilabWorker() { } /** * Constructor for the Simple task * * @param scilabConfig the configuration for scilab */ public AOScilabWorker(ScilabEngineConfig scilabConfig) throws Exception { this.engineConfig = scilabConfig; } private void initializeEngine() throws Exception { if (!initialized) { try { if (paconfig.isDebug()) { System.out.println("Scilab Initialization..."); System.out.println("PATH=" + System.getenv("PATH")); System.out.println("LD_LIBRARY_PATH=" + System.getenv("LD_LIBRARY_PATH")); System.out.println("java.library.path=" + System.getProperty("java.library.path")); } System.out.println("Starting a new Scilab engine:"); System.out.println(engineConfig); scilabStarter(); if (paconfig.isDebug()) { System.out.println("Initialization Complete!"); } } catch (UnsatisfiedLinkError e) { StringWriter error_message = new StringWriter(); PrintWriter pw = new PrintWriter(error_message); pw.println("Can't find the Scilab libraries in host " + java.net.InetAddress.getLocalHost()); pw.println("PATH=" + System.getenv("PATH")); pw.println("LD_LIBRARY_PATH=" + System.getenv("LD_LIBRARY_PATH")); pw.println("java.library.path=" + System.getProperty("java.library.path")); ScilabInitializationException ne = new ScilabInitializationException(error_message.toString()); ne.initCause(e); throw ne; } catch (NoClassDefFoundError e) { StringWriter error_message = new StringWriter(); PrintWriter pw = new PrintWriter(error_message); pw.println("Classpath Error in " + java.net.InetAddress.getLocalHost()); pw.println("java.class.path=" + System.getProperty("java.class.path")); ScilabInitializationException ne = new ScilabInitializationException(error_message.toString()); ne.initCause(e); throw ne; } catch (ScilabInitializationException e) { throw e; } catch (Throwable e) { StringWriter error_message = new StringWriter(); PrintWriter pw = new PrintWriter(error_message); pw.println("Error initializing Scilab in " + java.net.InetAddress.getLocalHost()); pw.println("PATH=" + System.getenv("PATH")); pw.println("LD_LIBRARY_PATH=" + System.getenv("LD_LIBRARY_PATH")); pw.println("java.library.path=" + System.getProperty("java.library.path")); pw.println("java.class.path=" + System.getProperty("java.class.path")); IllegalStateException ne = new IllegalStateException(error_message.toString()); ne.initCause(e); throw ne; } Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() { public void run() { engine.close(); } })); nodeName = PAActiveObject.getNode().getVMInformation().getName().replace('-', '_'); tmpDirNode = new File(tmpDir, nodeName); if (!tmpDirNode.exists() || !tmpDirNode.isDirectory()) { tmpDirNode.mkdir(); } initialized = true; } } private void scilabStarter() throws Throwable { Runnable runner = new Runnable() { public void run() { try { engine = new Scilab(); if (engine.open()) { } else { throw new IllegalStateException("Scilab engine could not start"); } initialized = true; } catch (Throwable t) { initError = t; initErrorOccured = true; } } }; Thread starter = new Thread(runner); starter.start(); int nbwait = 0; while (!initialized && !initErrorOccured && nbwait < 200) { try { Thread.sleep(50); nbwait++; } catch (InterruptedException e) { e.printStackTrace(); } } if (initErrorOccured) throw initError; if (!initialized) throw new ScilabInitializationHanged( "Couldn't initialize the Scilab engine, this is due to a known bug in Scilab initialization"); } public void init(String inputScript, String functionName, ArrayList<String> scriptLines, PASolveScilabGlobalConfig paconfig, PASolveScilabTaskConfig taskconfig, ScilabEngineConfig conf) throws Exception { if (!this.engineConfig.equals(conf)) { terminate(); } this.engineConfig = conf; this.inputScript = inputScript; this.mainscriptLines = scriptLines; this.paconfig = paconfig; this.taskconfig = taskconfig; this.functionName = functionName; // Create a log file if debug is enabled this.createLogFileOnDebug(); } private void testEngineInitOrRestart() throws Exception { initializeEngine(); try { ScilabBoolean test = new ScilabBoolean(true); put("test", test); ScilabType answer = get("test"); if ((answer == null) || !(answer instanceof ScilabBoolean)) { restart(); } if (answer.getHeight() != 1 || answer.getWidth() != 1) { restart(); } boolean[][] data = ((ScilabBoolean) answer).getData(); if (data[0][0] != true) { restart(); } exec("clear test"); } catch (Exception e) { restart(); } // ok } private void restart() throws Exception { try { terminate(); } catch (Exception e) { } initializeEngine(); } private void initDS() throws Exception { // Changing dir to local space URI ls = paconfig.getLocalSpace(); if (ls != null) { localSpace = new File(ls); if (localSpace.exists() && localSpace.canRead() && localSpace.canWrite()) { exec("cd('" + localSpace + "');"); tempSubDir = new File(localSpace, paconfig.getTempSubDirName()); } else { System.err.println("Error, can't write on : " + localSpace); printLog("Error, can't write on : " + localSpace); throw new IllegalStateException("Error, can't write on : " + localSpace); } } } private void transferSource() throws Exception { if (paconfig.isTransferSource() && tempSubDir != null) { if (paconfig.isDebug()) { System.out.println("Loading source files from " + tempSubDir); } File[] files = tempSubDir.listFiles(new FileFilter() { public boolean accept(File pathname) { if (pathname.getName().matches(".*\\.sci")) { return true; } return false; } }); if (files != null && files.length > 0) { exec("try;getd('" + tempSubDir + "');catch; end;"); } if (taskconfig.getFunctionVarFiles() != null) { for (String fileName : taskconfig.getFunctionVarFiles()) { exec("load('" + this.tempSubDir + fs + fileName + "');"); } } } } private void transferInputVariables() throws Exception { if (paconfig.isTransferVariables()) { File inMat = new File(taskconfig.getInputVariablesFileURI()); printLog("Loading Input Variable file " + inMat); exec("load('" + inMat + "');"); if (taskconfig.getComposedInputVariablesFileURI() != null) { File compinMat = new File(taskconfig.getComposedInputVariablesFileURI()); exec("load('" + compinMat + "');in=out;clear out;"); } } } private ScilabType transferOutputVariable() throws Exception { File outputFile = new File(tempSubDir, taskconfig.getOutputVariablesFileName()); printLog("Saving Output Variable file " + outputFile); exec("save('" + outputFile + "',out);"); if (!outputFile.exists()) { throw new ScilabTaskException(); } ScilabType out = new ScilabBoolean(true); return out; } public Serializable execute(int index, TaskResult... results) throws Throwable { testEngineInitOrRestart(); prepare(); boolean ok = true; if (!paconfig.isTransferVariables()) { HashMap<String, List<ScilabType>> newEnv = new HashMap<String, List<ScilabType>>(); if (results != null) { if (results.length > 1) { throw new InvalidNumberOfParametersException(results.length); } if (results.length == 1) { TaskResult res = results[0]; if (!(res.value() instanceof ScilabType)) { throw new InvalidParameterException(res.value().getClass()); } ScilabType in = (ScilabType) res.value(); put("in", in); } } } // Initialization, clearing up old variables : prepare(); initDS(); transferSource(); transferInputVariables(); //if (paconfig.isDebug()) { // exec("who"); //} if (inputScript != null) { printLog("Executing inputscript"); ok = executeScript(inputScript, false); if (paconfig.isDebug()) { System.out.println("End of inputscript execution"); } } printLog("Executing mainscript"); ok = executeScript(prepareScript(mainscriptLines), true); printLog("End of mainscript execution " + (ok ? "ok" : "ko")); //if (!ok) // throw new ScilabTaskException(); return getResults(ok); } /** * Terminates the Scilab engine * * @return true for synchronous call */ public BooleanWrapper terminate() { engine.close(); engine = null; initialized = false; return new BooleanWrapper(true); } private void prepare() { exec("errclear();clear;"); if (paconfig.isDebug()) { // To be improved exec("mode(3);lines(0);funcprot(0);"); } else { exec("lines(0);funcprot(0);"); } } public boolean cleanup() { if (engine != null) { exec("errclear();clear;"); exec("cd('" + tmpDir + "');"); } return true; } /** * Retrieves the output variables * * @return list of Scilab data */ protected ScilabType getResults(boolean ok) throws Exception { ScilabType out; printLog("Receiving outputs"); if (!ok) { throw new ScilabTaskException(); } if (paconfig.isTransferVariables()) { out = transferOutputVariable(); } else { try { out = get("out"); } catch (Exception e) { throw new ScilabTaskException(); } } return out; } /** * Executes both input and main scripts on the engine * * @throws Throwable */ protected boolean executeScript(String script, boolean eval) throws Throwable { if (eval) { if (script.indexOf(31) >= 0) { String[] lines = script.split("" + ((char) 31)); printLog("Executing multi-line: " + script); for (String line : lines) { // The special character ASCII 30 means that we want to execute the line using execstr instead of directly // This is used to get clearer error messages from Scilab if (line.startsWith("" + ((char) 30))) { String modifiedLine = "execstr('" + line.substring(1) + "','errcatch','n');"; printLog("Executing : " + modifiedLine); exec(modifiedLine); int errorcode = lasterrorcode(); if ((errorcode != 0) && (errorcode != 2)) { writeError(); return false; } } else { printLog("Executing : " + line); exec(line); int errorcode = lasterrorcode(); if ((errorcode != 0) && (errorcode != 2)) { writeError(); return false; } } } } else { printLog("Executing single-line: " + script); exec(script); int errorcode = lasterrorcode(); if ((errorcode != 0) && (errorcode != 2)) { writeError(); return false; } } } else { File temp; BufferedWriter out; printLog("Executing inputscript: " + script); temp = new File(tmpDirNode, "inpuscript.sce"); if (temp.exists()) { temp.delete(); } temp.createNewFile(); temp.deleteOnExit(); out = new BufferedWriter(new FileWriter(temp)); out.write(script); out.close(); if (paconfig.isDebug()) { exec("exec('" + temp.getAbsolutePath() + "',3);"); } else { exec("exec('" + temp.getAbsolutePath() + "',0);"); } int errorcode = lasterrorcode(); if ((errorcode != 0) && (errorcode != 2)) { exec("disp(lasterror())"); exec("errclear();"); return false; } } return true; } private void put(String name, ScilabType var) throws Exception { engine.put(name, var); } private ScilabType get(String name) throws Exception { return engine.get(name); } private void exec(String code) { engine.exec(code); } private int lasterrorcode() { return engine.getLastErrorCode(); } /** * Ouput in scilab the error occured */ private void writeError() { engine .exec("[str2,n2,line2,func2]=lasterror(%t);printf('!-- error %i\n%s\n at line %i of function %s\n',n2,str2,line2,func2)"); engine.exec("errclear();"); } /** * Appends all the script's lines as a single string * * @return single line script */ private String prepareScript(List<String> scriptLines) { String script = ""; for (String line : scriptLines) { script += line; script += nl; } return script; } private void printLog(final String message) { if (!this.paconfig.isDebug()) { return; } final Date d = new Date(); final String log = "[" + ISO8601FORMAT.format(d) + " " + HOSTNAME + " " + this.getClass() + "] " + message; System.out.println(log); System.out.flush(); if (this.outDebugWriter != null) { this.outDebugWriter.println(log); this.outDebugWriter.flush(); } } /** Creates a log file in the java.io.tmpdir if debug is enabled */ private void createLogFileOnDebug() throws Exception { if (!this.paconfig.isDebug()) { return; } String nodeName = MatSciEngineConfigBase.getNodeName(); String tmpPath = System.getProperty("java.io.tmpdir"); // system temp dir (not using java.io.tmpdir since in runasme it can be // inaccesible and the scratchdir property can inherited from parent jvm) // if (this.paconfig.isRunAsMe()) { // tmpPath = System.getProperty("node.dataspace.scratchdir"); // } // log file writer used for debugging File tmpDirFile = new File(tmpPath); File nodeTmpDir = new File(tmpDirFile, nodeName); if (!nodeTmpDir.exists()) { nodeTmpDir.mkdirs(); } File logFile = new File(tmpPath, this.getClass() + "_" + nodeName + ".log"); if (!logFile.exists()) { logFile.createNewFile(); } try { FileWriter outFile = new FileWriter(logFile); PrintWriter out = new PrintWriter(outFile); outDebugWriter = out; } catch (IOException e) { e.printStackTrace(); } } }
package com.lv.activity; import com.lv.movice.R; import android.animation.Animator; import android.animation.Animator.AnimatorListener; import android.animation.AnimatorInflater; import android.animation.AnimatorSet; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.widget.ImageView; public class MainActivity extends Activity { private ImageView back; private AnimatorSet animator; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); back=(ImageView) findViewById(R.id.background); animator=(AnimatorSet) AnimatorInflater.loadAnimator(this, R.animator.scale); animator.setTarget(back); animator.addListener(new AnimatorListener() { @Override public void onAnimationStart(Animator animation) { // TODO Auto-generated method stub } @Override public void onAnimationRepeat(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { startActivity(new Intent(MainActivity.this, ClientActivity.class)); finish(); } @Override public void onAnimationCancel(Animator animation) { } }); animator.start(); } }
/* * jsp나 servlet둘다 웹서버에서 해석 및 실행되어지므로, 글 등록 요청을 처리할 때는 * 둘다 가능하다. * 하지만 현재 시점에서 jsp로 개발하지 않는 이유는? * 앞으로 jsp는 서블릿의 디자인적 처리시 단점을 보완하기 위해 개발된 기술이므로 * jsp는 주로 디자인 영역에서 사용된다.. * * */ package com.webapp1216.board.controller; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.webapp1216.board.model.Notice; import com.webapp1216.board.model.NoticeDAO; public class RegistServlet extends HttpServlet{ NoticeDAO dao = new NoticeDAO(); //참고) doXXX형 메서드는 service()메서드에 의해 호출된다 이 때, 요청과 응답 객체가 전달된다. //글 쓰기를 처리하는 서블릿이므로, 클라이언트의 요청이 post로 들어온다 @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //클라이언트의 파라미터 받기 request.setCharacterEncoding("utf-8"); //파라미터에 대한 인코딩 처리 String title = request.getParameter("title"); String writer = request.getParameter("writer"); String content = request.getParameter("content"); //vo에 담자 Notice notice = new Notice(); notice.setTitle(title); notice.setWriter(writer); notice.setContent(content); //클라이언트의 브라우저에 출력할 데이터를 응답객체에 심어놓기 //response.setContentType("text/html;charset=utf-8"); response.setContentType("text/html"); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); //out.print("제목은 "+title+"<br>"); //out.print("작성자는 "+writer+"<br>"); //out.print("내용은 "+content+"<br>"); int result= dao.insert(notice); //글 등록 if(result==0) { out.print("<script>"); out.print("alert('등록실패');"); out.print("history.back();"); out.print("</script>"); }else { out.print("<script>"); out.print("alert('등록성공');"); out.print("location.href='/board/list';"); out.print("</script>"); } } }
package entities; import java.io.Serializable; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; /** * * @author Malthe */ public class GeoCityDetails implements Serializable { public String city; public String country; public String elevationMeters; public String population; }
public class MainClass { public static void main(String[] args) { PhaseOneProject object=new PhaseOneProject(); object.program(); } }
package org.ronkitay.lectures.encodings; import java.nio.charset.StandardCharsets; import java.util.Base64; /** * @author Ron Kitay * @since 03-Oct-2021. */ public class Base64Encoding { public static void main(String[] args) { demoEncoding(); demoDecoding(); } private static void demoEncoding() { byte[] encoded = Base64.getEncoder().encode("ABC".getBytes(StandardCharsets.UTF_8)); String prettyEncoded = new String(encoded, StandardCharsets.US_ASCII); System.out.printf("'ABC' encoded in Base64 is: %s%n", prettyEncoded); } private static void demoDecoding() { byte[] decoded = Base64.getDecoder().decode("QUJD"); String prettyDecoded = new String(decoded, StandardCharsets.UTF_8); System.out.printf("'QUJD' decoded from Base64 is: %s%n", prettyDecoded); } }
import java.util.Scanner; public class GuessNumber { public static void main(String[] args) { System.out.println("This is a program for number guessing."); Scanner input = new Scanner(System.in); int num = (int)(Math.random() * 100); int a = 0; //lower limit int b = 99; //upper limit System.out.println("Please input a number.(From " + a + " to " + b + ")"); int x = input.nextInt(); //System.out.println(num); //for debug while(x < a || x > b ) { System.out.println("Input value is not in range. Please input again.(From " + a + " to " + b + ")"); x = input.nextInt(); } //A(0). while( x != num ) { if(x < num) a = x + 1; else if(x > num) b = x - 1; //To change range. if (b == a) { System.out.println("You lose! The answer is " + num + "."); break; } // Loss condition. System.out.println("Please input again.(From " + a + " to " + b + ")"); x = input.nextInt(); while(x < a || x > b ) { System.out.println("Input value is not in range. Please input again.(From " + a + " to " + b + ")"); x = input.nextInt(); } //To check whether if the input value is in range. } //A(n) loop. if (x == num) { System.out.println("Congratulatins! You win."); } // Win condition. input.close(); } }
package commands; import java.io.File; import java.util.List; import javax.swing.JOptionPane; import model.ApplicationContext; import org.apache.commons.io.FileUtils; import events.DirectoryChanged; import exceptions.FileNotSelectedException; import view.localization.Localization; public class Move implements Command { private List<File> sourceFiles; private String destinationPath; public Move(List<File> sourceFiles, String destinationPath) { this.sourceFiles = sourceFiles; this.destinationPath = destinationPath; } @Override public void execute() throws Exception { if (sourceFiles == null || sourceFiles.isEmpty()) { throw new FileNotSelectedException(); } File destinationFile = new File(destinationPath); for (File file : sourceFiles) { if (file.isDirectory()) { String message = Localization.get("Move_DirConfirmation").replace("{0}", file.getName()); int result = JOptionPane.showConfirmDialog( ApplicationContext.getMainWindow(), message, Localization.get("Move_Title"), JOptionPane.YES_NO_CANCEL_OPTION); if (result == JOptionPane.NO_OPTION) { continue; } if (result == JOptionPane.CANCEL_OPTION) { return; } if (destinationFile.isDirectory()) { FileUtils.moveDirectoryToDirectory(file, destinationFile, true); } else { FileUtils.moveDirectory(file, destinationFile); } } else { if (destinationFile.isDirectory()) { FileUtils.moveFileToDirectory(file, destinationFile, true); } else { FileUtils.moveFile(file, destinationFile); } } String sourceBaseDir = sourceFiles.get(0).getParent(); ApplicationContext.publishForContextsInDir(sourceBaseDir, new DirectoryChanged(sourceBaseDir)); ApplicationContext.publishForContextsInDir(destinationPath, new DirectoryChanged(destinationPath)); } } }
package com.backend.listener; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.servlet.ServletContext; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import javax.websocket.Session; public class OnlineListener implements ServletContextListener{ private static Map<String, Session> sessionsMap = new ConcurrentHashMap<>(); public void contextInitialized(ServletContextEvent event) { ServletContext context = event.getServletContext(); context.setAttribute("TEA101G2DV_OnlineList", sessionsMap); System.out.println("FFFFFUCKTEA101G2DV_OnlineList"); } public void contextDestroyed(ServletContextEvent event) { ServletContext context = event.getServletContext(); context.removeAttribute("TEA101G2DV_OnlineList"); System.out.println("FUCKKKKKTEA101G2DV_OnlineList"); } }
package Metaphase02; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class HashMapIterator { public static void main(String[] args) { HashMap<String,String> map = new HashMap<>(); map.put("a","s"); map.put("b","ss"); map.put("c","sss"); map.put("d","ssss"); //先封装成set集合 Iterator<Map.Entry<String,String>> itr = map.entrySet().iterator(); while(itr.hasNext()){ Map.Entry<String,String> entry = itr.next(); System.out.println(entry.getKey()+"::"+entry.getValue()); } } }
package com.chisw.timofei.booking.reservation.controller; import com.chisw.timofei.booking.reservation.controller.api.ReservationRestService; import com.chisw.timofei.booking.reservation.controller.api.dto.GuestDTO; import com.chisw.timofei.booking.reservation.controller.api.dto.ReservationDTO; import com.chisw.timofei.booking.reservation.service.api.ReservationManagement; import com.chisw.timofei.booking.reservation.service.api.ReservationProvider; import com.google.common.collect.Lists; import lombok.extern.slf4j.Slf4j; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.inject.Inject; import java.util.List; /** * @author timofei.kasianov 10/2/18 */ @Slf4j @RestController public class ReservationRestServiceImpl implements ReservationRestService { private final ReservationProvider reservationProvider; private final ReservationManagement reservationManagement; @Inject public ReservationRestServiceImpl(ReservationProvider reservationProvider, ReservationManagement reservationManagement) { this.reservationProvider = reservationProvider; this.reservationManagement = reservationManagement; } @Override @GetMapping("/") public ResponseEntity<List<ReservationDTO>> list() { log.info("list"); final List<ReservationDTO> mockResponse = Lists.newArrayList( new ReservationDTO(1L, 1L, 1L, "accommodation-id", 1L, new GuestDTO("", "", "")) ); return ResponseEntity.ok().body(mockResponse); } @Override @GetMapping("/accommodations/{id}") public ResponseEntity<List<ReservationDTO>> listByAccommodationId(@PathVariable("id") String accommodationId) { log.info("listByAccommodationId"); final List<ReservationDTO> mockResponse = Lists.newArrayList( new ReservationDTO(1L, 1L, 1L, accommodationId, 1L, new GuestDTO("", "", "")) ); return ResponseEntity.ok().body(mockResponse); } @Override @GetMapping("/{id}") public ResponseEntity<ReservationDTO> get(@PathVariable("id") long reservationId) { log.info("get"); return ResponseEntity.ok().body(new ReservationDTO( 1L, 1L, 1L, "acc_id", 1L, new GuestDTO("", "", "")) ); } @Override @PostMapping("/") public ResponseEntity<Long> create(@RequestBody ReservationDTO createRequest) { log.info("create"); return ResponseEntity.ok().body(1L); } @Override @PutMapping("/{id}") public ResponseEntity<Void> update(@PathVariable("id") long reservationId, @RequestBody ReservationDTO updateRequest) { log.info("update"); return ResponseEntity.ok().build(); } @Override @DeleteMapping("/{id}") public ResponseEntity<Void> delete(@PathVariable("id") long reservationId) { log.info("delete"); return ResponseEntity.ok().build(); } }
package stormedpanda.simplyjetpacks.items; import net.minecraft.inventory.EquipmentSlotType; import net.minecraft.item.ArmorItem; import net.minecraft.item.Item; import stormedpanda.simplyjetpacks.SimplyJetpacks; import stormedpanda.simplyjetpacks.lists.ArmorMaterialList; public class PilotGogglesItem extends ArmorItem { public PilotGogglesItem() { super(ArmorMaterialList.PILOT_GOGGLES, EquipmentSlotType.HEAD, new Item.Properties().group(SimplyJetpacks.tabSimplyJetpacks)); } }
package com.instantviking.tile.animation; public class DefaultTileAnimation implements Animation { @Override public void tick(long delta) { } @Override public float getCompletionFactor() { return 0; } }
package dulieu; public class ChuyenNganh extends SV{ private int STT; private String HoTen,Khoa,MonHoc; private float TinChi; private String GhiChu; //constructor public ChuyenNganh() { } public ChuyenNganh(int STT, String HoTen, String Khoa, String MonHoc, float TinChi, String GhiChu) { this.STT = STT; this.HoTen = HoTen; this.Khoa = Khoa; this.MonHoc = MonHoc; this.TinChi = TinChi; this.GhiChu = GhiChu; } public ChuyenNganh(int STT, String HoTen, String Khoa, String MonHoc, float TinChi, String GhiChu, String MaSinhVien) { super(MaSinhVien); this.STT = STT; this.HoTen = HoTen; this.Khoa = Khoa; this.MonHoc = MonHoc; this.TinChi = TinChi; this.GhiChu = GhiChu; } //set-get public int getSTT() { return STT; } public void setSTT(int STT) { this.STT = STT; } public String getKhoa() { return Khoa; } public void setKhoa(String Khoa) { this.Khoa = Khoa; } public String getMonHoc() { return MonHoc; } public void setMonHoc(String MonHoc) { this.MonHoc = MonHoc; } public float getTinChi() { return TinChi; } public void setTinChi(float TinChi) { this.TinChi = TinChi; } public String getGhiChu() { return GhiChu; } public void setGhiChu(String GhiChu) { this.GhiChu = GhiChu; } public String getMaSinhVien() { return MaSinhVien; } public void setMaSinhVien(String MaSinhVien) { this.MaSinhVien = MaSinhVien; } public String getHoTen() { return HoTen; } public void setHoTen(String HoTen) { this.HoTen = HoTen; } }
package com.mkyong.web.model; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name = "journey") public class Journey implements Serializable, Comparable<Journey> { private Long journeyId; private UserRoute userRoute; private Location location; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "journey_id", unique = true, nullable = false) public Long getJourneyId() { return journeyId; } public void setJourneyId(Long journeyId) { this.journeyId = journeyId; } @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "user_route_id") public UserRoute getUserRoute() { return userRoute; } public void setUserRoute(UserRoute userRoute) { this.userRoute = userRoute; } @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "location_id") public Location getLocation() { return location; } public void setLocation(Location location) { this.location = location; } @Override public int compareTo(Journey o) { if(this.journeyId < o.journeyId){ return 1; }else if(this.journeyId > o.journeyId){ return -1; } return 0; } }
package com.yjxxt.server.mapper; import com.yjxxt.server.pojo.PoliticsStatus; import com.baomidou.mybatisplus.core.mapper.BaseMapper; /** * <p> * Mapper 接口 * </p> * * @author tk * @since 2021-09-24 */ public interface PoliticsStatusMapper extends BaseMapper<PoliticsStatus> { }
/* * Copyright 2002-2023 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.support; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import org.springframework.context.ApplicationContextException; import org.springframework.lang.Nullable; import org.springframework.util.Assert; /** * Convenient superclass for application objects that want to be aware of * the application context, e.g. for custom lookup of collaborating beans * or for context-specific resource access. It saves the application * context reference and provides an initialization callback method. * Furthermore, it offers numerous convenience methods for message lookup. * * <p>There is no requirement to subclass this class: It just makes things * a little easier if you need access to the context, e.g. for access to * file resources or to the message source. Note that many application * objects do not need to be aware of the application context at all, * as they can receive collaborating beans via bean references. * * <p>Many framework classes are derived from this class, particularly * within the web support. * * @author Rod Johnson * @author Juergen Hoeller * @see org.springframework.web.context.support.WebApplicationObjectSupport */ public abstract class ApplicationObjectSupport implements ApplicationContextAware { /** Logger that is available to subclasses. */ protected final Log logger = LogFactory.getLog(getClass()); /** ApplicationContext this object runs in. */ @Nullable private ApplicationContext applicationContext; /** MessageSourceAccessor for easy message access. */ @Nullable private MessageSourceAccessor messageSourceAccessor; @Override public final void setApplicationContext(@Nullable ApplicationContext context) throws BeansException { if (context == null && !isContextRequired()) { // Reset internal context state. this.applicationContext = null; this.messageSourceAccessor = null; } else if (this.applicationContext == null) { // Initialize with passed-in context. if (!requiredContextClass().isInstance(context)) { throw new ApplicationContextException( "Invalid application context: needs to be of type [" + requiredContextClass().getName() + "]"); } this.applicationContext = context; this.messageSourceAccessor = new MessageSourceAccessor(context); initApplicationContext(context); } else { // Ignore reinitialization if same context passed in. if (this.applicationContext != context) { throw new ApplicationContextException( "Cannot reinitialize with different application context: current one is [" + this.applicationContext + "], passed-in one is [" + context + "]"); } } } /** * Determine whether this application object needs to run in an ApplicationContext. * <p>Default is "false". Can be overridden to enforce running in a context * (i.e. to throw IllegalStateException on accessors if outside a context). * @see #getApplicationContext * @see #getMessageSourceAccessor */ protected boolean isContextRequired() { return false; } /** * Determine the context class that any context passed to * {@code setApplicationContext} must be an instance of. * Can be overridden in subclasses. * @see #setApplicationContext */ protected Class<?> requiredContextClass() { return ApplicationContext.class; } /** * Subclasses can override this for custom initialization behavior. * Gets called by {@code setApplicationContext} after setting the context instance. * <p>Note: Does <i>not</i> get called on re-initialization of the context * but rather just on first initialization of this object's context reference. * <p>The default implementation calls the overloaded {@link #initApplicationContext()} * method without ApplicationContext reference. * @param context the containing ApplicationContext * @throws ApplicationContextException in case of initialization errors * @throws BeansException if thrown by ApplicationContext methods * @see #setApplicationContext */ protected void initApplicationContext(ApplicationContext context) throws BeansException { initApplicationContext(); } /** * Subclasses can override this for custom initialization behavior. * <p>The default implementation is empty. Called by * {@link #initApplicationContext(ApplicationContext)}. * @throws ApplicationContextException in case of initialization errors * @throws BeansException if thrown by ApplicationContext methods * @see #setApplicationContext */ protected void initApplicationContext() throws BeansException { } /** * Return the ApplicationContext that this object is associated with. * @throws IllegalStateException if not running in an ApplicationContext */ @Nullable public final ApplicationContext getApplicationContext() throws IllegalStateException { if (this.applicationContext == null && isContextRequired()) { throw new IllegalStateException( "ApplicationObjectSupport instance [" + this + "] does not run in an ApplicationContext"); } return this.applicationContext; } /** * Obtain the ApplicationContext for actual use. * @return the ApplicationContext (never {@code null}) * @throws IllegalStateException in case of no ApplicationContext set * @since 5.0 */ protected final ApplicationContext obtainApplicationContext() { ApplicationContext applicationContext = getApplicationContext(); Assert.state(applicationContext != null, "No ApplicationContext"); return applicationContext; } /** * Return a MessageSourceAccessor for the application context * used by this object, for easy message access. * @throws IllegalStateException if not running in an ApplicationContext */ @Nullable protected final MessageSourceAccessor getMessageSourceAccessor() throws IllegalStateException { if (this.messageSourceAccessor == null && isContextRequired()) { throw new IllegalStateException( "ApplicationObjectSupport instance [" + this + "] does not run in an ApplicationContext"); } return this.messageSourceAccessor; } }
package com.gsitm.reserv.vo; import lombok.Data; import lombok.Getter; import lombok.Setter; /** * @author : 이창주 * @programName : SnackVO.java * @date : 2018. 6. 08. * @function : 간식 정보를 갖는 VO * <p> * [이름] [수정일] [내용] * ---------------------------------------------------------- * 이창주 2018-06-08 초안 작성 */ @Data public class SnackVO { @Getter @Setter String wpNo; @Getter @Setter String snackNo; @Getter @Setter String snackName; @Getter @Setter int quantity; @Getter @Setter int price; }
package core.event.game.turn; import core.server.game.controllers.mechanics.TurnGameController; public class DrawStartTurnEvent extends AbstractTurnEvent { public DrawStartTurnEvent(TurnGameController turn) { super(turn); } }
package com.liuyufei.bmc_android.admin; import android.content.ContentResolver; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Handler; import android.support.annotation.RequiresApi; import android.support.v4.app.Fragment; import android.support.v4.app.LoaderManager; import android.support.v4.content.CursorLoader; import android.support.v4.content.Loader; import android.util.Log; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import android.widget.SearchView; import com.liuyufei.bmc_android.R; import com.liuyufei.bmc_android.data.BMCContract; import com.liuyufei.bmc_android.model.Staff; public class StaffFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> { ContentResolver contentResolver; private static final int URL_LOADER = 0; /** * Mandatory empty constructor for the fragment manager to instantiate the * fragment (e.g. upon screen orientation changes). */ public StaffFragment() { } // TODO: Customize parameter initialization @SuppressWarnings("unused") public static StaffFragment newInstance(int columnCount) { StaffFragment fragment = new StaffFragment(); Bundle args = new Bundle(); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setHasOptionsMenu(true); getLoaderManager().initLoader(URL_LOADER, null, this); } Cursor cursor; StaffCursorAdapter adapter; ListView lv; @RequiresApi(api = Build.VERSION_CODES.M) @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_staff_list, container, false); contentResolver = view.getContext().getContentResolver(); lv = (ListView) view; adapter = new StaffCursorAdapter(getContext(), cursor, false); lv.setAdapter(adapter); lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int pos, long id) { //move the cursor to the selected row cursor = (Cursor) adapterView.getItemAtPosition(pos); //get the object data from the cursor int staffID = cursor.getInt(cursor.getColumnIndex(BMCContract.StaffEntry._ID)); String staffMobile = cursor.getString(cursor.getColumnIndex(BMCContract.StaffEntry.COLUMN_MOBILE)); String staffName = cursor.getString(cursor.getColumnIndex(BMCContract.StaffEntry.COLUMN_NAME)); String staffPhoto = cursor.getString(cursor.getColumnIndex(BMCContract.StaffEntry.COLUMN_PHOTO)); String staffDepartment = cursor.getString(cursor.getColumnIndex(BMCContract.StaffEntry.COLUMN_DEPARTMENT)); String staffTitle = cursor.getString(cursor.getColumnIndex(BMCContract.StaffEntry.COLUMN_TITLE)); //create the object that will be passed to the todoActivity Staff staff = new Staff(staffID, staffName, staffPhoto, staffDepartment, staffTitle, staffMobile); Intent intent = new Intent(getActivity(), EditStaffActivity.class); //pass the ID to the todoActivity intent.putExtra("staff", staff); startActivity(intent); } }); return view; } @Override public android.support.v4.content.Loader<Cursor> onCreateLoader(int id, Bundle args) { //change selection Log.i("onCreateLoader", "onCreateLoader selection changed"); Uri resourceUri = BMCContract.StaffEntry.CONTENT_URI; String[] selectionArgs = null; String selection = ""; String orderBy = null; if (args != null) { selectionArgs = args.getStringArray("selectionArgs"); selection = args.getString("selection"); String table = args.getString("table"); switch (table) { case BMCContract.StaffEntry.TABLE_NAME: resourceUri = BMCContract.StaffEntry.CONTENT_URI; orderBy = BMCContract.StaffEntry.COLUMN_NAME; break; case BMCContract.VisitorEntry.TABLE_NAME: resourceUri = BMCContract.VisitorEntry.CONTENT_URI; break; case BMCContract.AppointmentEntry.TABLE_NAME: resourceUri = BMCContract.AppointmentEntry.CONTENT_URI; break; } } Loader<Cursor> lc = new CursorLoader(getActivity(), resourceUri, null, selection, selectionArgs, orderBy); return lc; } @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { adapter.swapCursor(data); } @Override public void onLoaderReset(Loader<Cursor> loader) { adapter.swapCursor(null); } /* @RequiresApi(api = Build.VERSION_CODES.M) @Override public void onLoadFinished(Loader<Cursor> loader, Cursor data) { adapter.swapCursor(data); } @Override public void onLoaderReset(Loader<Cursor> loader) { adapter.swapCursor(null); } */ Handler handler = new Handler(); boolean canRun = true; @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.search_menu, menu); MenuItem searchItem = menu.findItem(R.id.search_item); SearchView searchView = (SearchView) searchItem.getActionView(); searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextSubmit(String query) { return true; } @Override public boolean onQueryTextChange(final String newText) { if (newText.length() >1) { String selection = BMCContract.StaffEntry.COLUMN_NAME + " like ?"; String[] selectionArgs = {"%"+newText+"%"}; Bundle bundle = new Bundle(); bundle.putString("selection", selection); bundle.putStringArray("selectionArgs", selectionArgs); bundle.putString("table", BMCContract.StaffEntry.TABLE_NAME); getLoaderManager().restartLoader(URL_LOADER, bundle, StaffFragment.this); }else{ //select all records getLoaderManager().restartLoader(URL_LOADER, null, StaffFragment.this); } return false; } }); searchView.setQueryHint("Search"); super.onCreateOptionsMenu(menu, inflater); super.onCreateOptionsMenu(menu, inflater); } }
package automat; public interface Resource { String uri(); }
package ua.com.rd.pizzaservice.service.pizza; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import ua.com.rd.pizzaservice.domain.pizza.Pizza; import ua.com.rd.pizzaservice.service.ServiceTestUtils; import java.util.HashSet; import java.util.Set; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:/inMemDbRepositoryContext.xml", "classpath:/appContext.xml", }) public class PizzaServiceImplInMemDbTest extends AbstractTransactionalJUnit4SpringContextTests { @Autowired private PizzaService pizzaService; private ServiceTestUtils serviceTestUtils; @Before public void setUp() { serviceTestUtils = new ServiceTestUtils(jdbcTemplate); } @Test public void getPizzaByIdTest() { Pizza pizza = serviceTestUtils.createPizza(1L, "Margarita", 150., Pizza.PizzaType.MEAT); Pizza newPizza = pizzaService.getPizzaById(pizza.getId()); Assert.assertEquals(pizza, newPizza); } @Test public void savePizzaTest() { Pizza pizza = new Pizza(); pizza.setName("Margarita"); pizza.setPrice(150.); pizza.setType(Pizza.PizzaType.MEAT); pizzaService.savePizza(pizza); Assert.assertNotNull(pizza.getId()); } @Test public void deletePizzaTest() { Pizza pizza = serviceTestUtils.createPizza(1L, "Margarita", 150., Pizza.PizzaType.MEAT); pizzaService.deletePizza(pizza); int countOfRecords = getCountOfPizzasById(pizza.getId()); Assert.assertEquals(0, countOfRecords); } private int getCountOfPizzasById(Long id) { final String sql = "SELECT COUNT(*) FROM pizzas WHERE pizza_id = ?"; return jdbcTemplate.queryForObject(sql, new Object[]{id}, Integer.class); } @Test public void findAllTest() { Pizza pizza1 = serviceTestUtils.createPizza(1L, "Margarita1", 150., Pizza.PizzaType.MEAT); Pizza pizza2 = serviceTestUtils.createPizza(2L, "Margarita2", 190., Pizza.PizzaType.SEA); Pizza pizza3 = serviceTestUtils.createPizza(3L, "Margarita3", 120., Pizza.PizzaType.VEGETARIAN); Pizza pizza4 = serviceTestUtils.createPizza(4L, "Margarita4", 130., Pizza.PizzaType.MEAT); Set<Pizza> pizzas = pizzaService.findAll(); Assert.assertEquals(4, pizzas.size()); Set<Pizza> expected = new HashSet<>(); expected.add(pizza1); expected.add(pizza2); expected.add(pizza3); expected.add(pizza4); Assert.assertEquals(expected, pizzas); } }
package project; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JPasswordField; import javax.swing.border.EmptyBorder; import lotto.dao.MemberDAO; import javax.swing.JTextField; import javax.swing.JLabel; import javax.swing.JOptionPane; import java.awt.Font; import java.awt.Toolkit; import javax.swing.JRadioButton; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JDialog; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class JoinGUI extends JFrame { private JPanel contentPane; private JLabel lbl_joinId; private JLabel lbl_joinpwd; private JLabel lbl_admin; private JTextField txt_joinId; private JTextField txt_joinpwd; private JLabel lblNewLabel_1; private JRadioButton rdbtn_user; private JRadioButton rdbtn_admin; private JButton btn_submit; private JButton btn_exit; private JDialog dialog; MemberDAO dao = new MemberDAO(); /** * Launch the application. */ public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { public void run() { try { JoinGUI frame = new JoinGUI(); frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the frame. */ public JoinGUI() { try{ dao.dbConnect(); }catch(Exception e){ e.printStackTrace(); } initGUI(); } private void initGUI() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setBounds(100, 100, 282, 288); //화면 중앙 출력을 위한 코드----- Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension frameSize = this.getSize(); int xpos = (int)(screenSize.getWidth() - frameSize.getWidth()) / 2; int ypos = (int)(screenSize.getHeight() - frameSize.getHeight()) / 2; this.setLocation(xpos, ypos); //-------------------------------- contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); lbl_joinId = new JLabel("ID"); lbl_joinId.setBounds(30, 76, 57, 15); contentPane.add(lbl_joinId); lbl_joinpwd = new JLabel("password"); lbl_joinpwd.setBounds(30, 115, 57, 15); contentPane.add(lbl_joinpwd); lbl_admin = new JLabel("admin"); lbl_admin.setBounds(30, 158, 57, 15); contentPane.add(lbl_admin); txt_joinId = new JTextField(); txt_joinId.setBounds(109, 73, 116, 21); contentPane.add(txt_joinId); txt_joinId.setColumns(10); txt_joinpwd = new JPasswordField(); txt_joinpwd.setColumns(10); txt_joinpwd.setBounds(109, 112, 116, 21); contentPane.add(txt_joinpwd); lblNewLabel_1 = new JLabel("회원가입"); lblNewLabel_1.setFont(new Font("굴림", Font.BOLD, 30)); lblNewLabel_1.setBounds(63, 20, 136, 41); contentPane.add(lblNewLabel_1); rdbtn_user = new JRadioButton("User"); rdbtn_user.setBounds(104, 154, 121, 23); contentPane.add(rdbtn_user); rdbtn_admin = new JRadioButton("Admin"); rdbtn_admin.setBounds(104, 182, 121, 23); contentPane.add(rdbtn_admin); ButtonGroup bg = new ButtonGroup();//다중 선택 방지를 위하여 그룹을 지어줌 bg.add(rdbtn_admin); bg.add(rdbtn_user); btn_submit = new JButton("완료"); btn_submit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { do_btn_submit_actionPerformed(e); } }); btn_submit.setBounds(30, 211, 97, 23); contentPane.add(btn_submit); btn_exit = new JButton("종료"); btn_exit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { do_btn_exit_actionPerformed(e); } }); btn_exit.setBounds(139, 211, 97, 23); contentPane.add(btn_exit); setVisible(true); this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); } protected void do_btn_exit_actionPerformed(ActionEvent e) { // System.exit(0); // JOptionPane.showMessageDialog(null, "종료합니다");// 팝업창으로 알려주는 기능 setVisible(false); } protected void do_btn_submit_actionPerformed(ActionEvent e) { String id = txt_joinId.getText(); String pwd = txt_joinpwd.getText(); int admin = 0; if(rdbtn_admin.isSelected()){ admin = 1; }else if(rdbtn_user.isSelected()){ admin = 0; } // System.out.println(admin); //라디오 버튼값 확인용 int n = dao.insertMember(id, pwd, admin); if(n > 0){ // System.out.println("가입성공"); JOptionPane.showMessageDialog(null,"가입성공","축하합니다!!",JOptionPane.NO_OPTION); setVisible(false); } else{ // System.out.println("가입실패 : ID중복"); JOptionPane.showMessageDialog(null,"가입실패 : ID중복","Message",JOptionPane.ERROR_MESSAGE); } } }
/* * Origin of the benchmark: * repo: https://github.com/diffblue/cbmc.git * branch: develop * directory: regression/jbmc-strings/TokenTest01 * The benchmark was taken from the repo: 24 January 2018 */ import java.util.StringTokenizer; public class Main { public static void main(String[] args) { String sentence = "automatic test case generation"; String[] tokens = sentence.split(" "); System.out.printf("Number of elements: %d\nThe tokens are:\n", tokens.length); assert tokens.length==4; int i=0; for (String token : tokens) { System.out.println(token); if (i==0) assert token.equals("automatic"); else if (i==1) assert token.equals("test"); else if (i==2) assert token.equals("case"); else if (i==3) assert token.equals("generation"); ++i; } } }
package android.support.v7.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.drawable.Drawable; import android.os.Build.VERSION; import android.support.annotation.RestrictTo; import android.support.annotation.RestrictTo.Scope; import android.support.v4.view.GravityCompat; import android.support.v4.view.ViewCompat; import android.support.v7.appcompat.R; import android.util.AttributeSet; import android.view.View; import android.view.View.MeasureSpec; import android.view.ViewGroup; import android.view.ViewGroup.MarginLayoutParams; import android.view.accessibility.AccessibilityEvent; import android.view.accessibility.AccessibilityNodeInfo; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; public class LinearLayoutCompat extends ViewGroup { public static final int HORIZONTAL = 0; private static final int INDEX_BOTTOM = 2; private static final int INDEX_CENTER_VERTICAL = 0; private static final int INDEX_FILL = 3; private static final int INDEX_TOP = 1; public static final int SHOW_DIVIDER_BEGINNING = 1; public static final int SHOW_DIVIDER_END = 4; public static final int SHOW_DIVIDER_MIDDLE = 2; public static final int SHOW_DIVIDER_NONE = 0; public static final int VERTICAL = 1; private static final int VERTICAL_GRAVITY_COUNT = 4; private boolean mBaselineAligned; private int mBaselineAlignedChildIndex; private int mBaselineChildTop; private Drawable mDivider; private int mDividerHeight; private int mDividerPadding; private int mDividerWidth; private int mGravity; private int[] mMaxAscent; private int[] mMaxDescent; private int mOrientation; private int mShowDividers; private int mTotalLength; private boolean mUseLargestChild; private float mWeightSum; @RestrictTo({Scope.LIBRARY_GROUP}) @Retention(RetentionPolicy.SOURCE) public @interface DividerMode { } public static class LayoutParams extends MarginLayoutParams { public int gravity; public float weight; public LayoutParams(Context context, AttributeSet attributeSet) { super(context, attributeSet); int i = -1; this.gravity = i; TypedArray obtainStyledAttributes = context.obtainStyledAttributes(attributeSet, R.styleable.LinearLayoutCompat_Layout); this.weight = obtainStyledAttributes.getFloat(R.styleable.LinearLayoutCompat_Layout_android_layout_weight, 0.0f); this.gravity = obtainStyledAttributes.getInt(R.styleable.LinearLayoutCompat_Layout_android_layout_gravity, i); obtainStyledAttributes.recycle(); } public LayoutParams(int i, int i2) { super(i, i2); this.gravity = -1; this.weight = 0.0f; } public LayoutParams(int i, int i2, float f) { super(i, i2); this.gravity = -1; this.weight = f; } public LayoutParams(android.view.ViewGroup.LayoutParams layoutParams) { super(layoutParams); this.gravity = -1; } public LayoutParams(MarginLayoutParams marginLayoutParams) { super(marginLayoutParams); this.gravity = -1; } public LayoutParams(LayoutParams layoutParams) { super(layoutParams); this.gravity = -1; this.weight = layoutParams.weight; this.gravity = layoutParams.gravity; } } @RestrictTo({Scope.LIBRARY_GROUP}) @Retention(RetentionPolicy.SOURCE) public @interface OrientationMode { } int getChildrenSkipCount(View view, int i) { return 0; } int getLocationOffset(View view) { return 0; } int getNextLocationOffset(View view) { return 0; } int measureNullChild(int i) { return 0; } public boolean shouldDelayChildPressedState() { return false; } public LinearLayoutCompat(Context context) { this(context, null); } public LinearLayoutCompat(Context context, AttributeSet attributeSet) { this(context, attributeSet, 0); } public LinearLayoutCompat(Context context, AttributeSet attributeSet, int i) { super(context, attributeSet, i); boolean z = true; this.mBaselineAligned = z; int i2 = -1; this.mBaselineAlignedChildIndex = i2; boolean z2 = false; this.mBaselineChildTop = z2; this.mGravity = 8388659; TintTypedArray obtainStyledAttributes = TintTypedArray.obtainStyledAttributes(context, attributeSet, R.styleable.LinearLayoutCompat, i, z2); int i3 = obtainStyledAttributes.getInt(R.styleable.LinearLayoutCompat_android_orientation, i2); if (i3 >= 0) { setOrientation(i3); } i3 = obtainStyledAttributes.getInt(R.styleable.LinearLayoutCompat_android_gravity, i2); if (i3 >= 0) { setGravity(i3); } boolean z3 = obtainStyledAttributes.getBoolean(R.styleable.LinearLayoutCompat_android_baselineAligned, z); if (!z3) { setBaselineAligned(z3); } this.mWeightSum = obtainStyledAttributes.getFloat(R.styleable.LinearLayoutCompat_android_weightSum, -1.0f); this.mBaselineAlignedChildIndex = obtainStyledAttributes.getInt(R.styleable.LinearLayoutCompat_android_baselineAlignedChildIndex, i2); this.mUseLargestChild = obtainStyledAttributes.getBoolean(R.styleable.LinearLayoutCompat_measureWithLargestChild, z2); setDividerDrawable(obtainStyledAttributes.getDrawable(R.styleable.LinearLayoutCompat_divider)); this.mShowDividers = obtainStyledAttributes.getInt(R.styleable.LinearLayoutCompat_showDividers, z2); this.mDividerPadding = obtainStyledAttributes.getDimensionPixelSize(R.styleable.LinearLayoutCompat_dividerPadding, z2); obtainStyledAttributes.recycle(); } public void setShowDividers(int i) { if (i != this.mShowDividers) { requestLayout(); } this.mShowDividers = i; } public int getShowDividers() { return this.mShowDividers; } public Drawable getDividerDrawable() { return this.mDivider; } public void setDividerDrawable(Drawable drawable) { if (drawable != this.mDivider) { this.mDivider = drawable; boolean z = false; if (drawable != null) { this.mDividerWidth = drawable.getIntrinsicWidth(); this.mDividerHeight = drawable.getIntrinsicHeight(); } else { this.mDividerWidth = z; this.mDividerHeight = z; } if (drawable == null) { z = true; } setWillNotDraw(z); requestLayout(); } } public void setDividerPadding(int i) { this.mDividerPadding = i; } public int getDividerPadding() { return this.mDividerPadding; } @RestrictTo({Scope.LIBRARY_GROUP}) public int getDividerWidth() { return this.mDividerWidth; } protected void onDraw(Canvas canvas) { if (this.mDivider != null) { if (this.mOrientation == 1) { drawDividersVertical(canvas); } else { drawDividersHorizontal(canvas); } } } void drawDividersVertical(Canvas canvas) { int virtualChildCount = getVirtualChildCount(); int i = 0; while (i < virtualChildCount) { View virtualChildAt = getVirtualChildAt(i); if (!(virtualChildAt == null || virtualChildAt.getVisibility() == 8 || !hasDividerBeforeChildAt(i))) { drawHorizontalDivider(canvas, (virtualChildAt.getTop() - ((LayoutParams) virtualChildAt.getLayoutParams()).topMargin) - this.mDividerHeight); } i++; } if (hasDividerBeforeChildAt(virtualChildCount)) { View virtualChildAt2 = getVirtualChildAt(virtualChildCount - 1); if (virtualChildAt2 == null) { virtualChildCount = (getHeight() - getPaddingBottom()) - this.mDividerHeight; } else { virtualChildCount = virtualChildAt2.getBottom() + ((LayoutParams) virtualChildAt2.getLayoutParams()).bottomMargin; } drawHorizontalDivider(canvas, virtualChildCount); } } void drawDividersHorizontal(Canvas canvas) { int virtualChildCount = getVirtualChildCount(); boolean isLayoutRtl = ViewUtils.isLayoutRtl(this); int i = 0; while (i < virtualChildCount) { View virtualChildAt = getVirtualChildAt(i); if (!(virtualChildAt == null || virtualChildAt.getVisibility() == 8 || !hasDividerBeforeChildAt(i))) { int right; LayoutParams layoutParams = (LayoutParams) virtualChildAt.getLayoutParams(); if (isLayoutRtl) { right = virtualChildAt.getRight() + layoutParams.rightMargin; } else { right = (virtualChildAt.getLeft() - layoutParams.leftMargin) - this.mDividerWidth; } drawVerticalDivider(canvas, right); } i++; } if (hasDividerBeforeChildAt(virtualChildCount)) { View virtualChildAt2 = getVirtualChildAt(virtualChildCount - 1); if (virtualChildAt2 != null) { LayoutParams layoutParams2 = (LayoutParams) virtualChildAt2.getLayoutParams(); if (isLayoutRtl) { virtualChildCount = (virtualChildAt2.getLeft() - layoutParams2.leftMargin) - this.mDividerWidth; } else { virtualChildCount = virtualChildAt2.getRight() + layoutParams2.rightMargin; } } else if (isLayoutRtl) { virtualChildCount = getPaddingLeft(); } else { virtualChildCount = (getWidth() - getPaddingRight()) - this.mDividerWidth; } drawVerticalDivider(canvas, virtualChildCount); } } void drawHorizontalDivider(Canvas canvas, int i) { this.mDivider.setBounds(getPaddingLeft() + this.mDividerPadding, i, (getWidth() - getPaddingRight()) - this.mDividerPadding, this.mDividerHeight + i); this.mDivider.draw(canvas); } void drawVerticalDivider(Canvas canvas, int i) { this.mDivider.setBounds(i, getPaddingTop() + this.mDividerPadding, this.mDividerWidth + i, (getHeight() - getPaddingBottom()) - this.mDividerPadding); this.mDivider.draw(canvas); } public boolean isBaselineAligned() { return this.mBaselineAligned; } public void setBaselineAligned(boolean z) { this.mBaselineAligned = z; } public boolean isMeasureWithLargestChildEnabled() { return this.mUseLargestChild; } public void setMeasureWithLargestChildEnabled(boolean z) { this.mUseLargestChild = z; } public int getBaseline() { if (this.mBaselineAlignedChildIndex < 0) { return super.getBaseline(); } if (getChildCount() <= this.mBaselineAlignedChildIndex) { throw new RuntimeException("mBaselineAlignedChildIndex of LinearLayout set to an index that is out of bounds."); } View childAt = getChildAt(this.mBaselineAlignedChildIndex); int baseline = childAt.getBaseline(); int i = -1; if (baseline != i) { i = this.mBaselineChildTop; if (this.mOrientation == 1) { int i2 = this.mGravity & 112; if (i2 != 48) { if (i2 == 16) { i += ((((getBottom() - getTop()) - getPaddingTop()) - getPaddingBottom()) - this.mTotalLength) / 2; } else if (i2 == 80) { i = ((getBottom() - getTop()) - getPaddingBottom()) - this.mTotalLength; } } } return (i + ((LayoutParams) childAt.getLayoutParams()).topMargin) + baseline; } else if (this.mBaselineAlignedChildIndex == 0) { return i; } else { throw new RuntimeException("mBaselineAlignedChildIndex of LinearLayout points to a View that doesn't know how to get its baseline."); } } public int getBaselineAlignedChildIndex() { return this.mBaselineAlignedChildIndex; } public void setBaselineAlignedChildIndex(int i) { if (i < 0 || i >= getChildCount()) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("base aligned child index out of range (0, "); stringBuilder.append(getChildCount()); stringBuilder.append(")"); throw new IllegalArgumentException(stringBuilder.toString()); } this.mBaselineAlignedChildIndex = i; } View getVirtualChildAt(int i) { return getChildAt(i); } int getVirtualChildCount() { return getChildCount(); } public float getWeightSum() { return this.mWeightSum; } public void setWeightSum(float f) { this.mWeightSum = Math.max(0.0f, f); } protected void onMeasure(int i, int i2) { if (this.mOrientation == 1) { measureVertical(i, i2); } else { measureHorizontal(i, i2); } } protected boolean hasDividerBeforeChildAt(int i) { boolean z = false; boolean z2 = true; if (i == 0) { if ((this.mShowDividers & z2) != 0) { z = z2; } return z; } else if (i == getChildCount()) { if ((this.mShowDividers & 4) != 0) { z = z2; } return z; } else if ((this.mShowDividers & 2) == 0) { return z; } else { for (i -= z2; i >= 0; i--) { if (getChildAt(i).getVisibility() != 8) { z = z2; break; } } return z; } } void measureVertical(int i, int i2) { int i3; int i4; int i5; int i6; int i7 = i; int i8 = i2; int i9 = 0; this.mTotalLength = i9; int virtualChildCount = getVirtualChildCount(); int mode = MeasureSpec.getMode(i); int mode2 = MeasureSpec.getMode(i2); int i10 = this.mBaselineAlignedChildIndex; boolean z = this.mUseLargestChild; float f = 0.0f; int i11 = 1; int i12 = i9; int i13 = i12; int i14 = i13; int i15 = i14; int i16 = i15; int i17 = i16; float f2 = f; int i18 = i11; int i19 = Integer.MIN_VALUE; while (i14 < virtualChildCount) { Object obj; View virtualChildAt = getVirtualChildAt(i14); if (virtualChildAt == null) { r7.mTotalLength += measureNullChild(i14); i3 = i9; i4 = virtualChildCount; i5 = mode2; } else { int i20 = i12; if (virtualChildAt.getVisibility() == 8) { i14 += getChildrenSkipCount(virtualChildAt, i14); i3 = i9; i4 = virtualChildCount; i5 = mode2; i12 = i20; } else { int i21; int i22; View view; LayoutParams layoutParams; int i23; int i24; if (hasDividerBeforeChildAt(i14)) { r7.mTotalLength += r7.mDividerHeight; } LayoutParams layoutParams2 = (LayoutParams) virtualChildAt.getLayoutParams(); float f3 = f2 + layoutParams2.weight; if (mode2 == 1073741824 && layoutParams2.height == 0 && layoutParams2.weight > f) { i6 = r7.mTotalLength; i21 = i19; r7.mTotalLength = Math.max(i6, (layoutParams2.topMargin + i6) + layoutParams2.bottomMargin); i22 = i13; view = virtualChildAt; layoutParams = layoutParams2; i23 = i9; i4 = virtualChildCount; i5 = mode2; i15 = i11; i24 = i17; mode2 = i20; obj = Integer.MIN_VALUE; virtualChildCount = i14; } else { i21 = i19; if (layoutParams2.height != 0 || layoutParams2.weight <= f) { i19 = Integer.MIN_VALUE; } else { layoutParams2.height = -2; i19 = 0; } i5 = mode2; mode2 = i20; int i25 = i19; int i26 = i21; i4 = virtualChildCount; virtualChildCount = i13; i13 = i7; view = virtualChildAt; i22 = virtualChildCount; i24 = i17; Object obj2 = 1073741824; virtualChildCount = i14; i14 = i8; layoutParams = layoutParams2; i23 = i9; i9 = Integer.MIN_VALUE; measureChildBeforeLayout(virtualChildAt, i14, i13, 0, i14, f3 == f ? r7.mTotalLength : 0); i6 = i25; if (i6 != i9) { layoutParams.height = i6; } i6 = view.getMeasuredHeight(); i12 = r7.mTotalLength; r7.mTotalLength = Math.max(i12, (((i12 + i6) + layoutParams.topMargin) + layoutParams.bottomMargin) + getNextLocationOffset(view)); i21 = z ? Math.max(i6, i26) : i26; } if (i10 >= 0 && i10 == virtualChildCount + 1) { r7.mBaselineChildTop = r7.mTotalLength; } if (virtualChildCount >= i10 || layoutParams.weight <= f) { if (mode != 1073741824) { i12 = -1; if (layoutParams.width == i12) { i6 = i11; i16 = i6; i19 = layoutParams.leftMargin + layoutParams.rightMargin; i13 = view.getMeasuredWidth() + i19; i3 = Math.max(mode2, i13); i14 = View.combineMeasuredStates(i23, view.getMeasuredState()); i12 = (i18 == 0 && layoutParams.width == i12) ? i11 : 0; if (layoutParams.weight <= f) { if (i6 == 0) { i19 = i13; } i13 = Math.max(i22, i19); } else { i8 = i22; if (i6 != 0) { i13 = i19; } i17 = Math.max(i24, i13); i13 = i8; i24 = i17; } i18 = i12; i12 = i3; i3 = i14; i19 = i21; i17 = i24; i14 = getChildrenSkipCount(view, virtualChildCount) + virtualChildCount; f2 = f3; i14++; i9 = i3; mode2 = i5; virtualChildCount = i4; i7 = i; i8 = i2; } } else { i12 = -1; } i6 = 0; i19 = layoutParams.leftMargin + layoutParams.rightMargin; i13 = view.getMeasuredWidth() + i19; i3 = Math.max(mode2, i13); i14 = View.combineMeasuredStates(i23, view.getMeasuredState()); if (i18 == 0) { } if (layoutParams.weight <= f) { i8 = i22; if (i6 != 0) { i13 = i19; } i17 = Math.max(i24, i13); i13 = i8; i24 = i17; } else { if (i6 == 0) { i19 = i13; } i13 = Math.max(i22, i19); } i18 = i12; i12 = i3; i3 = i14; i19 = i21; i17 = i24; i14 = getChildrenSkipCount(view, virtualChildCount) + virtualChildCount; f2 = f3; i14++; i9 = i3; mode2 = i5; virtualChildCount = i4; i7 = i; i8 = i2; } else { throw new RuntimeException("A child of LinearLayout with index less than mBaselineAlignedChildIndex has weight > 0, which won't work. Either remove the weight, or don't set mBaselineAlignedChildIndex."); } } } obj = Integer.MIN_VALUE; i14++; i9 = i3; mode2 = i5; virtualChildCount = i4; i7 = i; i8 = i2; } int i27 = i19; i8 = i13; i3 = i9; i4 = virtualChildCount; i5 = mode2; i19 = i17; i9 = Integer.MIN_VALUE; mode2 = i12; Object obj3 = -1; if (r7.mTotalLength > 0) { i13 = i4; if (hasDividerBeforeChildAt(i13)) { r7.mTotalLength += r7.mDividerHeight; } } else { i13 = i4; } if (z) { i14 = i5; if (i14 == i9 || i14 == 0) { r7.mTotalLength = 0; i7 = 0; while (i7 < i13) { View virtualChildAt2 = getVirtualChildAt(i7); if (virtualChildAt2 == null) { r7.mTotalLength += measureNullChild(i7); } else if (virtualChildAt2.getVisibility() == 8) { i7 += getChildrenSkipCount(virtualChildAt2, i7); } else { LayoutParams layoutParams3 = (LayoutParams) virtualChildAt2.getLayoutParams(); i10 = r7.mTotalLength; r7.mTotalLength = Math.max(i10, (((i10 + i27) + layoutParams3.topMargin) + layoutParams3.bottomMargin) + getNextLocationOffset(virtualChildAt2)); } i7++; obj3 = -1; } } } else { i14 = i5; } r7.mTotalLength += getPaddingTop() + getPaddingBottom(); i7 = i2; i12 = View.resolveSizeAndState(Math.max(r7.mTotalLength, getSuggestedMinimumHeight()), i7, 0); i9 = (16777215 & i12) - r7.mTotalLength; if (i15 != 0 || (i9 != 0 && f2 > f)) { if (r7.mWeightSum > f) { f2 = r7.mWeightSum; } i27 = 0; r7.mTotalLength = i27; float f4 = f2; i6 = i27; int i28 = i9; i9 = i3; i3 = i28; while (i6 < i13) { float f5; View virtualChildAt3 = getVirtualChildAt(i6); if (virtualChildAt3.getVisibility() == 8) { f5 = f4; i8 = i; } else { int i29; int i30; LayoutParams layoutParams4 = (LayoutParams) virtualChildAt3.getLayoutParams(); float f6 = layoutParams4.weight; if (f6 > f) { i29 = (int) ((((float) i3) * f6) / f4); i30 = i3 - i29; f5 = f4 - f6; i3 = getChildMeasureSpec(i, ((getPaddingLeft() + getPaddingRight()) + layoutParams4.leftMargin) + layoutParams4.rightMargin, layoutParams4.width); if (layoutParams4.height == 0) { i27 = 1073741824; if (i14 == i27) { if (i29 <= 0) { i29 = 0; } virtualChildAt3.measure(i3, MeasureSpec.makeMeasureSpec(i29, i27)); i9 = View.combineMeasuredStates(i9, virtualChildAt3.getMeasuredState() & -256); } } else { i27 = 1073741824; } i29 = virtualChildAt3.getMeasuredHeight() + i29; if (i29 < 0) { i29 = 0; } virtualChildAt3.measure(i3, MeasureSpec.makeMeasureSpec(i29, i27)); i9 = View.combineMeasuredStates(i9, virtualChildAt3.getMeasuredState() & -256); } else { f6 = f4; i8 = i; i30 = i3; f5 = f6; } i3 = layoutParams4.leftMargin + layoutParams4.rightMargin; i27 = virtualChildAt3.getMeasuredWidth() + i3; mode2 = Math.max(mode2, i27); int i31; if (mode != 1073741824) { i31 = i3; i3 = -1; if (layoutParams4.width == i3) { i29 = i11; if (i29 != 0) { i27 = i31; } i19 = Math.max(i19, i27); i27 = (i18 == 0 && layoutParams4.width == i3) ? i11 : 0; i29 = r7.mTotalLength; r7.mTotalLength = Math.max(i29, (((i29 + virtualChildAt3.getMeasuredHeight()) + layoutParams4.topMargin) + layoutParams4.bottomMargin) + getNextLocationOffset(virtualChildAt3)); i18 = i27; i3 = i30; } } else { i31 = i3; i3 = -1; } i29 = 0; if (i29 != 0) { i27 = i31; } i19 = Math.max(i19, i27); if (i18 == 0) { } i29 = r7.mTotalLength; r7.mTotalLength = Math.max(i29, (((i29 + virtualChildAt3.getMeasuredHeight()) + layoutParams4.topMargin) + layoutParams4.bottomMargin) + getNextLocationOffset(virtualChildAt3)); i18 = i27; i3 = i30; } i6++; f4 = f5; Object obj4 = null; } i8 = i; r7.mTotalLength += getPaddingTop() + getPaddingBottom(); i6 = i19; i3 = i9; } else { i6 = Math.max(i19, i8); if (z && i14 != 1073741824) { for (i19 = 0; i19 < i13; i19++) { View virtualChildAt4 = getVirtualChildAt(i19); if (!(virtualChildAt4 == null || virtualChildAt4.getVisibility() == 8 || ((LayoutParams) virtualChildAt4.getLayoutParams()).weight <= f)) { i9 = 1073741824; virtualChildAt4.measure(MeasureSpec.makeMeasureSpec(virtualChildAt4.getMeasuredWidth(), i9), MeasureSpec.makeMeasureSpec(i27, i9)); } } } i8 = i; } if (i18 == 0 && mode != 1073741824) { mode2 = i6; } setMeasuredDimension(View.resolveSizeAndState(Math.max(mode2 + (getPaddingLeft() + getPaddingRight()), getSuggestedMinimumWidth()), i8, i3), i12); if (i16 != 0) { forceUniformWidth(i13, i7); } } private void forceUniformWidth(int i, int i2) { int makeMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredWidth(), 1073741824); for (int i3 = 0; i3 < i; i3++) { View virtualChildAt = getVirtualChildAt(i3); if (virtualChildAt.getVisibility() != 8) { LayoutParams layoutParams = (LayoutParams) virtualChildAt.getLayoutParams(); if (layoutParams.width == -1) { int i4 = layoutParams.height; layoutParams.height = virtualChildAt.getMeasuredHeight(); measureChildWithMargins(virtualChildAt, makeMeasureSpec, 0, i2, 0); layoutParams.height = i4; } } } } void measureHorizontal(int i, int i2) { int[] iArr; int i3; boolean z; boolean z2; int i4; Object obj; int measuredHeight; int combineMeasuredStates; int i5; View virtualChildAt; LayoutParams layoutParams; int i6; int i7 = i; int i8 = i2; int i9 = 0; this.mTotalLength = i9; int virtualChildCount = getVirtualChildCount(); int mode = MeasureSpec.getMode(i); int mode2 = MeasureSpec.getMode(i2); int i10 = 4; if (this.mMaxAscent == null || r7.mMaxDescent == null) { r7.mMaxAscent = new int[i10]; r7.mMaxDescent = new int[i10]; } int[] iArr2 = r7.mMaxAscent; int[] iArr3 = r7.mMaxDescent; int i11 = 3; int i12 = -1; iArr2[i11] = i12; int i13 = 2; iArr2[i13] = i12; int i14 = 1; iArr2[i14] = i12; iArr2[i9] = i12; iArr3[i11] = i12; iArr3[i13] = i12; iArr3[i14] = i12; iArr3[i9] = i12; boolean z3 = r7.mBaselineAligned; boolean z4 = r7.mUseLargestChild; int i15 = 1073741824; int i16 = mode == i15 ? i14 : i9; float f = 0.0f; int i17 = i9; int i18 = i17; int i19 = i18; int i20 = i19; int i21 = i20; int i22 = i21; int i23 = i22; int i24 = i14; float f2 = f; i10 = Integer.MIN_VALUE; while (true) { iArr = iArr3; i3 = 8; if (i17 >= virtualChildCount) { break; } Object obj2; Object obj3; View virtualChildAt2 = getVirtualChildAt(i17); if (virtualChildAt2 == null) { r7.mTotalLength += measureNullChild(i17); } else if (virtualChildAt2.getVisibility() == i3) { i17 += getChildrenSkipCount(virtualChildAt2, i17); } else { int i25; LayoutParams layoutParams2; View view; if (hasDividerBeforeChildAt(i17)) { r7.mTotalLength += r7.mDividerWidth; } LayoutParams layoutParams3 = (LayoutParams) virtualChildAt2.getLayoutParams(); f2 += layoutParams3.weight; if (mode == i15 && layoutParams3.width == 0 && layoutParams3.weight > f) { if (i16 != 0) { r7.mTotalLength += layoutParams3.leftMargin + layoutParams3.rightMargin; } else { i3 = r7.mTotalLength; r7.mTotalLength = Math.max(i3, (layoutParams3.leftMargin + i3) + layoutParams3.rightMargin); } if (z3) { i3 = 0; i15 = MeasureSpec.makeMeasureSpec(i3, i3); virtualChildAt2.measure(i15, i15); i25 = i17; z = z4; z2 = z3; layoutParams2 = layoutParams3; i4 = mode; obj = -2; view = virtualChildAt2; } else { i25 = i17; z = z4; z2 = z3; layoutParams2 = layoutParams3; i4 = mode; i19 = i14; i17 = 1073741824; obj = -2; view = virtualChildAt2; if (mode2 == i17 && layoutParams2.height == -1) { i3 = i14; i23 = i3; } else { i3 = 0; } i15 = layoutParams2.topMargin + layoutParams2.bottomMargin; measuredHeight = view.getMeasuredHeight() + i15; combineMeasuredStates = View.combineMeasuredStates(i22, view.getMeasuredState()); if (z2) { i12 = view.getBaseline(); if (i12 != -1) { i5 = ((((layoutParams2.gravity < 0 ? r7.mGravity : layoutParams2.gravity) & 112) >> 4) & -2) >> 1; iArr2[i5] = Math.max(iArr2[i5], i12); iArr[i5] = Math.max(iArr[i5], measuredHeight - i12); } } i12 = Math.max(i18, measuredHeight); i5 = (i24 == 0 && layoutParams2.height == -1) ? i14 : 0; if (layoutParams2.weight <= f) { if (i3 == 0) { i15 = measuredHeight; } i7 = Math.max(i21, i15); } else { i7 = i21; if (i3 != 0) { measuredHeight = i15; } i20 = Math.max(i20, measuredHeight); } i9 = i25; i3 = getChildrenSkipCount(view, i9) + i9; i22 = combineMeasuredStates; i18 = i12; i24 = i5; i21 = i7; i15 = i17; i17 = i3 + 1; iArr3 = iArr; z4 = z; z3 = z2; mode = i4; obj2 = -1; i7 = i; obj3 = null; } } else { if (layoutParams3.width != 0 || layoutParams3.weight <= f) { obj3 = -2; i15 = Integer.MIN_VALUE; } else { layoutParams3.width = -2; i15 = 0; } i25 = i17; obj3 = Integer.MIN_VALUE; i9 = i15; z = z4; z2 = z3; layoutParams2 = layoutParams3; i4 = mode; Object obj4 = -1; view = virtualChildAt2; obj = -2; measureChildBeforeLayout(virtualChildAt2, i25, i7, f2 == f ? r7.mTotalLength : 0, i8, 0); if (i9 != Integer.MIN_VALUE) { layoutParams2.width = i9; } i17 = view.getMeasuredWidth(); if (i16 != 0) { r7.mTotalLength += ((layoutParams2.leftMargin + i17) + layoutParams2.rightMargin) + getNextLocationOffset(view); } else { i3 = r7.mTotalLength; r7.mTotalLength = Math.max(i3, (((i3 + i17) + layoutParams2.leftMargin) + layoutParams2.rightMargin) + getNextLocationOffset(view)); } if (z) { i10 = Math.max(i17, i10); } } i17 = 1073741824; if (mode2 == i17) { } i3 = 0; i15 = layoutParams2.topMargin + layoutParams2.bottomMargin; measuredHeight = view.getMeasuredHeight() + i15; combineMeasuredStates = View.combineMeasuredStates(i22, view.getMeasuredState()); if (z2) { i12 = view.getBaseline(); if (i12 != -1) { i5 = ((((layoutParams2.gravity < 0 ? r7.mGravity : layoutParams2.gravity) & 112) >> 4) & -2) >> 1; iArr2[i5] = Math.max(iArr2[i5], i12); iArr[i5] = Math.max(iArr[i5], measuredHeight - i12); } } i12 = Math.max(i18, measuredHeight); if (i24 == 0) { } if (layoutParams2.weight <= f) { i7 = i21; if (i3 != 0) { measuredHeight = i15; } i20 = Math.max(i20, measuredHeight); } else { if (i3 == 0) { i15 = measuredHeight; } i7 = Math.max(i21, i15); } i9 = i25; i3 = getChildrenSkipCount(view, i9) + i9; i22 = combineMeasuredStates; i18 = i12; i24 = i5; i21 = i7; i15 = i17; i17 = i3 + 1; iArr3 = iArr; z4 = z; z3 = z2; mode = i4; obj2 = -1; i7 = i; obj3 = null; } i3 = i17; i17 = i15; z = z4; z2 = z3; i4 = mode; i15 = i17; i17 = i3 + 1; iArr3 = iArr; z4 = z; z3 = z2; mode = i4; obj2 = -1; i7 = i; obj3 = null; } i17 = i15; z = z4; z2 = z3; i4 = mode; i12 = i18; i15 = i20; i7 = i21; i9 = i22; obj = -2; if (r7.mTotalLength > 0 && hasDividerBeforeChildAt(virtualChildCount)) { r7.mTotalLength += r7.mDividerWidth; } combineMeasuredStates = -1; if (!(iArr2[i14] == combineMeasuredStates && iArr2[0] == combineMeasuredStates && iArr2[i13] == combineMeasuredStates && iArr2[i11] == combineMeasuredStates)) { combineMeasuredStates = 0; i12 = Math.max(i12, Math.max(iArr2[i11], Math.max(iArr2[combineMeasuredStates], Math.max(iArr2[i14], iArr2[i13]))) + Math.max(iArr[i11], Math.max(iArr[combineMeasuredStates], Math.max(iArr[i14], iArr[i13])))); } if (z) { i17 = i4; if (i17 == Integer.MIN_VALUE || i17 == 0) { r7.mTotalLength = 0; measuredHeight = 0; while (measuredHeight < virtualChildCount) { int i26; virtualChildAt = getVirtualChildAt(measuredHeight); if (virtualChildAt == null) { r7.mTotalLength += measureNullChild(measuredHeight); } else if (virtualChildAt.getVisibility() == i3) { measuredHeight += getChildrenSkipCount(virtualChildAt, measuredHeight); } else { layoutParams = (LayoutParams) virtualChildAt.getLayoutParams(); if (i16 != 0) { r7.mTotalLength += ((layoutParams.leftMargin + i10) + layoutParams.rightMargin) + getNextLocationOffset(virtualChildAt); } else { i3 = r7.mTotalLength; i26 = measuredHeight; r7.mTotalLength = Math.max(i3, (((i3 + i10) + layoutParams.leftMargin) + layoutParams.rightMargin) + getNextLocationOffset(virtualChildAt)); measuredHeight = i26 + 1; i3 = 8; } } i26 = measuredHeight; measuredHeight = i26 + 1; i3 = 8; } } } else { i17 = i4; } r7.mTotalLength += getPaddingLeft() + getPaddingRight(); i3 = View.resolveSizeAndState(Math.max(r7.mTotalLength, getSuggestedMinimumWidth()), i, 0); combineMeasuredStates = (16777215 & i3) - r7.mTotalLength; if (i19 != 0 || (combineMeasuredStates != 0 && f2 > f)) { float f3 = r7.mWeightSum > f ? r7.mWeightSum : f2; i7 = -1; iArr2[i11] = i7; iArr2[i13] = i7; iArr2[i14] = i7; mode = 0; iArr2[mode] = i7; iArr[i11] = i7; iArr[i13] = i7; iArr[i14] = i7; iArr[mode] = i7; r7.mTotalLength = mode; mode = i15; i15 = 0; i7 = -1; while (i15 < virtualChildCount) { View virtualChildAt3 = getVirtualChildAt(i15); Object obj5; if (virtualChildAt3 == null || virtualChildAt3.getVisibility() == 8) { i6 = virtualChildCount; obj5 = 4; } else { int i27; layoutParams = (LayoutParams) virtualChildAt3.getLayoutParams(); float f4 = layoutParams.weight; if (f4 > f) { i6 = virtualChildCount; virtualChildCount = (int) ((((float) combineMeasuredStates) * f4) / f3); f3 -= f4; i27 = combineMeasuredStates - virtualChildCount; measuredHeight = getChildMeasureSpec(i8, ((getPaddingTop() + getPaddingBottom()) + layoutParams.topMargin) + layoutParams.bottomMargin, layoutParams.height); if (layoutParams.width == 0) { combineMeasuredStates = 1073741824; if (i17 == combineMeasuredStates) { if (virtualChildCount <= 0) { virtualChildCount = 0; } virtualChildAt3.measure(MeasureSpec.makeMeasureSpec(virtualChildCount, combineMeasuredStates), measuredHeight); i9 = View.combineMeasuredStates(i9, virtualChildAt3.getMeasuredState() & -16777216); } } else { combineMeasuredStates = 1073741824; } virtualChildCount = virtualChildAt3.getMeasuredWidth() + virtualChildCount; if (virtualChildCount < 0) { virtualChildCount = 0; } virtualChildAt3.measure(MeasureSpec.makeMeasureSpec(virtualChildCount, combineMeasuredStates), measuredHeight); i9 = View.combineMeasuredStates(i9, virtualChildAt3.getMeasuredState() & -16777216); } else { i6 = virtualChildCount; i27 = combineMeasuredStates; } if (i16 != 0) { r7.mTotalLength += ((virtualChildAt3.getMeasuredWidth() + layoutParams.leftMargin) + layoutParams.rightMargin) + getNextLocationOffset(virtualChildAt3); } else { measuredHeight = r7.mTotalLength; r7.mTotalLength = Math.max(measuredHeight, (((virtualChildAt3.getMeasuredWidth() + measuredHeight) + layoutParams.leftMargin) + layoutParams.rightMargin) + getNextLocationOffset(virtualChildAt3)); } measuredHeight = (mode2 == 1073741824 || layoutParams.height != -1) ? 0 : i14; combineMeasuredStates = layoutParams.topMargin + layoutParams.bottomMargin; virtualChildCount = virtualChildAt3.getMeasuredHeight() + combineMeasuredStates; i7 = Math.max(i7, virtualChildCount); if (measuredHeight == 0) { combineMeasuredStates = virtualChildCount; } measuredHeight = Math.max(mode, combineMeasuredStates); if (i24 != 0) { mode = -1; if (layoutParams.height == mode) { combineMeasuredStates = i14; if (z2) { i10 = virtualChildAt3.getBaseline(); if (i10 != mode) { obj5 = 4; i5 = ((((layoutParams.gravity < 0 ? r7.mGravity : layoutParams.gravity) & 112) >> 4) & -2) >> 1; iArr2[i5] = Math.max(iArr2[i5], i10); iArr[i5] = Math.max(iArr[i5], virtualChildCount - i10); mode = measuredHeight; i24 = combineMeasuredStates; combineMeasuredStates = i27; } } obj5 = 4; mode = measuredHeight; i24 = combineMeasuredStates; combineMeasuredStates = i27; } } else { mode = -1; } combineMeasuredStates = 0; if (z2) { i10 = virtualChildAt3.getBaseline(); if (i10 != mode) { obj5 = 4; i5 = ((((layoutParams.gravity < 0 ? r7.mGravity : layoutParams.gravity) & 112) >> 4) & -2) >> 1; iArr2[i5] = Math.max(iArr2[i5], i10); iArr[i5] = Math.max(iArr[i5], virtualChildCount - i10); mode = measuredHeight; i24 = combineMeasuredStates; combineMeasuredStates = i27; } } obj5 = 4; mode = measuredHeight; i24 = combineMeasuredStates; combineMeasuredStates = i27; } i15++; virtualChildCount = i6; measuredHeight = i; } i6 = virtualChildCount; r7.mTotalLength += getPaddingLeft() + getPaddingRight(); i15 = -1; if (iArr2[i14] == i15 && iArr2[0] == i15 && iArr2[i13] == i15 && iArr2[i11] == i15) { i12 = i7; } else { i15 = 0; i12 = Math.max(i7, Math.max(iArr2[i11], Math.max(iArr2[i15], Math.max(iArr2[i14], iArr2[i13]))) + Math.max(iArr[i11], Math.max(iArr[i15], Math.max(iArr[i14], iArr[i13])))); } } else { i15 = Math.max(i15, i7); if (z && i17 != 1073741824) { for (i17 = 0; i17 < virtualChildCount; i17++) { virtualChildAt = getVirtualChildAt(i17); if (!(virtualChildAt == null || virtualChildAt.getVisibility() == 8 || ((LayoutParams) virtualChildAt.getLayoutParams()).weight <= f)) { i7 = 1073741824; virtualChildAt.measure(MeasureSpec.makeMeasureSpec(i10, i7), MeasureSpec.makeMeasureSpec(virtualChildAt.getMeasuredHeight(), i7)); } } } mode = i15; i6 = virtualChildCount; } if (i24 != 0 || mode2 == 1073741824) { mode = i12; } setMeasuredDimension(i3 | (-16777216 & i9), View.resolveSizeAndState(Math.max(mode + (getPaddingTop() + getPaddingBottom()), getSuggestedMinimumHeight()), i8, i9 << 16)); if (i23 != 0) { forceUniformHeight(i6, i); } } private void forceUniformHeight(int i, int i2) { int makeMeasureSpec = MeasureSpec.makeMeasureSpec(getMeasuredHeight(), 1073741824); for (int i3 = 0; i3 < i; i3++) { View virtualChildAt = getVirtualChildAt(i3); if (virtualChildAt.getVisibility() != 8) { LayoutParams layoutParams = (LayoutParams) virtualChildAt.getLayoutParams(); if (layoutParams.height == -1) { int i4 = layoutParams.width; layoutParams.width = virtualChildAt.getMeasuredWidth(); measureChildWithMargins(virtualChildAt, i2, 0, makeMeasureSpec, 0); layoutParams.width = i4; } } } } void measureChildBeforeLayout(View view, int i, int i2, int i3, int i4, int i5) { measureChildWithMargins(view, i2, i3, i4, i5); } protected void onLayout(boolean z, int i, int i2, int i3, int i4) { if (this.mOrientation == 1) { layoutVertical(i, i2, i3, i4); } else { layoutHorizontal(i, i2, i3, i4); } } void layoutVertical(int i, int i2, int i3, int i4) { int paddingTop; int paddingLeft = getPaddingLeft(); int i5 = i3 - i; int paddingRight = i5 - getPaddingRight(); int paddingRight2 = (i5 - paddingLeft) - getPaddingRight(); int virtualChildCount = getVirtualChildCount(); i5 = this.mGravity & 112; int i6 = this.mGravity & 8388615; if (i5 == 16) { paddingTop = (((i4 - i2) - r6.mTotalLength) / 2) + getPaddingTop(); } else if (i5 != 80) { paddingTop = getPaddingTop(); } else { paddingTop = ((getPaddingTop() + i4) - i2) - r6.mTotalLength; } int i7 = 0; while (i7 < virtualChildCount) { int i8; View virtualChildAt = getVirtualChildAt(i7); int i9 = 1; if (virtualChildAt == null) { paddingTop += measureNullChild(i7); } else if (virtualChildAt.getVisibility() != 8) { int measuredWidth = virtualChildAt.getMeasuredWidth(); int measuredHeight = virtualChildAt.getMeasuredHeight(); LayoutParams layoutParams = (LayoutParams) virtualChildAt.getLayoutParams(); i8 = layoutParams.gravity; if (i8 < 0) { i8 = i6; } i8 = GravityCompat.getAbsoluteGravity(i8, ViewCompat.getLayoutDirection(this)) & 7; if (i8 == i9) { i8 = ((((paddingRight2 - measuredWidth) / 2) + paddingLeft) + layoutParams.leftMargin) - layoutParams.rightMargin; } else if (i8 != 5) { i8 = layoutParams.leftMargin + paddingLeft; } else { i8 = (paddingRight - measuredWidth) - layoutParams.rightMargin; } i5 = i8; if (hasDividerBeforeChildAt(i7)) { paddingTop += r6.mDividerHeight; } int i10 = paddingTop + layoutParams.topMargin; LayoutParams layoutParams2 = layoutParams; setChildFrame(virtualChildAt, i5, i10 + getLocationOffset(virtualChildAt), measuredWidth, measuredHeight); i7 += getChildrenSkipCount(virtualChildAt, i7); paddingTop = i10 + ((measuredHeight + layoutParams2.bottomMargin) + getNextLocationOffset(virtualChildAt)); i8 = 1; i7 += i8; } i8 = i9; i7 += i8; } } void layoutHorizontal(int i, int i2, int i3, int i4) { int paddingLeft; int i5; int i6; boolean isLayoutRtl = ViewUtils.isLayoutRtl(this); int paddingTop = getPaddingTop(); int i7 = i4 - i2; int paddingBottom = i7 - getPaddingBottom(); int paddingBottom2 = (i7 - paddingTop) - getPaddingBottom(); int virtualChildCount = getVirtualChildCount(); i7 = this.mGravity & 8388615; int i8 = this.mGravity & 112; boolean z = this.mBaselineAligned; int[] iArr = this.mMaxAscent; int[] iArr2 = this.mMaxDescent; i7 = GravityCompat.getAbsoluteGravity(i7, ViewCompat.getLayoutDirection(this)); int i9 = 2; int i10 = 1; if (i7 == i10) { paddingLeft = (((i3 - i) - r6.mTotalLength) / i9) + getPaddingLeft(); } else if (i7 != 5) { paddingLeft = getPaddingLeft(); } else { paddingLeft = ((getPaddingLeft() + i3) - i) - r6.mTotalLength; } int i11 = 0; if (isLayoutRtl) { i5 = virtualChildCount - 1; i6 = -1; } else { i5 = i11; i6 = i10; } i7 = i11; while (i7 < virtualChildCount) { int i12; int i13; int i14; int i15; Object obj; Object obj2; int i16 = i5 + (i6 * i7); View virtualChildAt = getVirtualChildAt(i16); int i17; if (virtualChildAt == null) { paddingLeft += measureNullChild(i16); i12 = i10; i13 = paddingTop; i14 = virtualChildCount; i15 = i8; } else if (virtualChildAt.getVisibility() != 8) { int i18; View view; LayoutParams layoutParams; View view2; i9 = virtualChildAt.getMeasuredWidth(); i10 = virtualChildAt.getMeasuredHeight(); LayoutParams layoutParams2 = (LayoutParams) virtualChildAt.getLayoutParams(); if (z) { i18 = i7; i14 = virtualChildCount; if (layoutParams2.height != -1) { i7 = virtualChildAt.getBaseline(); virtualChildCount = layoutParams2.gravity; if (virtualChildCount < 0) { virtualChildCount = i8; } virtualChildCount &= 112; i15 = i8; Object obj3; if (virtualChildCount != 16) { obj3 = -1; i12 = 1; i7 = ((((paddingBottom2 - i10) / 2) + paddingTop) + layoutParams2.topMargin) - layoutParams2.bottomMargin; } else if (virtualChildCount != 48) { if (virtualChildCount != 80) { i7 = paddingTop; obj3 = -1; } else { virtualChildCount = (paddingBottom - i10) - layoutParams2.bottomMargin; if (i7 != -1) { virtualChildCount -= iArr2[2] - (virtualChildAt.getMeasuredHeight() - i7); } i7 = virtualChildCount; } i12 = 1; } else { virtualChildCount = layoutParams2.topMargin + paddingTop; if (i7 != -1) { i12 = 1; virtualChildCount += iArr[i12] - i7; } else { i12 = 1; } i7 = virtualChildCount; } if (hasDividerBeforeChildAt(i16)) { paddingLeft += r6.mDividerWidth; } virtualChildCount = layoutParams2.leftMargin + paddingLeft; view = virtualChildAt; i8 = i16; i16 = virtualChildCount + getLocationOffset(virtualChildAt); i17 = i18; i13 = paddingTop; obj = -1; layoutParams = layoutParams2; setChildFrame(virtualChildAt, i16, i7, i9, i10); view2 = view; i7 = i17 + getChildrenSkipCount(view2, i8); paddingLeft = virtualChildCount + ((i9 + layoutParams.rightMargin) + getNextLocationOffset(view2)); i7++; i10 = i12; virtualChildCount = i14; i8 = i15; paddingTop = i13; obj2 = 2; } } else { i18 = i7; i14 = virtualChildCount; } i7 = -1; virtualChildCount = layoutParams2.gravity; if (virtualChildCount < 0) { virtualChildCount = i8; } virtualChildCount &= 112; i15 = i8; if (virtualChildCount != 16) { obj3 = -1; i12 = 1; i7 = ((((paddingBottom2 - i10) / 2) + paddingTop) + layoutParams2.topMargin) - layoutParams2.bottomMargin; } else if (virtualChildCount != 48) { if (virtualChildCount != 80) { i7 = paddingTop; obj3 = -1; } else { virtualChildCount = (paddingBottom - i10) - layoutParams2.bottomMargin; if (i7 != -1) { virtualChildCount -= iArr2[2] - (virtualChildAt.getMeasuredHeight() - i7); } i7 = virtualChildCount; } i12 = 1; } else { virtualChildCount = layoutParams2.topMargin + paddingTop; if (i7 != -1) { i12 = 1; virtualChildCount += iArr[i12] - i7; } else { i12 = 1; } i7 = virtualChildCount; } if (hasDividerBeforeChildAt(i16)) { paddingLeft += r6.mDividerWidth; } virtualChildCount = layoutParams2.leftMargin + paddingLeft; view = virtualChildAt; i8 = i16; i16 = virtualChildCount + getLocationOffset(virtualChildAt); i17 = i18; i13 = paddingTop; obj = -1; layoutParams = layoutParams2; setChildFrame(virtualChildAt, i16, i7, i9, i10); view2 = view; i7 = i17 + getChildrenSkipCount(view2, i8); paddingLeft = virtualChildCount + ((i9 + layoutParams.rightMargin) + getNextLocationOffset(view2)); i7++; i10 = i12; virtualChildCount = i14; i8 = i15; paddingTop = i13; obj2 = 2; } else { i17 = i7; i13 = paddingTop; i14 = virtualChildCount; i15 = i8; i12 = 1; } obj = -1; i7++; i10 = i12; virtualChildCount = i14; i8 = i15; paddingTop = i13; obj2 = 2; } } private void setChildFrame(View view, int i, int i2, int i3, int i4) { view.layout(i, i2, i3 + i, i4 + i2); } public void setOrientation(int i) { if (this.mOrientation != i) { this.mOrientation = i; requestLayout(); } } public int getOrientation() { return this.mOrientation; } public void setGravity(int i) { if (this.mGravity != i) { if ((8388615 & i) == 0) { i |= 8388611; } if ((i & 112) == 0) { i |= 48; } this.mGravity = i; requestLayout(); } } public int getGravity() { return this.mGravity; } public void setHorizontalGravity(int i) { int i2 = 8388615; i &= i2; if ((i2 & this.mGravity) != i) { this.mGravity = i | (this.mGravity & -8388616); requestLayout(); } } public void setVerticalGravity(int i) { i &= 112; if ((this.mGravity & 112) != i) { this.mGravity = i | (this.mGravity & -113); requestLayout(); } } public LayoutParams generateLayoutParams(AttributeSet attributeSet) { return new LayoutParams(getContext(), attributeSet); } protected LayoutParams generateDefaultLayoutParams() { int i = -2; if (this.mOrientation == 0) { return new LayoutParams(i, i); } return this.mOrientation == 1 ? new LayoutParams(-1, i) : null; } protected LayoutParams generateLayoutParams(android.view.ViewGroup.LayoutParams layoutParams) { return new LayoutParams(layoutParams); } protected boolean checkLayoutParams(android.view.ViewGroup.LayoutParams layoutParams) { return layoutParams instanceof LayoutParams; } public void onInitializeAccessibilityEvent(AccessibilityEvent accessibilityEvent) { if (VERSION.SDK_INT >= 14) { super.onInitializeAccessibilityEvent(accessibilityEvent); accessibilityEvent.setClassName(LinearLayoutCompat.class.getName()); } } public void onInitializeAccessibilityNodeInfo(AccessibilityNodeInfo accessibilityNodeInfo) { if (VERSION.SDK_INT >= 14) { super.onInitializeAccessibilityNodeInfo(accessibilityNodeInfo); accessibilityNodeInfo.setClassName(LinearLayoutCompat.class.getName()); } } }
package info.mrconst.qlient.data; import android.content.Context; import android.widget.Filter; import android.widget.Filterable; import java.util.ArrayList; import java.util.Collection; import info.mrconst.qlient.notifications.NotificationCenter; public abstract class FilterableFeed<T> extends BaseFeed<T> implements Filterable { public static final String NOTIFICATION_FILTER_STARTED = "filter_start"; public static final String NOTIFICATION_FILTER_FINISHED = "filter_finish"; private static final String STATE_FILTER_CONSTRAINT = "filter_constraint"; protected FeedFilter mFilter; private CharSequence mFilterConstraint = ""; protected ArrayList<T> mFilteredObjects = new ArrayList<>(); public FilterableFeed(Context ctx, Class<T> tClass) { super(ctx, tClass); } public CharSequence getFilterConstraint() { return mFilterConstraint; } public void startFilter(CharSequence text) { if (mFilter == null) mFilter = new FeedFilter(); mFilterConstraint = text; mFilter.filter(text.toString().toLowerCase()); NotificationCenter.sendMessage(NOTIFICATION_FILTER_STARTED, null, this, true); } @Override public int size() { return mFilteredObjects.size(); } @Override public T get(int i) { return mFilteredObjects.get(i); } @Override public Filter getFilter() { return mFilter; } private class FeedFilter extends Filter { @Override protected FilterResults performFiltering(CharSequence constraint) { FilterResults result = new FilterResults(); if (constraint != null && constraint.toString().length() > 0) { ArrayList<T> filteredItems = new ArrayList<>(); for (T item: mObjects) { if (itemConformsToFilterCondition(item, constraint)) filteredItems.add(item); } result.count = filteredItems.size(); result.values = filteredItems; } else { synchronized (this) { result.values = mObjects; result.count = mObjects.size(); } } return result; } @SuppressWarnings("unchecked") @Override protected void publishResults(CharSequence constraint, FilterResults results) { mFilteredObjects.clear(); mFilteredObjects.addAll((Collection<T>)results.values); NotificationCenter.sendMessage(BaseFeed.NOTIFICATION_DATASET_UPDATE, null, FilterableFeed.this, true); NotificationCenter.sendMessage(NOTIFICATION_FILTER_FINISHED, null, FilterableFeed.this, true); } } protected abstract boolean itemConformsToFilterCondition(T item, CharSequence constraint); }
package com.atguigu.java; /* �߼�������� &���߼��� | ���߼��� �����߼��� && ����·�� || ����·�� ^ ���߼���� ˵���� 1.&��&& �����߶�Ϊtrue���Ϊtrue(ֻҪ��һ��Ϊfalse���Ϊfalse) 2.|��|| �����߶�Ϊfalse���Ϊfalse(ֻҪ��һ��Ϊtrue���Ϊtrue) 3.! : ȡ�� 4.^ :��ͬΪfalse����ͬΪtrue �ص� �� 1.�߼��������������������Dz������� 2.�߼�������Ľ��Ϊ�������� */ public class LogicTest{ public static void main(String[] args){ boolean boo1 = true; boolean boo2 = false; System.out.println(boo1 & boo2); //false System.out.println(boo1 && boo2); //false System.out.println(boo1 | boo2); //true System.out.println(boo1 || boo2);//true System.out.println(!boo2);//true System.out.println(boo1 ^ boo2);//true System.out.println("-----------------------������---------------------------"); /* |��||��������ʲô��&��&&��������ʲô�� &��&&��������ʲô�� &��&&��ߵ�ʽ��Ϊtrueʱ���ұߵ�ʽ�Ӷ���ִ�С�����Ϊ�жϲ�������� &��&&��ߵ�ʽ��Ϊfalseʱ�� &�ұߵ�ʽ����Ȼ��ִ�С� &&�ұߵ�ʽ�Ӳ���ִ�С�����Ϊ�ܹ��жϳ������Ϊfalse�� |��||��������ʲô�� |��||��ߵ�ʽ��Ϊfalseʱ���ұߵ�ʽ�Ӷ���ִ�С�����Ϊ�жϲ�������� |��||��ߵ�ʽ��Ϊtrueʱ�� |�ұߵ�ʽ����Ȼ��ִ�С� ||�ұߵ�ʽ�Ӳ���ִ�С�����Ϊ�ܹ��жϳ������Ϊtrue�� */ //&��&&��������ʲô�� /* boolean bo = false; int number = 5; if(bo & (++number < 10)){ System.out.println("����һ��true"); } System.out.println("bo=" + bo + " number=" + number); int number2 = 5; if(bo && (++number2 < 10)){ System.out.println("����һ��true"); } System.out.println("bo=" + bo + " number2=" + number2); */ System.out.println("------------------------------------------------"); boolean bo = true; int number = 5; if(bo | (++number < 10)){ System.out.println("����һ��true"); } System.out.println("bo=" + bo + " number=" + number); int number2 = 5; if(bo || (++number2 < 10)){ System.out.println("����һ��true"); } System.out.println("bo=" + bo + " number2=" + number2); } }
package com.turo.pages; import org.junit.Assert; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MainPage extends Base{ Logger logger = LoggerFactory.getLogger(MainPage.class); @FindBy(xpath = "//*[name()='use' and contains(@height,'72')]") public WebElement logo; @FindBy(xpath = "//a[normalize-space()='Log in']") public WebElement login; @FindBy(xpath = "//a[normalize-space()='Sign up']") public WebElement signup; @FindBy(xpath = "//img[@alt='Liberty Mutual Insurance']") public WebElement insuranceLogo; public void verifyLogo() { logo.isDisplayed(); logger.info("Turo logo is displayed"); } String actual; public void verifyTheFields(String value) { if(value.equals(login.getText())){ actual = login.getText(); Assert.assertEquals(value, actual); logger.info("{} is displayed", value); }else if(value.equals(signup.getText())){ actual = signup.getText(); Assert.assertEquals(value, actual); logger.info("{} is displayed",actual); }else logger.warn("Error"); } public void verifyInsuranceLogo() { insuranceLogo.isDisplayed(); logger.info("Insurance logo is displayed"); } }
package com.google.gwt.ParkIt.client; import java.util.Collection; import java.util.Comparator; import java.util.List; import com.google.gwt.ParkIt.shared.LatLong; import com.google.gwt.ParkIt.shared.MapEntry; import com.google.gwt.cell.client.NumberCell; import com.google.gwt.dom.client.Style; import com.google.gwt.user.cellview.client.CellTable; import com.google.gwt.user.cellview.client.Column; import com.google.gwt.user.cellview.client.ColumnSortEvent.ListHandler; import com.google.gwt.user.cellview.client.TextColumn; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.view.client.ListDataProvider; public class MapEntryTable { public static void displayMapEntryTable(Collection<MapEntry> entries) { // Create CellTable. CellTable<MapEntry> table = new CellTable<MapEntry>(); // Create type column. TextColumn<MapEntry> typeColumn = new TextColumn<MapEntry>() { @Override public String getValue(MapEntry mapEntry) { return mapEntry.getType(); } }; // Create lat column. NumberCell latCell = new NumberCell(); Column<MapEntry, Number> latColumn = new Column<MapEntry, Number>(latCell) { @Override public Number getValue(MapEntry mapEntry) { LatLong latLong = mapEntry.getLatLong(); return latLong.getLat(); } }; // Create lon column. NumberCell lonCell = new NumberCell(); Column<MapEntry, Number> lonColumn = new Column<MapEntry, Number>(lonCell) { @Override public Number getValue(MapEntry mapEntry) { LatLong latLong = mapEntry.getLatLong(); return latLong.getLong(); } }; // Make the type column sortable. // Note: the table is sorted on the client side. typeColumn.setSortable(true); latColumn.setSortable(true); lonColumn.setSortable(true); // Add the columns. table.addColumn(typeColumn, "Type"); table.addColumn(latColumn, "Lat"); table.addColumn(lonColumn, "Long"); // Create a data provider. ListDataProvider<MapEntry> dataProvider = new ListDataProvider<MapEntry>(); // Connect the table to the data provider. dataProvider.addDataDisplay(table); // Add the data to the data provider, which automatically pushes it to the // widget. List<MapEntry> list = dataProvider.getList(); for (MapEntry MapEntry : entries) { list.add(MapEntry); } // Add a ColumnSortEvent.ListHandler to connect sorting to the // java.util.List. // type Column sorting ListHandler<MapEntry> typeColumnSortHandler = new ListHandler<MapEntry>(list); typeColumnSortHandler.setComparator(typeColumn, new Comparator<MapEntry>() { public int compare(MapEntry o1, MapEntry o2) { if (o1 == o2) { return 0; } // Compare the type columns. if (o1 != null) { if (o2 != null) { return o1.getType().compareTo(o2.getType()); } return 1; } return -1; } }); table.addColumnSortHandler(typeColumnSortHandler); // lat Column sorting ListHandler<MapEntry> latColumnSortHandler = new ListHandler<MapEntry>(list); latColumnSortHandler.setComparator(latColumn, new Comparator<MapEntry>() { public int compare(MapEntry o1, MapEntry o2) { if (o1 == o2) { return 0; } // Compare the lat columns. if (o1 != null) { if (o2 != null) { LatLong l1 = o1.getLatLong(); LatLong l2 = o2. getLatLong(); return (l1.getLat() < l2.getLat()) ? -1 : 1; } return 1; } return -1; } }); table.addColumnSortHandler(latColumnSortHandler); // lon Column sorting ListHandler<MapEntry> lonColumnSortHandler = new ListHandler<MapEntry>(list); lonColumnSortHandler.setComparator(lonColumn, new Comparator<MapEntry>() { public int compare(MapEntry o1, MapEntry o2) { if (o1 == o2) { return 0; } // Compare the lon columns. if (o1 != null) { if (o2 != null) { LatLong l1 = o1.getLatLong(); LatLong l2 = o2. getLatLong(); return (l1.getLong() < l2.getLong()) ? -1 : 1; } return 1; } return -1; } }); table.addColumnSortHandler(lonColumnSortHandler); // We know that the data is sorted alphabetically by default. table.getColumnSortList().push(typeColumn); table.getColumnSortList().push(latColumn); table.getColumnSortList().push(lonColumn); // arbitrary visible range of table; don't set it too high or performance will suffer table.setVisibleRange(0, 100); Style style = table.getElement().getStyle(); style.setProperty("margin", "auto"); // Add it to the root panel. RootPanel.get("table").add(table); } }
package com.pykj.mybatis.test; import com.pykj.mybatis.entity.Student; import com.pykj.mybatis.repository.StudengRepository; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder; import java.io.InputStream; public class Test6 { public static void main(String[] args) { InputStream inputStream = Test.class.getClassLoader().getResourceAsStream("mybatis.xml"); SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder(); SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream); SqlSession sqlSession = sqlSessionFactory.openSession(); StudengRepository studengRepository = sqlSession.getMapper(StudengRepository.class); System.out.println("====查询===="); Student byId = studengRepository.findByIdLazy(1); System.out.println(byId.getClasses()); } }
package com.citibank.ods.persistence.pl.dao.rdb.oracle; import java.math.BigDecimal; import java.math.BigInteger; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import com.citibank.ods.common.connection.rdb.ManagedRdbConnection; import com.citibank.ods.common.dataset.DataSet; import com.citibank.ods.common.dataset.DataSetRow; import com.citibank.ods.common.dataset.ResultSetDataSet; import com.citibank.ods.common.exception.NoRowsReturnedException; import com.citibank.ods.common.exception.UnexpectedException; import com.citibank.ods.entity.pl.BaseTplBrokerEntity; import com.citibank.ods.entity.pl.TplBrokerEntity; import com.citibank.ods.entity.pl.valueobject.TplBrokerEntityVO; import com.citibank.ods.persistence.pl.dao.TplBrokerDAO; import com.citibank.ods.persistence.pl.dao.rdb.oracle.factory.OracleODSDAOFactory; import com.citibank.ods.persistence.util.CitiStatement; /** * Implementação Oracle para DAO da tabela TPL_BROKER * @author Hamilton Matos */ public class OracleTplBrokerDAO extends BaseOracleTplBrokerDAO implements TplBrokerDAO { private static final String C_TABLE_COLUMNS = "BKR_CNPJ_NBR, BKR_NAME_TEXT, BKR_ADDR_TEXT, BKR_BMF_MKT_CODE, BKR_BOVESPA_MKT_CODE, BKR_RBT_BMF_RATE, BKR_RBT_BOVESPA_RATE, BKR_REQ_DATE, BKR_RNW_DATE, BKR_APPRV_STAT_CODE, BKR_APPRV_DATE, BKR_AUTH_PROC_SIT_TEXT, BKR_REQ_CR_LIM_LCY_AMT, BKR_APPRV_CR_LIM_LCY_AMT, BKR_REQ_CR_LIM_DLR_AMT, BKR_APPRV_CR_LIM_DLR_AMT, BKR_SUPL_SERV_TEXT, BKR_COMMENT_TEXT, LAST_UPD_USER_ID, LAST_UPD_DATE, LAST_AUTH_DATE, LAST_AUTH_USER_ID, REC_STAT_CODE"; private static final String C_LAST_AUTH_DATE = "LAST_AUTH_DATE"; private static final String C_LAST_AUTH_USER_ID = "LAST_AUTH_USER_ID"; private static final String C_OPERN_CODE = "OPERN_CODE"; private static final String C_REC_STAT_CODE = "REC_STAT_CODE"; private static final String C_BKR_ADDR_TEXT = "BKR_ADDR_TEXT"; private static final String C_BKR_APPRV_CR_LIM_DLR_AMT = "BKR_APPRV_CR_LIM_DLR_AMT"; private static final String C_BKR_APPRV_CR_LIM_LCY_AMT = "BKR_APPRV_CR_LIM_LCY_AMT"; private static final String C_BKR_APPRV_DATE = "BKR_APPRV_DATE"; private static final String C_BKR_APPRV_STAT_CODE = "BKR_APPRV_STAT_CODE"; private static final String C_BKR_AUTH_PROC_SIT_TEXT = "BKR_AUTH_PROC_SIT_TEXT"; private static final String C_BKR_BMF_MKT_CODE = "BKR_BMF_MKT_CODE"; private static final String C_BKR_BOVESPA_MKT_CODE = "BKR_BOVESPA_MKT_CODE"; private static final String C_BKR_CNPJ_NBR = "BKR_CNPJ_NBR"; private static final String C_BKR_COMMENT_TEXT = "BKR_COMMENT_TEXT"; private static final String C_BKR_NAME_TEXT = "BKR_NAME_TEXT"; private static final String C_BKR_RBT_BMF_RATE = "BKR_RBT_BMF_RATE"; private static final String C_BKR_RBT_BOVESPA_RATE = "BKR_RBT_BOVESPA_RATE"; private static final String C_BKR_REQ_CR_LIM_DLR_AMT = "BKR_REQ_CR_LIM_DLR_AMT"; private static final String C_BKR_REQ_CR_LIM_LCY_AMT = "BKR_REQ_CR_LIM_LCY_AMT"; private static final String C_BKR_REQ_DATE = "BKR_REQ_DATE"; private static final String C_BKR_RNW_DATE = "BKR_RNW_DATE"; private static final String C_BKR_SUPL_SERV_TEXT = "BKR_SUPL_SERV_TEXT"; private static final String C_LAST_UPD_DATE = "LAST_UPD_DATE"; private static final String C_LAST_UPD_USER_ID = "LAST_UPD_USER_ID"; private static final String C_TABLE_NAME = C_PL_SCHEMA + "TPL_BROKER"; public TplBrokerEntity insert( TplBrokerEntity tplBrokerEntity_ ) throws UnexpectedException { ManagedRdbConnection connection = null; CitiStatement preparedStatement = null; ResultSet resultSet = null; StringBuffer sqlQuery = new StringBuffer(); sqlQuery.append( "INSERT INTO " + C_TABLE_NAME + "( " ); sqlQuery.append( C_BKR_ADDR_TEXT + ", " ); sqlQuery.append( C_BKR_APPRV_CR_LIM_DLR_AMT + ", " ); sqlQuery.append( C_BKR_APPRV_CR_LIM_LCY_AMT + ", " ); sqlQuery.append( C_BKR_APPRV_DATE + ", " ); sqlQuery.append( C_BKR_APPRV_STAT_CODE + ", " ); sqlQuery.append( C_BKR_AUTH_PROC_SIT_TEXT + ", " ); sqlQuery.append( C_BKR_BMF_MKT_CODE + ", " ); sqlQuery.append( C_BKR_BOVESPA_MKT_CODE + ", " ); sqlQuery.append( C_BKR_CNPJ_NBR + ", " ); sqlQuery.append( C_BKR_COMMENT_TEXT + ", " ); sqlQuery.append( C_BKR_NAME_TEXT + ", " ); sqlQuery.append( C_BKR_RBT_BMF_RATE + ", " ); sqlQuery.append( C_BKR_RBT_BOVESPA_RATE + ", " ); sqlQuery.append( C_BKR_REQ_CR_LIM_DLR_AMT + ", " ); sqlQuery.append( C_BKR_REQ_CR_LIM_LCY_AMT + ", " ); sqlQuery.append( C_BKR_REQ_DATE + ", " ); sqlQuery.append( C_BKR_RNW_DATE + ", " ); sqlQuery.append( C_BKR_SUPL_SERV_TEXT + ", " ); sqlQuery.append( C_LAST_UPD_DATE + ", " ); sqlQuery.append( C_LAST_UPD_USER_ID + ", " ); sqlQuery.append( C_LAST_AUTH_USER_ID + ", " ); sqlQuery.append( C_LAST_AUTH_DATE + ", " ); sqlQuery.append( C_REC_STAT_CODE + ") " ); sqlQuery.append( " VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)" ); try { connection = OracleODSDAOFactory.getConnection(); preparedStatement = new CitiStatement(connection.prepareStatement( sqlQuery.toString() )); int count = 1; if ( tplBrokerEntity_.getData().getBkrAddrText() != null && !tplBrokerEntity_.getData().getBkrAddrText().equals( "" ) ) { preparedStatement.setString( count++, tplBrokerEntity_.getData().getBkrAddrText() ); } else { preparedStatement.setString( count++, "" ); } if ( tplBrokerEntity_.getData().getBkrApprvCrLimDlrAmt() != null ) { preparedStatement.setBigDecimal( count++, tplBrokerEntity_.getData().getBkrApprvCrLimDlrAmt() ); } else { preparedStatement.setNull( count++, java.sql.Types.DECIMAL ); } if ( tplBrokerEntity_.getData().getBkrApprvCrLimLcyAmt() != null ) { preparedStatement.setBigDecimal( count++, tplBrokerEntity_.getData().getBkrApprvCrLimLcyAmt() ); } else { preparedStatement.setNull( count++, java.sql.Types.DECIMAL ); } if ( tplBrokerEntity_.getData().getBkrApprvDate() != null && !tplBrokerEntity_.getData().getBkrApprvDate().equals( "" ) ) { preparedStatement.setTimestamp( count++, new Timestamp( tplBrokerEntity_.getData().getBkrApprvDate().getTime() ) ); } else { preparedStatement.setTimestamp( count++, null ); } if ( tplBrokerEntity_.getData().getBkrApprvStatCode() != null && !tplBrokerEntity_.getData().getBkrApprvStatCode().equals( "" ) ) { preparedStatement.setString( count++, tplBrokerEntity_.getData().getBkrApprvStatCode() ); } else { preparedStatement.setString( count++, null ); } if ( tplBrokerEntity_.getData().getBkrAuthProcSitText() != null && !tplBrokerEntity_.getData().getBkrAuthProcSitText().equals( "" ) ) { preparedStatement.setString( count++, tplBrokerEntity_.getData().getBkrAuthProcSitText() ); } else { preparedStatement.setString( count++, null ); } if ( tplBrokerEntity_.getData().getBkrBmfMktCode() != null && !tplBrokerEntity_.getData().getBkrBmfMktCode().equals( "" ) ) { preparedStatement.setString( count++, tplBrokerEntity_.getData().getBkrBmfMktCode() ); } else { preparedStatement.setString( count++, null ); } if ( tplBrokerEntity_.getData().getBkrBovespaMktCode() != null && !tplBrokerEntity_.getData().getBkrBovespaMktCode().equals( "" ) ) { preparedStatement.setString( count++, tplBrokerEntity_.getData().getBkrBovespaMktCode() ); } else { preparedStatement.setString( count++, null ); } if ( tplBrokerEntity_.getData().getBkrCnpjNbr() != null && !tplBrokerEntity_.getData().getBkrCnpjNbr().equals( "" ) ) { preparedStatement.setString( count++, tplBrokerEntity_.getData().getBkrCnpjNbr() ); } else { throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null ); } if ( tplBrokerEntity_.getData().getBkrCommentText() != null && !tplBrokerEntity_.getData().getBkrCommentText().equals( "" ) ) { preparedStatement.setString( count++, tplBrokerEntity_.getData().getBkrCommentText() ); } else { preparedStatement.setString( count++, null ); } if ( tplBrokerEntity_.getData().getBkrNameText() != null && !tplBrokerEntity_.getData().getBkrNameText().equals( "" ) ) { preparedStatement.setString( count++, tplBrokerEntity_.getData().getBkrNameText() ); } else { preparedStatement.setString( count++, null ); } if ( tplBrokerEntity_.getData().getBkrRbtBmfRate() != null ) { preparedStatement.setBigDecimal( count++, tplBrokerEntity_.getData().getBkrRbtBmfRate() ); } else { preparedStatement.setNull( count++, java.sql.Types.DECIMAL ); } if ( tplBrokerEntity_.getData().getBkrRbtBovespaRate() != null ) { preparedStatement.setBigDecimal( count++, tplBrokerEntity_.getData().getBkrRbtBovespaRate() ); } else { preparedStatement.setNull( count++, java.sql.Types.DECIMAL ); } if ( tplBrokerEntity_.getData().getBkrReqCrLimDlrAmt() != null ) { preparedStatement.setBigDecimal( count++, tplBrokerEntity_.getData().getBkrReqCrLimDlrAmt() ); } else { preparedStatement.setNull( count++, java.sql.Types.DECIMAL ); } if ( tplBrokerEntity_.getData().getBkrReqCrLimLcyAmt() != null ) { preparedStatement.setBigDecimal( count++, tplBrokerEntity_.getData().getBkrReqCrLimLcyAmt() ); } else { preparedStatement.setNull( count++, java.sql.Types.DECIMAL ); } if ( tplBrokerEntity_.getData().getBkrReqDate() != null && !tplBrokerEntity_.getData().getBkrReqDate().equals( "" ) ) { preparedStatement.setTimestamp( count++, new Timestamp( tplBrokerEntity_.getData().getBkrReqDate().getTime() ) ); } else { preparedStatement.setTimestamp( count++, null ); } if ( tplBrokerEntity_.getData().getBkrRnwDate() != null && !tplBrokerEntity_.getData().getBkrRnwDate().equals( "" ) ) { preparedStatement.setTimestamp( count++, new Timestamp( tplBrokerEntity_.getData().getBkrRnwDate().getTime() ) ); } else { preparedStatement.setTimestamp( count++, null ); } if ( tplBrokerEntity_.getData().getBkrSuplServText() != null && !tplBrokerEntity_.getData().getBkrSuplServText().equals( "" ) ) { preparedStatement.setString( count++, tplBrokerEntity_.getData().getBkrSuplServText() ); } else { preparedStatement.setString( count++, null ); } if ( tplBrokerEntity_.getData().getLastUpdDate() != null && !tplBrokerEntity_.getData().getLastUpdDate().equals( "" ) ) { preparedStatement.setTimestamp( count++, new Timestamp( tplBrokerEntity_.getData().getLastUpdDate().getTime() ) ); } else { throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null ); } if ( tplBrokerEntity_.getData().getLastUpdUserId() != null && !tplBrokerEntity_.getData().getLastUpdUserId().equals( "" ) ) { preparedStatement.setString( count++, tplBrokerEntity_.getData().getLastUpdUserId() ); } else { throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null ); } TplBrokerEntityVO tplBrokerEntityVO = ( TplBrokerEntityVO ) tplBrokerEntity_.getData(); if ( tplBrokerEntityVO.getLastAuthUserId() != null ) { preparedStatement.setString( count++, tplBrokerEntityVO.getLastAuthUserId() ); } else { throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null ); } if ( tplBrokerEntityVO.getLastAuthDate() != null ) { preparedStatement.setTimestamp( count++, new Timestamp( tplBrokerEntityVO.getLastAuthDate().getTime() ) ); } else { throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null ); } if ( tplBrokerEntityVO.getRecStatCode() != null ) { preparedStatement.setString( count++, tplBrokerEntityVO.getRecStatCode() ); } else { throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null ); } preparedStatement.replaceParametersInQuery(sqlQuery.toString()); preparedStatement.executeUpdate(); } catch ( SQLException e ) { throw new UnexpectedException( e.getErrorCode(), C_ERROR_EXECUTING_STATEMENT, e ); } finally { closeStatement( preparedStatement ); closeConnection( connection ); } return tplBrokerEntity_; } /** * Atualiza uma linha na tabela TPL_BROKER de acordo com ID contido na * entidade passada como parâmetro. * @param tplBrokerEntity__ * @throws UnexpectedException * @author Hamilton Matos */ public void update( TplBrokerEntity tplBrokerEntity_ ) throws UnexpectedException { ManagedRdbConnection connection = null; CitiStatement preparedStatement = null; ResultSet resultSet = null; StringBuffer sqlQuery = new StringBuffer(); int rowCount; sqlQuery.append( "UPDATE " ); sqlQuery.append( C_TABLE_NAME ); sqlQuery.append( " SET " ); sqlQuery.append( C_BKR_ADDR_TEXT + " = ?, " ); sqlQuery.append( C_BKR_APPRV_CR_LIM_DLR_AMT + " = ?, " ); sqlQuery.append( C_BKR_APPRV_CR_LIM_LCY_AMT + " = ?, " ); sqlQuery.append( C_BKR_APPRV_DATE + " = ?, " ); sqlQuery.append( C_BKR_APPRV_STAT_CODE + " = ?, " ); sqlQuery.append( C_BKR_AUTH_PROC_SIT_TEXT + " = ?, " ); sqlQuery.append( C_BKR_BMF_MKT_CODE + " = ?, " ); sqlQuery.append( C_BKR_BOVESPA_MKT_CODE + " = ?, " ); sqlQuery.append( C_BKR_COMMENT_TEXT + " = ?, " ); sqlQuery.append( C_BKR_NAME_TEXT + " = ?, " ); sqlQuery.append( C_BKR_RBT_BMF_RATE + " = ?, " ); sqlQuery.append( C_BKR_RBT_BOVESPA_RATE + " = ?, " ); sqlQuery.append( C_BKR_REQ_CR_LIM_DLR_AMT + " = ?, " ); sqlQuery.append( C_BKR_REQ_CR_LIM_LCY_AMT + " = ?, " ); sqlQuery.append( C_BKR_REQ_DATE + " = ?, " ); sqlQuery.append( C_BKR_RNW_DATE + " = ?, " ); sqlQuery.append( C_BKR_SUPL_SERV_TEXT + " = ?, " ); sqlQuery.append( C_LAST_UPD_DATE + " = ?, " ); sqlQuery.append( C_LAST_UPD_USER_ID + " = ?, " ); sqlQuery.append( C_LAST_AUTH_DATE + " = ?, " ); sqlQuery.append( C_LAST_AUTH_USER_ID + " = ?, " ); sqlQuery.append( C_REC_STAT_CODE + " = ? " ); sqlQuery.append( " WHERE " ); sqlQuery.append( C_BKR_CNPJ_NBR + " = ? " ); try { connection = OracleODSDAOFactory.getConnection(); preparedStatement = new CitiStatement(connection.prepareStatement( sqlQuery.toString() )); int count = 1; if ( tplBrokerEntity_.getData().getBkrAddrText() != null && !tplBrokerEntity_.getData().getBkrAddrText().equals( "" ) ) { preparedStatement.setString( count++, tplBrokerEntity_.getData().getBkrAddrText() ); } else { preparedStatement.setString( count++, null ); } if ( tplBrokerEntity_.getData().getBkrApprvCrLimDlrAmt() != null ) { preparedStatement.setBigDecimal( count++, tplBrokerEntity_.getData().getBkrApprvCrLimDlrAmt() ); } else { preparedStatement.setNull( count++, java.sql.Types.DECIMAL ); } if ( tplBrokerEntity_.getData().getBkrApprvCrLimLcyAmt() != null ) { preparedStatement.setBigDecimal( count++, tplBrokerEntity_.getData().getBkrApprvCrLimLcyAmt() ); } else { preparedStatement.setNull( count++, java.sql.Types.DECIMAL ); } if ( tplBrokerEntity_.getData().getBkrApprvDate() != null && !tplBrokerEntity_.getData().getBkrApprvDate().equals( "" ) ) { preparedStatement.setTimestamp( count++, new Timestamp( tplBrokerEntity_.getData().getBkrApprvDate().getTime() ) ); } else { preparedStatement.setTimestamp( count++, null ); } if ( tplBrokerEntity_.getData().getBkrApprvStatCode() != null && !tplBrokerEntity_.getData().getBkrApprvStatCode().equals( "" ) ) { preparedStatement.setString( count++, tplBrokerEntity_.getData().getBkrApprvStatCode() ); } else { preparedStatement.setString( count++, null ); } if ( tplBrokerEntity_.getData().getBkrAuthProcSitText() != null && !tplBrokerEntity_.getData().getBkrAuthProcSitText().equals( "" ) ) { preparedStatement.setString( count++, tplBrokerEntity_.getData().getBkrAuthProcSitText() ); } else { preparedStatement.setString( count++, null ); } if ( tplBrokerEntity_.getData().getBkrBmfMktCode() != null && !tplBrokerEntity_.getData().getBkrBmfMktCode().equals( "" ) ) { preparedStatement.setString( count++, tplBrokerEntity_.getData().getBkrBmfMktCode() ); } else { preparedStatement.setString( count++, null ); } if ( tplBrokerEntity_.getData().getBkrBovespaMktCode() != null && !tplBrokerEntity_.getData().getBkrBovespaMktCode().equals( "" ) ) { preparedStatement.setString( count++, tplBrokerEntity_.getData().getBkrBovespaMktCode() ); } else { preparedStatement.setString( count++, null ); } if ( tplBrokerEntity_.getData().getBkrCommentText() != null && !tplBrokerEntity_.getData().getBkrCommentText().equals( "" ) ) { preparedStatement.setString( count++, tplBrokerEntity_.getData().getBkrCommentText() ); } else { preparedStatement.setString( count++, null ); } if ( tplBrokerEntity_.getData().getBkrNameText() != null && !tplBrokerEntity_.getData().getBkrNameText().equals( "" ) ) { preparedStatement.setString( count++, tplBrokerEntity_.getData().getBkrNameText() ); } else { preparedStatement.setString( count++, null ); } if ( tplBrokerEntity_.getData().getBkrRbtBmfRate() != null ) { preparedStatement.setBigDecimal( count++, tplBrokerEntity_.getData().getBkrRbtBmfRate() ); } else { preparedStatement.setNull( count++, java.sql.Types.DECIMAL ); } if ( tplBrokerEntity_.getData().getBkrRbtBovespaRate() != null ) { preparedStatement.setBigDecimal( count++, tplBrokerEntity_.getData().getBkrRbtBovespaRate() ); } else { preparedStatement.setNull( count++, java.sql.Types.DECIMAL ); } if ( tplBrokerEntity_.getData().getBkrReqCrLimDlrAmt() != null ) { preparedStatement.setBigDecimal( count++, tplBrokerEntity_.getData().getBkrReqCrLimDlrAmt() ); } else { preparedStatement.setNull( count++, java.sql.Types.DECIMAL ); } if ( tplBrokerEntity_.getData().getBkrReqCrLimLcyAmt() != null ) { preparedStatement.setBigDecimal( count++, tplBrokerEntity_.getData().getBkrReqCrLimLcyAmt() ); } else { preparedStatement.setNull( count++, java.sql.Types.DECIMAL ); } if ( tplBrokerEntity_.getData().getBkrReqDate() != null && !tplBrokerEntity_.getData().getBkrReqDate().equals( "" ) ) { preparedStatement.setTimestamp( count++, new Timestamp( tplBrokerEntity_.getData().getBkrReqDate().getTime() ) ); } else { preparedStatement.setTimestamp( count++, null ); } if ( tplBrokerEntity_.getData().getBkrRnwDate() != null && !tplBrokerEntity_.getData().getBkrRnwDate().equals( "" ) ) { preparedStatement.setTimestamp( count++, new Timestamp( tplBrokerEntity_.getData().getBkrRnwDate().getTime() ) ); } else { preparedStatement.setTimestamp( count++, null ); } if ( tplBrokerEntity_.getData().getBkrSuplServText() != null && !tplBrokerEntity_.getData().getBkrSuplServText().equals( "" ) ) { preparedStatement.setString( count++, tplBrokerEntity_.getData().getBkrSuplServText() ); } else { preparedStatement.setString( count++, null ); } if ( tplBrokerEntity_.getData().getLastUpdDate() != null && !tplBrokerEntity_.getData().getLastUpdDate().equals( "" ) ) { preparedStatement.setTimestamp( count++, new Timestamp( tplBrokerEntity_.getData().getLastUpdDate().getTime() ) ); } else { throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null ); } if ( tplBrokerEntity_.getData().getLastUpdUserId() != null && !tplBrokerEntity_.getData().getLastUpdUserId().equals( "" ) ) { preparedStatement.setString( count++, tplBrokerEntity_.getData().getLastUpdUserId() ); } else { throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null ); } TplBrokerEntityVO tplBrokerEntityVO = ( TplBrokerEntityVO ) tplBrokerEntity_.getData(); if ( tplBrokerEntityVO.getLastAuthDate() != null ) { preparedStatement.setTimestamp( count++, new Timestamp( tplBrokerEntityVO.getLastAuthDate().getTime() ) ); } else { throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null ); } if ( tplBrokerEntityVO.getLastAuthUserId() != null ) { preparedStatement.setString( count++, tplBrokerEntityVO.getLastAuthUserId() ); } else { throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null ); } if ( tplBrokerEntityVO.getRecStatCode() != null ) { preparedStatement.setString( count++, tplBrokerEntityVO.getRecStatCode() ); } else { throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null ); } if ( tplBrokerEntity_.getData().getBkrCnpjNbr() != null ) { preparedStatement.setString( count++, tplBrokerEntity_.getData().getBkrCnpjNbr() ); } else { throw new UnexpectedException( C_ERROR_EXECUTING_STATEMENT, null ); } preparedStatement.replaceParametersInQuery(sqlQuery.toString()); preparedStatement.executeUpdate(); } catch ( SQLException e ) { throw new UnexpectedException( e.getErrorCode(), C_ERROR_EXECUTING_STATEMENT, e ); } finally { closeStatement( preparedStatement ); closeConnection( connection ); } } /* * (non-Javadoc) * @see com.citibank.ods.persistence.pl.dao.TplBrokerDAO#delete(java.math.BigInteger) */ public void delete( BigInteger entityKey_ ) throws UnexpectedException { // } /* * (non-Javadoc) * @see com.citibank.ods.persistence.pl.dao.TplBrokerDAO#list(java.util.Date, * java.lang.String, java.lang.String, java.lang.String, * java.lang.String, java.math.BigInteger, java.math.BigInteger, * java.util.Date, java.lang.String, java.lang.String, java.lang.String, * java.lang.String, java.lang.String, java.lang.String, * java.lang.String, java.math.BigInteger, java.math.BigInteger, * java.math.BigInteger, java.math.BigInteger, java.util.Date, * java.util.Date, java.lang.String, java.util.Date, java.lang.String) */ // public DataSet list( Date lastAuthDate_, String lastAuthUserId_, // String opernCode_, String recStatCode_, // String bkrAddrText_, BigDecimal bkrApprvCrLimDlrAmt_, // BigDecimal bkrApprvCrLimLcyAmt_, Date bkrApprvDate_, // String bkrApprvStatCode_, String bkrAuthProcSitText_, // String bkrBmfMktCode_, String bkrBovespaMktCode_, // String bkrCnpjNbr_, String bkrCommentText_, // String bkrNameText_, BigDecimal bkrRbtBmfRate_, // BigDecimal bkrRbtBovespaRate_, // BigDecimal bkrReqCrLimDlrAmt_, // BigDecimal bkrReqCrLimLcyAmt_, Date bkrReqDate_, // Date bkrRnwDate_, String bkrSuplServText_, // Date lastUpdDate_, String lastUpdUserId_ ) // throws UnexpectedException // { // ResultSet resultSet = null; // ResultSetDataSet resultSetDataSet = null; // CitiStatement preparedStatement = null; // ManagedRdbConnection connection = null; // StringBuffer sqlQuery = new StringBuffer(); // // try // { // connection = OracleODSDAOFactory.getConnection(); // sqlQuery.append( "SELECT " ); // // sqlQuery.append( C_TABLE_COLUMNS ); // sqlQuery.append( " FROM " ); // sqlQuery.append( C_TABLE_NAME ); // sqlQuery.append( "WHERE " ); // // if ( lastAuthDate_ != null && !lastAuthDate_.equals( "" ) ) // { // sqlQuery.append( " TRUNC(LAST_AUTH_DATE) = ? " ); // } // if ( lastAuthUserId_ != null && !lastAuthUserId_.equals( "" ) ) // { // sqlQuery.append( " LAST_AUTH_USER_ID = ? " ); // } // // if ( opernCode_ != null && !opernCode_.equals( "" ) ) // { // sqlQuery.append( " OPERN_CODE = ? " ); // } // // if ( recStatCode_ != null && !recStatCode_.equals( "" ) ) // { // sqlQuery.append( " REC_STAT_CODE = ? " ); // } // // if ( bkrAddrText_ != null && !bkrAddrText_.equals( "" ) ) // { // sqlQuery.append( " BKR_ADDR_TEXT = ? AND " ); // } // // if ( bkrApprvCrLimDlrAmt_ != null && !bkrApprvCrLimDlrAmt_.equals( "" ) ) // { // sqlQuery.append( " BKR_APPRV_CR_LIM_DLR_AMT = ? AND " ); // } // // if ( bkrApprvCrLimLcyAmt_ != null && !bkrApprvCrLimLcyAmt_.equals( "" ) ) // { // sqlQuery.append( " BKR_APPRV_CR_LIM_LCY_AMT = ? AND " ); // } // // if ( bkrApprvDate_ != null && !bkrApprvDate_.equals( "" ) ) // { // sqlQuery.append( " BKR_APPRV_DATE = ? AND " ); // } // // if ( bkrApprvStatCode_ != null && !bkrApprvStatCode_.equals( "" ) ) // { // sqlQuery.append( " BKR_APPRV_STAT_CODE = ? AND " ); // } // // if ( bkrAuthProcSitText_ != null && !bkrAuthProcSitText_.equals( "" ) ) // { // sqlQuery.append( " BKR_AUTH_PROC_SIT_TEXT = ? AND " ); // } // // if ( bkrBmfMktCode_ != null && !bkrBmfMktCode_.equals( "" ) ) // { // sqlQuery.append( " BKR_BMF_MKT_CODE = ? AND " ); // } // // if ( bkrBovespaMktCode_ != null && !bkrBovespaMktCode_.equals( "" ) ) // { // sqlQuery.append( " BKR_BOVESPA_MKT_CODE = ? AND " ); // } // // if ( bkrCnpjNbr_ != null && !bkrCnpjNbr_.equals( "" ) ) // { // sqlQuery.append( " BKR_CNPJ_NBR = ? AND " ); // } // // if ( bkrCommentText_ != null && !bkrCommentText_.equals( "" ) ) // { // sqlQuery.append( " BKR_COMMENT_TEXT = ? AND " ); // } // // if ( bkrNameText_ != null && !bkrNameText_.equals( "" ) ) // { // sqlQuery.append( " BKR_NAME_TEXT = ? AND " ); // } // // if ( bkrRbtBmfRate_ != null && !bkrRbtBmfRate_.equals( "" ) ) // { // sqlQuery.append( " BKR_RBT_BMF_RATE = ? AND " ); // } // // if ( bkrRbtBovespaRate_ != null && !bkrRbtBovespaRate_.equals( "" ) ) // { // sqlQuery.append( " BKR_RBT_BOVESPA_RATE = ? AND " ); // } // // if ( bkrReqCrLimDlrAmt_ != null && !bkrReqCrLimDlrAmt_.equals( "" ) ) // { // sqlQuery.append( " BKR_REQ_CR_LIM_DLR_AMT = ? AND " ); // } // // if ( bkrReqCrLimLcyAmt_ != null && !bkrReqCrLimLcyAmt_.equals( "" ) ) // { // sqlQuery.append( " BKR_REQ_CR_LIM_LCY_AMT = ? AND " ); // } // // if ( bkrReqDate_ != null && !bkrReqDate_.equals( "" ) ) // { // sqlQuery.append( " BKR_REQ_DATE = ? AND " ); // } // // if ( bkrRnwDate_ != null && !bkrRnwDate_.equals( "" ) ) // { // sqlQuery.append( " BKR_RNW_DATE = ? AND " ); // } // // if ( bkrSuplServText_ != null && !bkrSuplServText_.equals( "" ) ) // { // sqlQuery.append( " BKR_SUPL_SERV_TEXT = ? AND " ); // } // // if ( lastUpdDate_ != null && !lastUpdDate_.equals( "" ) ) // { // sqlQuery.append( " TRUNC(LAST_UPD_DATE) = ? " ); // } // // if ( lastUpdUserId_ != null && !lastUpdUserId_.equals( "" ) ) // { // sqlQuery.append( " LAST_UPD_USER_ID = ? " ); // } // // sqlQuery.append( " ORDER BY BKR_CNPJ_NBR" ); // // preparedStatement = new CitiStatement(connection.prepareStatement( sqlQuery.toString() )); // // int count = 1; // // if ( lastAuthDate_ != null || !lastAuthDate_.equals( "" ) ) // { // preparedStatement.setDate( count++, new java.sql.Date( lastAuthDate_.getTime() ) ); // } // if ( lastAuthUserId_ != null || !lastAuthUserId_.equals( "" ) ) // { // preparedStatement.setString( count++, lastAuthUserId_ ); // } // // if ( opernCode_ != null || !opernCode_.equals( "" ) ) // { // preparedStatement.setString( count++, opernCode_ ); // } // if ( recStatCode_ != null || !recStatCode_.equals( "" ) ) // { // preparedStatement.setString( count++, recStatCode_ ); // } // // if ( bkrAddrText_ != null || !bkrAddrText_.equals( "" ) ) // { // preparedStatement.setString( count++, bkrAddrText_ ); // } // // if ( bkrApprvCrLimDlrAmt_ != null ) // { // preparedStatement.setBigDecimal( count++, bkrApprvCrLimDlrAmt_ ); // } // // if ( bkrApprvCrLimLcyAmt_ != null ) // { // preparedStatement.setBigDecimal( count++, bkrApprvCrLimLcyAmt_ ); // } // // if ( bkrApprvDate_ != null || !bkrApprvDate_.equals( "" ) ) // { // preparedStatement.setDate( count++, new java.sql.Date( bkrApprvDate_.getTime() ) ); // } // // if ( bkrApprvStatCode_ != null || !bkrApprvStatCode_.equals( "" ) ) // { // preparedStatement.setString( count++, bkrApprvStatCode_ ); // } // // if ( bkrAuthProcSitText_ != null || !bkrAuthProcSitText_.equals( "" ) ) // { // preparedStatement.setString( count++, bkrAuthProcSitText_ ); // } // // if ( bkrBmfMktCode_ != null || !bkrBmfMktCode_.equals( "" ) ) // { // preparedStatement.setString( count++, bkrBmfMktCode_ ); // } // // if ( bkrBovespaMktCode_ != null || !bkrBovespaMktCode_.equals( "" ) ) // { // preparedStatement.setString( count++, bkrBovespaMktCode_ ); // } // // if ( bkrCnpjNbr_ != null || !bkrCnpjNbr_.equals( "" ) ) // { // preparedStatement.setString( count++, bkrCnpjNbr_ ); // } // // if ( bkrCommentText_ != null || !bkrCommentText_.equals( "" ) ) // { // preparedStatement.setString( count++, bkrCommentText_ ); // } // // if ( bkrNameText_ != null || !bkrNameText_.equals( "" ) ) // { // preparedStatement.setString( count++, bkrNameText_ ); // } // // if ( bkrRbtBmfRate_ != null ) // { // preparedStatement.setBigDecimal( count++, bkrRbtBmfRate_ ); // } // // if ( bkrRbtBovespaRate_ != null ) // { // preparedStatement.setBigDecimal( count++, bkrRbtBovespaRate_ ); // } // // if ( bkrReqCrLimDlrAmt_ != null ) // { // preparedStatement.setBigDecimal( count++, bkrReqCrLimDlrAmt_ ); // } // // if ( bkrReqCrLimLcyAmt_ != null ) // { // preparedStatement.setBigDecimal( count++, bkrReqCrLimLcyAmt_ ); // } // // if ( bkrReqDate_ != null || !bkrReqDate_.equals( "" ) ) // { // preparedStatement.setDate( count++, new java.sql.Date( bkrReqDate_.getTime() ) ); // } // // if ( bkrRnwDate_ != null || !bkrRnwDate_.equals( "" ) ) // { // preparedStatement.setDate( count++, new java.sql.Date( bkrRnwDate_.getTime() ) ); // } // // if ( bkrSuplServText_ != null || !bkrSuplServText_.equals( "" ) ) // { // preparedStatement.setString( count++, bkrSuplServText_ ); // } // // if ( lastUpdDate_ != null || !lastUpdDate_.equals( "" ) ) // { // preparedStatement.setDate( count++, new java.sql.Date( lastUpdDate_.getTime() ) ); // } // // if ( lastUpdUserId_ != null || !lastUpdUserId_.equals( "" ) ) // { // preparedStatement.setString( count++, lastUpdUserId_ ); // } // // preparedStatement.replaceParametersInQuery(sqlQuery.toString()); // resultSet = preparedStatement.executeQuery(); // // // resultSetDataSet = new ResultSetDataSet( resultSet ); // // resultSet.close(); // } // catch ( SQLException e ) // { // throw new UnexpectedException( e.getErrorCode(), // C_ERROR_EXECUTING_STATEMENT, e ); // } // finally // { // closeStatement( preparedStatement ); // closeConnection( connection ); // } // return resultSetDataSet; // } public DataSet list( String bkrCnpjNbr_, String bkrNameText_ ) throws UnexpectedException { ResultSet resultSet = null; ResultSetDataSet resultSetDataSet = null; CitiStatement preparedStatement = null; ManagedRdbConnection connection = null; StringBuffer sqlQuery = new StringBuffer(); try { connection = OracleODSDAOFactory.getConnection(); sqlQuery.append( "SELECT " ); sqlQuery.append( C_TABLE_COLUMNS ); sqlQuery.append( " FROM " ); sqlQuery.append( C_TABLE_NAME ); String criteria = ""; criteria = criteria + C_REC_STAT_CODE + " != '" + BaseTplBrokerEntity.C_REC_STAT_CODE_INACTIVE + "'" + " AND "; if ( bkrCnpjNbr_ != null && !bkrCnpjNbr_.equals( "" ) ) { criteria = criteria + C_BKR_CNPJ_NBR + " = ? AND "; } if ( bkrNameText_ != null && !bkrNameText_.equals( "" ) ) { criteria = criteria + "UPPER(" + C_BKR_NAME_TEXT + ") like ? AND "; } if ( criteria.length() > 0 ) { criteria = criteria.substring( 0, criteria.length() - 5 ); sqlQuery.append( " WHERE " + criteria ); } sqlQuery.append( " ORDER BY " + C_BKR_NAME_TEXT); preparedStatement = new CitiStatement(connection.prepareStatement( sqlQuery.toString() )); int count = 1; if ( bkrCnpjNbr_ != null && !"".equals( bkrCnpjNbr_ ) ) { preparedStatement.setString( count++, bkrCnpjNbr_ ); } if ( bkrNameText_ != null && !"".equals( bkrNameText_ ) ) { preparedStatement.setString( count++, "%" + bkrNameText_.toUpperCase() + "%" ); } preparedStatement.replaceParametersInQuery(sqlQuery.toString()); resultSet = preparedStatement.executeQuery(); resultSetDataSet = new ResultSetDataSet( resultSet ); resultSet.close(); } catch ( SQLException e ) { throw new UnexpectedException( e.getErrorCode(), C_ERROR_EXECUTING_STATEMENT, e ); } finally { closeStatement( preparedStatement ); closeConnection( connection ); } return resultSetDataSet; } /* * (non-Javadoc) * @see com.citibank.ods.persistence.pl.dao.BaseTplBrokerDAO#find(com.citibank.ods.entity.pl.BaseTplBrokerEntity) */ public BaseTplBrokerEntity find( BaseTplBrokerEntity baseTplBrokerEntity_ ) throws UnexpectedException { ManagedRdbConnection connection = null; CitiStatement preparedStatement = null; ResultSet resultSet = null; StringBuffer sqlQuery = new StringBuffer(); ArrayList tplBrokerEntities; BaseTplBrokerEntity tplBrokerEntity = null; try { connection = OracleODSDAOFactory.getConnection(); sqlQuery.append( "SELECT " ); sqlQuery.append( C_TABLE_COLUMNS ); sqlQuery.append( " FROM " ); sqlQuery.append( C_TABLE_NAME ); sqlQuery.append( " WHERE " ); sqlQuery.append( " BKR_CNPJ_NBR = ? " ); preparedStatement = new CitiStatement(connection.prepareStatement( sqlQuery.toString() )); preparedStatement.setString( 1, baseTplBrokerEntity_.getData().getBkrCnpjNbr() ); preparedStatement.replaceParametersInQuery(sqlQuery.toString()); resultSet = preparedStatement.executeQuery(); tplBrokerEntities = instantiateFromResultSet( resultSet ); if ( tplBrokerEntities.size() == 0 ) { throw new NoRowsReturnedException(); } else if ( tplBrokerEntities.size() > 1 ) { throw new UnexpectedException( C_ERROR_TOO_MANY_ROWS_RETURNED ); } else { tplBrokerEntity = ( BaseTplBrokerEntity ) tplBrokerEntities.get( 0 ); } return tplBrokerEntity; } catch ( SQLException e ) { throw new UnexpectedException( e.getErrorCode(), C_ERROR_EXECUTING_STATEMENT, e ); } finally { closeStatement( preparedStatement ); closeConnection( connection ); } } /* * Retorna uma coleção de entities a partir do rs */ private ArrayList instantiateFromResultSet( ResultSet resultSet_ ) { TplBrokerEntity tplBrokerEntity; ArrayList tplBrokerEntities = new ArrayList(); try { while ( resultSet_.next() ) { tplBrokerEntity = new TplBrokerEntity(); tplBrokerEntity.getData().setBkrCnpjNbr( resultSet_.getString( C_BKR_CNPJ_NBR ) ); tplBrokerEntity.getData().setBkrNameText( resultSet_.getString( C_BKR_NAME_TEXT ) ); tplBrokerEntity.getData().setBkrAddrText( resultSet_.getString( C_BKR_ADDR_TEXT ) ); tplBrokerEntity.getData().setBkrBmfMktCode( resultSet_.getString( C_BKR_BMF_MKT_CODE ) ); tplBrokerEntity.getData().setBkrBovespaMktCode( resultSet_.getString( C_BKR_BOVESPA_MKT_CODE ) ); tplBrokerEntity.getData().setBkrRbtBmfRate( resultSet_.getString( C_BKR_RBT_BMF_RATE ) != null ? new BigDecimal( resultSet_.getString( C_BKR_RBT_BMF_RATE ) ) : null ); tplBrokerEntity.getData().setBkrRbtBovespaRate( resultSet_.getString( C_BKR_RBT_BOVESPA_RATE ) != null ? new BigDecimal( resultSet_.getString( C_BKR_RBT_BOVESPA_RATE ) ) : null ); tplBrokerEntity.getData().setBkrReqDate( resultSet_.getDate( C_BKR_REQ_DATE ) ); tplBrokerEntity.getData().setBkrRnwDate( resultSet_.getDate( C_BKR_RNW_DATE ) ); tplBrokerEntity.getData().setBkrApprvStatCode( resultSet_.getString( C_BKR_APPRV_STAT_CODE ) ); tplBrokerEntity.getData().setBkrApprvDate( resultSet_.getDate( C_BKR_APPRV_DATE ) ); tplBrokerEntity.getData().setBkrAuthProcSitText( resultSet_.getString( C_BKR_AUTH_PROC_SIT_TEXT ) ); tplBrokerEntity.getData().setBkrReqCrLimLcyAmt( resultSet_.getString( C_BKR_REQ_CR_LIM_LCY_AMT ) != null ? new BigDecimal( resultSet_.getString( C_BKR_REQ_CR_LIM_LCY_AMT ) ) : null ); tplBrokerEntity.getData().setBkrApprvCrLimLcyAmt( resultSet_.getString( C_BKR_APPRV_CR_LIM_LCY_AMT ) != null ? new BigDecimal( resultSet_.getString( C_BKR_APPRV_CR_LIM_LCY_AMT ) ) : null ); tplBrokerEntity.getData().setBkrReqCrLimDlrAmt( resultSet_.getString( C_BKR_REQ_CR_LIM_DLR_AMT ) != null ? new BigDecimal( resultSet_.getString( C_BKR_REQ_CR_LIM_DLR_AMT ) ) : null ); tplBrokerEntity.getData().setBkrApprvCrLimDlrAmt( resultSet_.getString( C_BKR_APPRV_CR_LIM_DLR_AMT ) != null ? new BigDecimal( resultSet_.getString( C_BKR_APPRV_CR_LIM_DLR_AMT ) ) : null ); tplBrokerEntity.getData().setBkrSuplServText( resultSet_.getString( C_BKR_SUPL_SERV_TEXT ) ); tplBrokerEntity.getData().setBkrCommentText( resultSet_.getString( C_BKR_COMMENT_TEXT ) ); tplBrokerEntity.getData().setLastUpdUserId( resultSet_.getString( C_LAST_UPD_USER_ID ) ); tplBrokerEntity.getData().setLastUpdDate( resultSet_.getDate( C_LAST_UPD_DATE ) ); // Casting para a atribuicao das colunas especificas TplBrokerEntityVO tplBrokerEntityVO = ( TplBrokerEntityVO ) tplBrokerEntity.getData(); tplBrokerEntityVO.setRecStatCode( resultSet_.getString( C_REC_STAT_CODE ) ); tplBrokerEntityVO.setLastAuthDate( resultSet_.getDate( C_LAST_AUTH_DATE ) ); tplBrokerEntityVO.setLastAuthUserId( resultSet_.getString( C_LAST_AUTH_USER_ID ) ); tplBrokerEntities.add( tplBrokerEntity ); } } catch ( SQLException e ) { throw new UnexpectedException( e.getErrorCode(), C_ERROR_INSTANTIATE_FROM_RESULT_SET, e ); } return tplBrokerEntities; } /* * (non-Javadoc) * @see com.citibank.ods.persistence.pl.dao.TplBrokerDAO#existsActive(com.citibank.ods.entity.pl.TplBrokerEntity) */ public boolean existsActive( TplBrokerEntity tplBrokerEntity_ ) throws UnexpectedException { boolean exists = true; try { TplBrokerEntity tplBrokerEntity = ( TplBrokerEntity ) this.find( tplBrokerEntity_ ); TplBrokerEntityVO brokerEntityVO = ( TplBrokerEntityVO ) tplBrokerEntity.getData(); if ( !TplBrokerEntity.C_REC_STAT_CODE_ACTIVE.equals( brokerEntityVO.getRecStatCode() ) ) { exists = false; } } catch ( NoRowsReturnedException exception ) { exists = false; } return exists; } /* * (non-Javadoc) * @see com.citibank.ods.persistence.pl.dao.TplBrokerDAO#exists(com.citibank.ods.entity.pl.TplBrokerEntity) */ public boolean exists( TplBrokerEntity tplBrokerEntity_ ) { boolean exists = true; try { this.find( tplBrokerEntity_ ); } catch ( NoRowsReturnedException exception ) { exists = false; } return exists; } /** * Realiza uma consulta em lista na tabela e cria uma ArrayList de Entities * para ser utilizada */ public ArrayList listForBrokerGrid( String bkrCnpjNbr_, String bkrNameText_ ) { TplBrokerEntity tplBrokerEntity; TplBrokerEntityVO tplBrokerEntityVO; DataSetRow row; ArrayList result = new ArrayList(); DataSet rds = this.list( bkrCnpjNbr_, bkrNameText_ ); for ( int indexRow = 0; indexRow < rds.size(); indexRow++ ) { tplBrokerEntity = new TplBrokerEntity(); tplBrokerEntityVO = ( TplBrokerEntityVO ) tplBrokerEntity.getData(); row = rds.getRow( indexRow ); tplBrokerEntityVO.setBkrCnpjNbr( row.getStringByName( C_BKR_CNPJ_NBR ) ); tplBrokerEntityVO.setBkrNameText( row.getStringByName( C_BKR_NAME_TEXT ) ); tplBrokerEntityVO.setBkrAddrText( row.getStringByName( C_BKR_ADDR_TEXT ) ); result.add( tplBrokerEntity ); } return result; } }
package controller.gerente; import controller.TelaPrincipalController; import entity.Funcionario; import entity.Login; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.Button; import javafx.scene.control.ComboBox; import javafx.scene.control.TextField; import javafx.scene.layout.AnchorPane; public class TelaDemitirFuncionarioController implements Initializable { private TelaPrincipalController telaPrincipalController; @FXML AnchorPane telaDemitirFuncionario; @FXML Button demitirBtn; @FXML ComboBox cpfCombo; @FXML TextField motivoTxt; @Override public void initialize(URL url, ResourceBundle rb) { preencherBoxCPFFuncionario(); } private void preencherBoxCPFFuncionario() { List<String> funcionarios = new ArrayList<>(); for (Object pessoa : Login.usuario.values()) { if (pessoa instanceof Funcionario) { funcionarios.add(((Funcionario) pessoa).getCPF()); } } ObservableList<String> opcoes = FXCollections.observableArrayList(funcionarios); cpfCombo.setItems(opcoes); } private void sair(ActionEvent event) { telaPrincipalController.retornar(); } }
/* ExtendletLoader.java Purpose: Description: History: Wed May 28 17:01:32 2008, Created by tomyeh Copyright (C) 2008 Potix Corporation. All Rights Reserved. {{IS_RIGHT This program is distributed under LGPL Version 2.1 in the hope that it will be useful, but WITHOUT ANY WARRANTY. }}IS_RIGHT */ package org.zkoss.web.util.resource; import java.net.URL; import java.io.InputStream; import org.zkoss.lang.Library; import org.zkoss.lang.Exceptions; import org.zkoss.io.Files; import org.zkoss.util.logging.Log; import org.zkoss.util.resource.Loader; /** * A skeletal implementation of the loader used to implement an extendlet. * All you have to do is to implement {@link #parse} * and {@link #getExtendletContext}. * * <p>If the real path is not the same as the path specified in URL, * you can override {@link #getRealPath}. * * @author tomyeh * @see Extendlet * @since 3.0.6 */ abstract public class ExtendletLoader implements Loader { private static final Log log = Log.lookup(ExtendletLoader.class); private int _checkPeriod; protected ExtendletLoader() { _checkPeriod = getInitCheckPeriod(); } /** Returns the real path for the specified path. * * <p>Default: return path, i.e., the path specified in URL is * the real path. * * <p>Notice that {@link #parse} will receive the original path * (rather than the returned path). * * @param path the path specified in URL. * Notice that it does NOT start with "~./". Rather it starts with * "/". For example, "/zul/css/zk.wcs". * @since 5.0.0 */ protected String getRealPath(String path) { return path; } //Loader// public boolean shallCheck(Object src, long expiredMillis) { return expiredMillis > 0; } /** Returns the last modified time. */ public long getLastModified(Object src) { if (getCheckPeriod() < 0) return 1; //any value (because it is not dynamic) try { final URL url = getExtendletContext().getResource((String)src); if (url != null) { final long v = url.openConnection().getLastModified(); return v != -1 ? v: 0; //not to reload (5.0.6 for better performance) } } catch (Throwable ex) { } return -1; //reload (might be removed) } public Object load(Object src) throws Exception { // if (D.ON && log.debugable()) log.debug("Parse "+src); final String path = getRealPath((String)src); InputStream is = null; if (getCheckPeriod() >= 0) { //Due to Web server might cache the result, we use URL if possible try { URL real = getExtendletContext().getResource(path); if (real != null) is = real.openStream(); } catch (Throwable ex) { log.warningBriefly("Unable to read from URL: "+path, ex); } } if (is == null) { is = getExtendletContext().getResourceAsStream(path); if (is == null) return null; } try { return parse(is, path, (String)src); } catch (Throwable ex) { log.realCauseBriefly("Failed to parse "+src, ex); return null; //as non-existent } finally { Files.close(is); } } //Derive to override// /** It is called to parse the resource into an intermediate format * depending on {@link Extendlet}. * * <p>The object is returned directly by {@link #load}, so * you can return an instance of org.zkoss.util.resource.Loader.Resource * to have more control on {@link org.zkoss.util.resource.ResourceCache}. * * @param is the content of the resource * @param path the path of the resource. * It is the value returned by {@link #getRealPath}, so called * the real path * @param orgpath the original path. * It is the path passed to the <code>path</code> argument * of {@link #getRealPath}. It is useful if you want to retrieve * the additional information encoded into the URI. * @since 5.0.0 */ abstract protected Object parse(InputStream is, String path, String orgpath) throws Exception; /** Returns the extendlet context. */ abstract protected ExtendletContext getExtendletContext(); /** Returns the check period, or -1 if the content is never changed. * Unit: milliseconds. * * <p>Default: It checks if an integer (unit: second) is assigned * to a system property called org.zkoss.util.resource.extendlet.checkPeriod. * If no such system property, -1 is assumed (never change). * For the runtime environment the content is never changed, * since all extendlet resources are packed in JAR files. */ public int getCheckPeriod() { return _checkPeriod; } private static int getInitCheckPeriod() { final int v = Library.getIntProperty("org.zkoss.util.resource.extendlet.checkPeriod", -1); return v > 0 ? v * 1000: v; } }
package slimeknights.tconstruct.plugin.jei.alloy; import java.util.List; import javax.annotation.Nonnull; import com.google.common.collect.ImmutableList; import mezz.jei.api.IGuiHelper; import mezz.jei.api.gui.IDrawable; import mezz.jei.api.gui.IDrawableAnimated; import mezz.jei.api.gui.IDrawableStatic; import mezz.jei.api.gui.IGuiFluidStackGroup; import mezz.jei.api.gui.IRecipeLayout; import mezz.jei.api.ingredients.IIngredients; import mezz.jei.api.recipe.IRecipeCategory; import net.minecraft.client.Minecraft; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fluids.FluidStack; import slimeknights.tconstruct.TConstruct; import slimeknights.tconstruct.library.Util; public class AlloyRecipeCategory implements IRecipeCategory<AlloyRecipeWrapper> { public static String CATEGORY = Util.prefix("alloy"); public static ResourceLocation background_loc = Util.getResource("textures/gui/jei/smeltery.png"); protected final IDrawable background; protected final IDrawableAnimated arrow; public AlloyRecipeCategory(IGuiHelper guiHelper) { background = guiHelper.createDrawable(background_loc, 0, 60, 160, 60); IDrawableStatic arrowDrawable = guiHelper.createDrawable(background_loc, 160, 60, 24, 17); this.arrow = guiHelper.createAnimatedDrawable(arrowDrawable, 200, IDrawableAnimated.StartDirection.LEFT, false); } @Nonnull @Override public String getUid() { return CATEGORY; } @Nonnull @Override public String getTitle() { return Util.translate("gui.jei.alloy.title"); } @Nonnull @Override public IDrawable getBackground() { return background; } @Override public void drawExtras(@Nonnull Minecraft minecraft) { arrow.draw(minecraft, 76, 22); } @Override public void setRecipe(IRecipeLayout recipeLayout, AlloyRecipeWrapper recipe, IIngredients ingredients) { IGuiFluidStackGroup fluids = recipeLayout.getFluidStacks(); List<FluidStack> inputs = recipe.inputs; List<FluidStack> outputs = ingredients.getOutputs(FluidStack.class).get(0); float w = 36f / inputs.size(); // find maximum used amount in the recipe so relations are correct int max_amount = 0; for(FluidStack fs : inputs) { if(fs.amount > max_amount) { max_amount = fs.amount; } } for(FluidStack fs : outputs) { if(fs.amount > max_amount) { max_amount = fs.amount; } } // inputs for(int i = 0; i < inputs.size(); i++) { int x = 21 + (int) (i * w); int _w = (int) ((i + 1) * w - i * w); fluids.init(i + 1, true, x, 11, _w, 32, max_amount, false, null); } // output fluids.init(0, false, 118, 11, 18, 32, max_amount, false, null); fluids.set(ingredients); } @Override public List<String> getTooltipStrings(int mouseX, int mouseY) { return ImmutableList.of(); } @Override public IDrawable getIcon() { // use the default icon return null; } @Override public String getModName() { return TConstruct.modName; } }
package com.itheima.bos.web.action; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import java.util.List; import java.util.zip.ZipInputStream; import javax.annotation.Resource; import org.activiti.engine.ProcessEngine; import org.activiti.engine.repository.DeploymentBuilder; import org.activiti.engine.repository.ProcessDefinition; import org.activiti.engine.repository.ProcessDefinitionQuery; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import com.opensymphony.xwork2.ActionChainResult; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; /** * 流程定义管理Action * * @author zhaoqx * */ @Controller @Scope("prototype") public class ProcessDefinitionAction extends ActionSupport { @Resource private ProcessEngine processEngine; /** * 查询最新版本的流程定义列表数据 */ public String list() { ProcessDefinitionQuery query = processEngine.getRepositoryService() .createProcessDefinitionQuery(); query.latestVersion(); List<ProcessDefinition> list = query.list(); // 压栈 ActionContext.getContext().getValueStack().set("list", list); return "list"; } // 接收上传的文件 private File deploy;// zip文件 /** * 部署流程定义 * * @throws Exception */ public String deploy() throws Exception { DeploymentBuilder deploymentBuilder = processEngine .getRepositoryService().createDeployment(); ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream( deploy)); deploymentBuilder.addZipInputStream(zipInputStream); deploymentBuilder.deploy(); return "toList"; } public void setDeploy(File deploy) { this.deploy = deploy; } //接收流程定义ID private String pdId; /** * 查看png图片 */ public String showpng(){ //processEngine.getRepositoryService().getResourceAsStream(deploymentId, resourceName); InputStream pngStream = processEngine.getRepositoryService().getProcessDiagram(pdId); ActionContext.getContext().getValueStack().set("pngStream", pngStream); //使用struts2的文件下载功能展示png图片 return "showpng"; } public void setPdId(String pdId) { this.pdId = pdId; } }
package implementation; import java.util.ArrayList; import java.util.HashSet; import java.util.Objects; /** * Represents a single course offered by ACU. Maintains data for * <ul> * <li>course subject</li> * <li>course number</li> * <li>course title</li> * <li>prerequisite list</li> * <li>student set</li> * </ul> * * <p> * Instances of CourseDescription will also contain a subject and number, * by which Courses may look up data from their coresponding CourseDescription. * </p> * * @author Kevin Shurtz * @version 1.0 */ public class CourseDescription { // Course characteristics private String courseSubject; // Course subject (BIBL, CS, IT, etc.) private String courseNumber; // Course number (101, 102, etc.) private String courseTitle; // Course title (without number) private ArrayList<Prereq> prereqsNeeded; // List of prereqs needed for a certain class private HashSet<Student> students; // Set of students in course history /** * Constructs a Course object to represent a student's course. Course * delegates the instantiation of instance variables to method setCourse. * * @param subject course subject, such as 'BIBL', 'CS', 'IT', etc * @param title course title, such as 'Software Engineering', 'Networking', etc * @param courseNum course number, such as 220, 221, etc * @throws IllegalArgumentException If one of the arguements provided * was unacceptable * @see CourseDescription#setCourseDescription(int, String, int, String) */ public CourseDescription(String subject, String courseNum, String title) { setCourseDescription(subject, courseNum, title); prereqsNeeded = new ArrayList<Prereq>(); // instantiate prerequisite list students = new HashSet<Student>(); // instantiate student list } /** * Assigns values to CourseDescription instance variables. The function * delegates assignment to each of the assignment functions * for each instance variable, many of which validate the input. * * @param crnNum course registration number * @param subject course subject, such as 'BIBL', 'CS', 'IT', etc * @param title course title, such as 'Software Engineering', 'Networking', etc * @param courseNum course number, such as 220, 221, etc * @throws IllegalArgumentException If one of the arguements provided * was unacceptable */ public void setCourseDescription(String subject, String courseNum, String title) { setCourseSubject(subject); // Assign subject setCourseNumber(courseNum); // Assign course number setCourseTitle(title); // Assign title } /** * Adds a Prereq to CourseDescriptions's List of Prereqs. * * @param prerequisite a course prerequisite */ public void addPrereq(Prereq prerequisite) { prereqsNeeded.add(prerequisite); } /** * Adds a student to CourseDescription's Set of Students. * * @param student a student that has taken the CourseDescription's course */ public void addStudent(Student student) { students.add(student); } /** * Assigns the course subject. No validation is conducted on the string, * but typically a course subject is fully capitalized, and no longer * than four characters. * * @param subject course subject, such as BIBL, CS, IT, etc */ public void setCourseSubject(String subject) { courseSubject = subject; } /** * Assigns the course number. Examples include 101, 102, 374, etc. Extensions to * course numbers, like 'H1' in '101.H1', are not stored in this field. Rather, * extensions are stored as a String in setCourseNumberExt. If a course number * does not consist of three digits, an exception is thrown. * * @param courseNum course number * @throws IllegalArgumentException If the course number is not three digits * @see Course#setCourseNumberExt(String) */ public void setCourseNumber(String courseNum) { if (courseNum.length() != 3) throw new IllegalArgumentException("Course number is not three digits"); courseNumber = courseNum; } /** * Assigns the course title. No validation is conducted. The title is not * to include the course's number, or other identifying information. * * @param title the title of the course, such as 'Software Engineering', or 'Networking' */ public void setCourseTitle(String title) { courseTitle = title; } /** * Returns the course subject. The course subject is output in an abbreviated format such * as 'BIBL', 'CS', 'IT', etc. * * @return the course subject */ public String getCourseSubject() { return courseSubject; } /** * Returns the course number. * * @return the course number */ public String getCourseNumber() { return courseNumber; } /** * Returns the course title. * * @return the course title */ public String getCourseTitle() { return courseTitle; } /** * Returns a deeply copied ArrayList of Prereqs. * * @return a copy of the Prereq list for the CourseDescription */ public ArrayList<Prereq> getPrereqList() { // deep copy and return ArrayList<Prereq> prereqList = new ArrayList<Prereq>(); for (Prereq prerequisite : prereqsNeeded) { // Note: While Strings are objects, they are immutable; this works for a deep copy String subject = prerequisite.getPrereqSubject(); String number = prerequisite.getPrereqNumber(); String title = prerequisite.getPrereqTitle(); String grade = prerequisite.getPrereqGrade(); prereqList.add(new Prereq(subject, number, title, grade)); } return prereqList; } /** * Returns a deeply copied HashSet of Students. * * @return a copy of the Student set for the CourseDescription */ public HashSet<Student> getStudentSet() { // deep copy and return HashSet<Student> studentSet = new HashSet<Student>(); for (Student student : students) { // Note: While Strings are objects, they are immutable; this works for a deep copy int bannerID = student.getStudentBannerID(); String section = student.getStudentSection(); int year = student.getStudentYear(); Term term = student.getStudentTerm(); String grade = student.getStudentGrade(); boolean now = student.isTakingNow(); studentSet.add(new Student(bannerID, section, year, term, grade, now)); } return studentSet; } /** * Returns a deeply copied HashSet of Students currently in the course. * * @return a copy of the Student set for the CourseDescription for all current students */ public HashSet<Student> getCurrentStudentSet() { // deep copy and return HashSet<Student> studentSet = new HashSet<Student>(); for (Student student : students) { // Note: While Strings are objects, they are immutable; this works for a deep copy int bannerID = student.getStudentBannerID(); String section = student.getStudentSection(); int year = student.getStudentYear(); Term term = student.getStudentTerm(); String grade = student.getStudentGrade(); boolean now = student.isTakingNow(); // If the student is current if (year == DataModule.currentYear && term == DataModule.currentTerm) studentSet.add(new Student(bannerID, section, year, term, grade, now)); } return studentSet; } /** * Determines if the CourseDescription is equal to another CourseDescripion or Course. * This function delegates the equals operation to one of the two private equals * functions in CourseDescription. * * @param other either a CourseDescription or Course object * @return whether the CourseDescription is equal to the other object */ @Override public boolean equals(Object other) { if (other == null) return false; if (other == this) return true; if (other instanceof CourseDescription) return equals((CourseDescription)other); if (other instanceof Course) return equals((Course)other); return false; } /** * Checks if two CourseDescription objects are equal. * * @param other the other CourseDescription object * @return whether or not the CourseDescription objects are identical */ private boolean equals(CourseDescription other) { if (other == null) return false; if (!getCourseSubject().equals(other.getCourseSubject())) return false; if (!getCourseNumber().equals(other.getCourseNumber())) return false; return true; } /** * Checks if a Course object is represented by a CourseDescription object. * * @param other the Course object looking up the appropriate CourseDescription object * @return whether or not the Course object is represetned by the CourseDescription object */ private boolean equals(Course other) { if (other == null) return false; if (!courseSubject.equals(other.getCourseSubject())) return false; if (!courseNumber.equals(other.getCourseNumber())) return false; return true; } /** * Returns a hash for CourseDescription. The hash utilizes the Objects library * hash function, and uses the course subject and number to generate the hash. * * Course should hash to the same value. * * @return a hash for CourseDescription */ @Override public int hashCode() { return Objects.hash(getCourseSubject(), getCourseNumber()); } }
package com.xcl.service.Impl; import com.xcl.entity.Cart; import com.xcl.repository.CartRepository; import com.xcl.service.CartService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class CartImpl implements CartService { @Autowired private CartRepository cartRepository; @Override public void add(Cart cart) { cartRepository.add(cart); } @Override public List<Cart> findAllByUserId(Integer userid) { return cartRepository.findAllByUserId(userid); } @Override public void updateCart(Integer id, Integer quantity, Double cost) { cartRepository.updateCart(id,quantity,cost); } @Override public void deleteById(Integer id) { cartRepository.deleteById(id); } }
import desmoj.core.simulator.Model; import desmoj.core.simulator.SimProcess; import desmoj.core.simulator.TimeSpan; import java.util.concurrent.TimeUnit; /** * Created by Pedro on 20/04/2015. */ public class AGV extends SimProcess { Modelo modelo; double speed; int currentposition; public AGV(Model model, String s, boolean b) { super(model, s, b); modelo = (Modelo)model; currentposition = Modelo.STATION; speed = 2.5; } @Override public void lifeCycle() { while(true){ if(modelo.jobqueue.isEmpty()){ if(Modelo.returnstobase){ double distance = Modelo.distances[currentposition][Modelo.STATION]; double time = distance/speed; sendTraceNote("MOVing to station"); hold(new TimeSpan(time, TimeUnit.SECONDS)); } modelo.agvqueue.insert(this); passivate(); } else{ Job job = modelo.jobqueue.first(); modelo.jobqueue.remove(job); double distance = Modelo.distances[currentposition][job.getCurrentPosition()]; double time = distance/ speed; sendTraceNote("Going from " + currentposition + "to " + job.getCurrentPosition()); hold(new TimeSpan(time, TimeUnit.SECONDS)); //Mover-se para a posição do job currentposition = job.getCurrentPosition(); if(job.getCurrentPosition()!=Modelo.STATION){ modelo.estacao[job.getCurrentPosition()].desoccupy(job); modelo.estacao[job.getCurrentPosition()].blockedtime+= presentTime().getTimeAsDouble() - modelo.estacao[job.getCurrentPosition()].startedblocking; if(!modelo.estacao[job.getCurrentPosition()].iswaitlineempty()) { Job job1 = modelo.estacao[job.getCurrentPosition()].getFirstJobWaiting(); sendTraceNote("Chegou a queue a " + presentTime()+ " e saiu a " + job1.arrivalinqueue + "Demorou " + (presentTime().getTimeAsDouble()-job1.arrivalinqueue)); job1.timeinqueue+=presentTime().getTimeAsDouble() - job1.arrivalinqueue; if(modelo.estacao[job.getCurrentPosition()].occupy(job1)){ job1.activate(); } } } sendTraceNote(" TAKING " + job + " from " + currentposition + " to " + job.getNextPosition()); job.move(); distance = Modelo.distances[currentposition][job.getCurrentPosition()]; time = distance/speed; job.totaltimeinagv+=time; sendTraceNote(""+time); currentposition = job.getCurrentPosition(); hold(new TimeSpan(time,TimeUnit.SECONDS)); //Levar Job para a proxima posição if(job.getCurrentPosition()!=Modelo.STATION) { if (modelo.estacao[currentposition].occupy(job)) { job.activate(); } else { modelo.estacao[currentposition].wait(job); job.arrivalinqueue = presentTime().getTimeAsDouble(); } } else{ job.activate(); } } } } }
package nl.kasperschipper.alligatorithm.services.impl; import nl.kasperschipper.alligatorithm.services.BinaryDataReader; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.ArrayUtils; import org.springframework.core.io.ClassPathResource; import org.springframework.stereotype.Service; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @Service public class BinaryDataReaderImpl implements BinaryDataReader { @Override public List<Byte> readBinaryDataFromFile(String filePath) { try (InputStream file = new ClassPathResource(filePath).getInputStream()) { byte[] bytes = IOUtils.toByteArray(file); Byte[] boxedBytes = ArrayUtils.toObject(bytes); List<Byte> inputBytesList = Arrays.asList(boxedBytes); return inputBytesList; } catch (IOException e) { throw new RuntimeException(e); // crash app for now, ideally would want to do proper error handling given time } } }
package selenium.basics.webdriver; import java.util.List; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.chrome.ChromeDriverService; public class JavaScriptDemo { public static void main(String[] args) { String chromeDriverPath = System.getProperty("user.dir") + "//drivers/chromedriver.exe"; System.setProperty(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY, chromeDriverPath); WebDriver driver = new ChromeDriver(); JavascriptExecutor js = ((JavascriptExecutor) driver); // driver.get('https://www.wikipedia.com') // javascript to launch the url js.executeScript("window.location = 'https://www.wikipedia.com';"); String jsTitle = (String) js.executeScript("return document.title"); System.out.println(driver.getTitle() + "\tjavscript title " + jsTitle); String jsURL = (String) js.executeScript("return document.URL"); System.out.println(driver.getCurrentUrl() + "using selenium" + "\t using javscript url " + jsURL); String jsReadyState = (String) js.executeScript("return document.readyState"); List<Object> jsAllLinks = (List<Object>) js.executeScript("return document.links"); System.out.println("jsURL:" + jsURL + "\tjsReadyState: " + jsReadyState); System.out.println("Total jsAllLinks: " + jsAllLinks.size()); //create alert using js js.executeScript("window.window.alert('Hey, I am using js.executescript() to create this alert during testcase execution');"); } }
package com.example.authexample; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.http.client.HttpResponseException; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpDelete; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Toast; import com.savagelook.android.UrlJsonAsyncTask; public class HomeActivity extends Activity { private static final String TASKS_URL = Constants.SERVER_URL+"api/v1/tasks.json"; private SharedPreferences mPreferences; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); mPreferences = getSharedPreferences("CurrentUser", MODE_PRIVATE); //loadTasksFromAPI(TASKS_URL); } private void loadTasksFromAPI(String url) { GetTasksTask getTasksTask = new GetTasksTask(HomeActivity.this); getTasksTask.setMessageLoading("Loading tasks..."); //getTasksTask.execute(url); getTasksTask.execute(url + "?auth_token=" + mPreferences.getString("AuthToken", "")); } private class GetTasksTask extends UrlJsonAsyncTask { public GetTasksTask(Context context) { super(context); } @Override protected void onPostExecute(JSONObject json) { try { //display json string Toast.makeText(getApplicationContext(), json.toString(), Toast.LENGTH_LONG).show(); if(!json.getBoolean("success")) { // Toast.makeText(context, json.getString("info"),Toast.LENGTH_LONG).show(); // Toast.makeText(context, "Server not found",Toast.LENGTH_LONG).show(); return; } JSONArray jsonTasks = json.getJSONObject("data").getJSONArray("tasks"); int length = jsonTasks.length(); List<String> tasksTitles = new ArrayList<String>(length); for (int i = 0; i < length; i++) { tasksTitles.add(jsonTasks.getJSONObject(i).getString("title")); } ListView tasksListView = (ListView) findViewById (R.id.tasks_list_view); if (tasksListView != null) { tasksListView.setAdapter(new ArrayAdapter<String>(HomeActivity.this, android.R.layout.simple_list_item_1, tasksTitles)); } } catch (Exception e) { Toast.makeText(context, e.getMessage(),Toast.LENGTH_LONG).show(); } finally { super.onPostExecute(json); } } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.home, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.menu_logout: logout(); return true; case R.id.menu_refresh: loadTasksFromAPI(TASKS_URL); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onResume() { super.onResume(); if (mPreferences.contains("AuthToken")) { loadTasksFromAPI(TASKS_URL); } else { Intent intent = new Intent(HomeActivity.this, WelcomeActivity.class); startActivityForResult(intent, 0); } } // public void logout(View button) { // LogoutTask logoutTask = new LogoutTask(LogoutActivity.this); // logoutTask.setMessageLoading("Logging in..."); // logoutTask.execute(LOGIN_API_ENDPOINT_URL); // } private final static String LOGOUT_API_ENDPOINT_URL = Constants.SERVER_URL+"api/v1/sessions"; public void logout() { LogoutTask logoutTask = new LogoutTask(HomeActivity.this); logoutTask.setMessageLoading("Logging out..."); logoutTask.execute(LOGOUT_API_ENDPOINT_URL); } private class LogoutTask extends UrlJsonAsyncTask { public LogoutTask(Context context) { super(context); } @Override protected JSONObject doInBackground(String... urls) { DefaultHttpClient client = new DefaultHttpClient(); String authtoken=mPreferences.getString("AuthToken", ""); HttpDelete post = new HttpDelete(urls[0]+"?auth_token="+authtoken+""); String response = null; JSONObject json = new JSONObject(); try { try { // setup the returned values beforehand, // in case something goes wrong json.put("success", false); json.put("info", "Server not found"); // add the user email and password to // the params // userObj.put("email", mUserEmail); // userObj.put("password", mUserPassword); // holder.put("user", userObj); // StringEntity se = new StringEntity(holder.toString()); // post.setEntity(se); // setup the request headers post.setHeader("Accept", "application/json"); post.setHeader("Content-Type", "application/json"); // Toast.makeText(context, post.toString(),Toast.LENGTH_LONG).show(); Log.e("ClientProtocol Post", post.getURI().toString()); ResponseHandler<String> responseHandler = new BasicResponseHandler(); response = client.execute(post, responseHandler); json = new JSONObject(response); } catch (HttpResponseException e) { Log.e("ClientProtocol JSON", json.toString()); e.printStackTrace(); Log.e("ClientProtocol", "" + e); json.put("info", "HttpResponseException"); } catch (IOException e) { e.printStackTrace(); Log.e("IO", "" + e); } } catch (JSONException e) { e.printStackTrace(); Log.e("JSON", "" + e); } return json; } @Override protected void onPostExecute(JSONObject json) { try { //display json string Toast.makeText(getApplicationContext(), json.toString(), Toast.LENGTH_LONG).show(); if (json.getBoolean("success")) { // everything is ok mPreferences.edit().remove("AuthToken").commit(); // launch the HomeActivity and close this one Intent intent = new Intent(getApplicationContext(), WelcomeActivity.class); startActivityForResult(intent, 0); //finish(); } Toast.makeText(context, json.getString("info"), Toast.LENGTH_LONG).show(); } catch (Exception e) { // something went wrong: show a Toast // with the exception message Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show(); } finally { super.onPostExecute(json); } } } }
public class SameTree { /** * Returns if two trees are exactly same */ class TreeNode { TreeNode left; TreeNode right; int val; TreeNode(int val) { val = val; } } public boolean isSameTree(TreeNode p, TreeNode q) { if (p == null && q == null) return true; if (p == null || q == null) return false; if (p.val != q.val) return false; return ((isSameTree(p.right, q.right)) && (isSameTree(p.left, q.left))); } /** * Basic checks, nothing serious here. */ }
package p14; import java.util.ArrayList; import java.util.Random; public class Excute { public static void main(String[] args) { MapExam me = new MapExam(); ArrayList<MapExam> alMap = new ArrayList<MapExam>(); Random rand = new Random(); for (int i = 0; i < 10; i++) { me=new MapExam(); me.put("name", "" + i); me.put("age", "" + (rand.nextInt(100) + 1)); alMap.add(me); } for(MapExam me2:alMap) { System.out.println(me2); } } }
package com.zhicai.byteera.activity.knowwealth.presenter; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.util.Log; import com.google.protobuf.InvalidProtocolBufferException; import com.zhicai.byteera.MyApp; import com.zhicai.byteera.activity.bean.BannerEntity; import com.zhicai.byteera.activity.bean.Consult; import com.zhicai.byteera.activity.knowwealth.view.KnowWealthDetailActivity; import com.zhicai.byteera.activity.knowwealth.view.KnowWealthDetailCommentActivity2; import com.zhicai.byteera.activity.knowwealth.viewinterface.KnowWealthIV; import com.zhicai.byteera.commonutil.ActivityUtil; import com.zhicai.byteera.commonutil.Constants; import com.zhicai.byteera.service.Common; import com.zhicai.byteera.service.information.Information; import com.zhicai.byteera.service.serversdk.BaseHandlerClass; import com.zhicai.byteera.service.serversdk.TiangongClient; import java.util.ArrayList; import java.util.List; /** Created by bing on 2015/6/27. */ public class KnowWealthPre { private KnowWealthIV knowWealthIV; private Context mContext; private List<Information.Zixun> zixunList; private String pageLastZiXunId; public KnowWealthPre(KnowWealthIV knowWealthIV) { this.knowWealthIV = knowWealthIV; zixunList = new ArrayList<>(); } public void setContext() { this.mContext = knowWealthIV.getContext(); } public void intentToKnowWealthDetailActivity(Consult item) { Intent intent = new Intent(mContext, KnowWealthDetailActivity.class); intent.putExtra("zixun_id", item.getZiXunId()); intent.putExtra("title", item.getTitle()); intent.putExtra("imgUrl", item.getAvatarUrl()); ActivityUtil.startActivity((Activity) mContext, intent); } public void getData(final int value) { Information.MainPageReq page; if (pageLastZiXunId != null) { page = Information.MainPageReq.newBuilder().setProductType(Common.ProductType.valueOf(value)).setZixunId(pageLastZiXunId).setIsafter(0).build(); } else { page = Information.MainPageReq.newBuilder().setProductType(Common.ProductType.valueOf(value)).setIsafter(0).build(); } TiangongClient.instance().send("chronos", "get_main_page", page.toByteArray(), new BaseHandlerClass() { public void onSuccess(byte[] buffer) { try { final Information.MainPage data = Information.MainPage.parseFrom(buffer); Log.d("KnowWealthPre", "res-->" + data.toString() + ",type-->" + value); MyApp.getMainThreadHandler().post(new Runnable() { @Override public void run() { if (data.getErrorno() == 0) { if (pageLastZiXunId == null) knowWealthIV.removeAllViews(); if (value == Constants.ZHICAI_ALL) loadZHICAI_ALL(data); if (data.getZixunCount() > 0) loadMore(data); knowWealthIV.notifyDataSetChanged(); } knowWealthIV.loadComplete(); knowWealthIV.refreshFinish(); } }); } catch (InvalidProtocolBufferException e) { e.printStackTrace(); } } }); } private void loadZHICAI_ALL(Information.MainPage data) { List<BannerEntity> bannerList = new ArrayList<>(); for (int i = 0; i < data.getMainImageList().size(); i++) { Information.ADImg adImg = data.getMainImageList().get(i); BannerEntity bannerEntity = new BannerEntity(adImg.getImageUrl(), adImg.getJumpPoint().getNumber(), adImg.getJumpUrl()); bannerList.add(bannerEntity); } if (pageLastZiXunId == null && data.getZixunCount() > 0) knowWealthIV.addItem(bannerList); } private void loadMore(Information.MainPage data) { List<Information.Zixun> dataZixunList = data.getZixunList(); if (pageLastZiXunId == null) KnowWealthPre.this.zixunList.clear(); KnowWealthPre.this.zixunList.addAll(dataZixunList); for (int i = 0; i < dataZixunList.size(); i++) { Information.Zixun zixun = dataZixunList.get(i); Consult consult = new Consult(zixun.getImageUrl(), zixun.getZixunId(), zixun.getTitle(), zixun.getCommentTimes(), zixun.getPublishTime(), zixun.getProductType()); knowWealthIV.addItem(consult); pageLastZiXunId = dataZixunList.get(data.getZixunCount() - 1).getZixunId(); } } public void intenttoComment(Consult consult) { Intent intent = new Intent(mContext, KnowWealthDetailCommentActivity2.class); intent.putExtra("zixun_id", consult.getZiXunId()); ActivityUtil.startActivity((Activity) mContext, intent); } }
package Service.impl; import DO.Request.LuckMoneyArg; import DO.Request.LuckMoneyDetailArg; import DO.Response.LuckMoneyDetailResult; import DO.Response.LuckMoneyResult; import Manager.LuckMoneyManager; import Manager.PayManager; import Service.LuckMoneyService; /** * Created by zhaoyf * 2015/12/4 */ public class LuckMoneyServiceImpl implements LuckMoneyService{ private LuckMoneyManager luckMoneyManager; private PayManager payManager; public LuckMoneyResult createLuckMoney(LuckMoneyArg luckMoneyArg) { // 1 基本参数校验 // 1.1 用户信息是否正确 // 1.2 金额、数目是否合法 // 1.3 支付密码是否正确 // 1.4 如果是余额支付,判断用户余额是否足够。如果不是,直接跳过 // 2 调用支付系统冻结用户资金 // 3 冻结成功,更新订单号到DB // 4 按照红包类型计算金额,拆完,刷新记录到DB // 5 更新红包信息到Redis // 6 按照红包类型发送消息到企信(部门红包),其他的不需要 // 7 返回成功给用户 return null; } public LuckMoneyDetailResult grabLuckMoneyDetail(LuckMoneyDetailArg luckMoneyDetailArg) { // 1 redis 查询该用户是否可以抢 // 2 可以就继续,不可以就返回红包详情 // 3 redis查询该人是否抢过 // 4 有结果,返回结果 // 5. redis查询是否还有红包遗留 // 5.1 无红包,提示抢完了 // 5.2 有红包,开抢 // 6 抢到红包 // 7 更新成功,返回 // 8 // 9 // 10 // 11 // 12 // 13 return null; } public LuckMoneyDetailResult getLuckMoneyDetail(LuckMoneyDetailArg luckMoneyDetailArg) { // 1 基本参数校验 // 2 只有抢过的人和红包发放的人才可以看详情 // 3 按照翻页参数查询数据 // 4 返回结果 return null; } public LuckMoneyDetailResult tksLuckMoneyDetail(LuckMoneyDetailArg luckMoneyDetailArg) { return null; } }
package com.esum.web.ims.etx.dao; import java.util.HashMap; import java.util.List; import java.util.Map; import com.esum.appetizer.dao.AbstractDao; import com.esum.appetizer.util.PageUtil; import com.esum.web.ims.etx.vo.Mspool; public class MspoolDao extends AbstractDao { public Mspool select(String mspMsgid, String mspWhichstd, String mspApmsgid, String mspVersion, String mspCtlagnc, String mspRelease, String mspFuncode) { Map<String, Object> param = new HashMap<String, Object>(); param.put("mspMsgid", mspMsgid); param.put("mspWhichstd", mspWhichstd); param.put("mspApmsgid", mspApmsgid); param.put("mspVersion", mspVersion); param.put("mspCtlagnc", mspCtlagnc); param.put("mspRelease", mspRelease); param.put("mspFuncode", mspFuncode); return getSqlSession().selectOne("mspool.select", param); } public List<Mspool> selectList(String mspMsgid, String mspWhichstd, String mspApmsgid, PageUtil pageUtil) { Map<String, Object> param = new HashMap<String, Object>(); param.put("mspMsgid", mspMsgid); // escape for LIKE param.put("mspWhichstd", mspWhichstd); param.put("mspApmsgid", mspApmsgid); param.put("startRow", pageUtil.getStartRow()); param.put("endRow", pageUtil.getEndRow()); return getSqlSession().selectList("mspool.selectPageList", param); } public int countList(String mspMsgid, String mspWhichstd, String mspApmsgid) { Map<String, Object> param = new HashMap<String, Object>(); param.put("mspMsgid", mspMsgid); // escape for LIKE param.put("mspWhichstd", mspWhichstd); param.put("mspApmsgid", mspApmsgid); return (Integer)getSqlSession().selectOne("mspool.countList", param); } public int insert(Mspool vo) { return getSqlSession().insert("mspool.insert", vo); } public int update(Mspool vo) { return getSqlSession().update("mspool.update", vo); } public int delete(Mspool vo) { return getSqlSession().delete("mspool.delete", vo); } }
package com.larryhsiao.nyx.core.jots; import com.larryhsiao.nyx.core.jots.ConstJot; import com.larryhsiao.nyx.core.jots.JotUri; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Unit-test for the class {@link JotUri} */ public class JotUriTest { /** * Check simple output. */ @Test public void simple() { assertEquals( "http://localhost.com/jots/1", new JotUri( "http://localhost.com/", new ConstJot( 1, "content", 0, new double[]{}, "", 1, false) ).value().toASCIIString() ); } }
package com.frontlinerlzx.tmall_lzx.dao; import com.frontlinerlzx.tmall_lzx.pojo.User; import org.springframework.data.jpa.repository.JpaRepository; /** * @author lzx * @create 2019-08-31-10:23 */ public interface UserDao extends JpaRepository<User, Integer> { User findByName(String name); }
package com.SearchHouse.service.impl; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.SearchHouse.mapper.HouseMapper; import com.SearchHouse.mapper.PhotoMapper; import com.SearchHouse.mapper.PriceContainsMapper; import com.SearchHouse.pojo.House; import com.SearchHouse.pojo.Photo; import com.SearchHouse.pojo.PriceContain; import com.SearchHouse.pojo.ShaiXuan; import com.SearchHouse.service.HouseInfoService; @Service @Transactional public class HouseInfoServiceImpl implements HouseInfoService { @Resource HouseMapper houseMapper; @Resource PhotoMapper photoMapper; @Resource PriceContainsMapper priceContainsMapper; public PriceContainsMapper getPriceContainsMapper() { return priceContainsMapper; } public void setPriceContainsMapper(PriceContainsMapper priceContainsMapper) { this.priceContainsMapper = priceContainsMapper; } public PhotoMapper getPhotoMapper() { return photoMapper; } public void setPhotoMapper(PhotoMapper photoMapper) { this.photoMapper = photoMapper; } public HouseMapper getHouseMapper() { return houseMapper; } public void setHouseMapper(HouseMapper houseMapper) { this.houseMapper = houseMapper; } @Override public void addHouse(House house) { // TODO Auto-generated method stub houseMapper.addHouse(house); Integer houseId = house.getHouseId(); List<String> photos = house.getPhotos(); List<String> priceContains = house.getPriceContains(); for (String photoName : photos) { photoMapper.addPhoto(new Photo(null, photoName, houseId)); } for (Integer i = 0; i < priceContains.size(); i++) { priceContainsMapper.addPri(new PriceContain(houseId, priceContains.get(i), i)); } } @Override public void deleteHouse(int houseId) { // TODO Auto-generated method stub houseMapper.deleteHouse(houseId); } @Override public void uodateHouse(House house) { // TODO Auto-generated method stub houseMapper.updateHouse(house); } @Override public House getHouseById(int houseId) { // TODO Auto-generated method stub return houseMapper.getHouseById(houseId); } @Override public List<House> getAllHouses() { // TODO Auto-generated method stub return houseMapper.getAllHouses(); } @Override public List<House> getHouseByType(Integer number) { return houseMapper.getHouseByType(number); } @Override public List<House> getHouseByKeyAll(String keyName) { // TODO Auto-generated method stub return houseMapper.getHouseByKeyAll(keyName); } @Override public List<House> getHouseByKey(String keyName, Integer number) { // TODO Auto-generated method stub return houseMapper.getHouseByKey(keyName, number); } @Override public List<House> getHouseByTypeAll() { // TODO Auto-generated method stub return houseMapper.getHouseByTypeAll(); } @Override public List<House> getByType() { return houseMapper.getByType(); } @Override public List<House> getHouseByNum(Integer number) { return houseMapper.getHouseByNum(number); } @Override public List<House> getHouseByUserID(String userId) { // TODO Auto-generated method stub return houseMapper.getHouseByUserID(userId); } @Override public List<House> getHouseMoHuAll(ShaiXuan shaiXuan) { // TODO Auto-generated method stub return houseMapper.getHouseMoHuAll(shaiXuan); } }
package tarea19; public class NoMainDarly { public void registro(String numCedula, String Nombre) { System.out.println("Bienvenido a nuestra plataforma"); System.out.println("Su numero de cedula es:"); System.out.println(numCedula); System.out.println("Bienvenido/a "+Nombre); } }
package style.gui.test.correct; import javafx.scene.control.Label; import javafx.scene.effect.ColorAdjust; import javafx.scene.layout.HBox; import style.gui.icons.CorrectIcon; import style.gui.icons.Icon; import style.gui.icons.IncorrectIcon; import style.gui.CreateNodes; /** * Created by Markus on 2017-05-28. */ public class CorrAnswer extends HBox { private Icon correctIcon; private String type, text, order; private boolean correct, answered; public CorrAnswer(String type, String text, boolean correct, boolean answered, String order){ this.type = type; this.text = text; this.correct = correct; this.answered = answered; this.order = order; setup(); } private void setup(){ switch(type){ case "Open question": setAnsweredText(); answered = false; setAnsweredStyle(); break; case "Order": text = order + " " + text; System.out.println(text); setAnsweredText(); break; case "Multiple choice": addIcon(); setAnsweredText(); setAnsweredStyle(); break; case "One choice": addIcon(); setAnsweredText(); setAnsweredStyle(); break; } } private void addIcon(){ if(correct){ correctIcon = new CorrectIcon(); } else { correctIcon = new IncorrectIcon(); } getChildren().add(correctIcon); } private void setAnsweredText(){ Label answerLabel = CreateNodes.createLabel2(text); answerLabel.setMaxWidth(300); answerLabel.setWrapText(true); getChildren().add(answerLabel); } private void setAnsweredStyle(){ if(answered){ getStyleClass().add("answered"); } else { getStyleClass().add("unanswered"); ColorAdjust grayScale = new ColorAdjust(); grayScale.setSaturation(-1); grayScale.setContrast(10); grayScale.setBrightness(-50); setEffect(grayScale); } } }
package com.nag.android.kurikuri; import android.widget.TextView; import com.nag.android.util.FlipView; interface ResourceManager{ Board getBoard(); Properties getProperties(); AppPlayer getPlayer(); FlipView getSignBoard(); TextView getScoreBoard(); Score getScore(); }
package rdfsynopsis.dataset; import com.hp.hpl.jena.query.Query; import com.hp.hpl.jena.query.QueryExecution; public abstract class SparqlDataset extends Dataset { public abstract QueryExecution query(Query query); }