blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
410
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
51
license_type
stringclasses
2 values
repo_name
stringlengths
5
132
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
80
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
5.85k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
131 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
9.45M
extension
stringclasses
32 values
content
stringlengths
3
9.45M
authors
sequencelengths
1
1
author_id
stringlengths
0
313
6f36dab313285efe6ee2159287be3167f6e39e11
d231708f381ac4255cd1ca9d9aecf23733e09dc5
/p6.java
c35d1138fd0a902a3157e64a4829c1955987d3f3
[]
no_license
muskanmahajan37/Java
5e115333c2e88079d6a2cae8d2a9faff5f736aca
da8c953e34be2a189db81752c98cee74f5d25445
refs/heads/master
2021-05-31T14:43:26.509524
2016-05-24T04:33:20
2016-05-24T04:33:20
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,655
java
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class p6 */ @WebServlet("/p6") public class p6 extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public p6() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub PrintWriter out = response.getWriter(); String name = request.getParameter("name"); String gender = request.getParameter("gender"); int age = Integer.parseInt(request.getParameter("age")); if(age == 60) { if(gender.equals("male")) out.print("<h1>" + "Namaste Uncle "+ name + "</h1>"); else out.print("<h1>" + "Namaste Aunty "+ name + "</h1>"); } else if(age == 18) { out.print("<h1>" + "Hi! " + name + ", How are you dude?" + "</h1>"); } else out.print("<h1>" + "Hey Stranger!" + "</h1>"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request,response); } }
07af6f095aac134ee804205cd2a4dc607a3e3218
b07e61f16cdf293b90565fda238181c846d2fa3b
/nb-mall-develop/nb-related/src/main/java/com/nowbook/rlt/settle/manager/DepositManager.java
15261006ba9d269f985729cc893507b50d46e4e5
[]
no_license
gspandy/QTH-Server
4d9bbb385c43a6ecb6afbecfe2aacce69f1a37b7
9a47cef25542feb840f6ffdebdcb79fc4c7fc57b
refs/heads/master
2023-09-03T12:36:39.468049
2018-02-06T06:09:49
2018-02-06T06:09:49
123,294,108
0
1
null
2018-02-28T14:11:08
2018-02-28T14:11:07
null
UTF-8
Java
false
false
6,709
java
package com.nowbook.rlt.settle.manager; import com.nowbook.rlt.settle.dao.DepositAccountDao; import com.nowbook.rlt.settle.dao.DepositFeeCashDao; import com.nowbook.rlt.settle.dao.DepositFeeDao; import com.nowbook.rlt.settle.model.DepositAccount; import com.nowbook.rlt.settle.model.DepositFee; import com.nowbook.rlt.settle.model.DepositFeeCash; import com.google.common.base.Objects; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import java.util.List; import static com.nowbook.common.utils.Arguments.equalWith; import static com.nowbook.common.utils.Arguments.notNull; import static com.google.common.base.Preconditions.checkState; /** * Mail: [email protected] <br> * Date: 2014-02-10 12:18 PM <br> * Author:cheng */ @Slf4j @Component public class DepositManager { @Autowired private DepositFeeDao depositFeeDao; @Autowired private DepositAccountDao depositAccountDao; @Autowired private DepositFeeCashDao depositFeeCashDao; public Boolean isAccountLocked(Long sellerId, Integer threshold) { DepositAccount account = depositAccountDao.findBySellerId(sellerId); checkState(notNull(account) && notNull(account.getBalance()), "deposit.account.not.found"); return isAccountLocked(account, threshold); } public Boolean isAccountLocked(DepositAccount account, Integer threshold) { Long balance = account.getBalance(); return balance < threshold; } /** * 商户缴纳保证金 * * @param fee 保证金信息 * @return 记录标识 */ @Transactional public Long createDepositFee(DepositFee fee) { DepositAccount account = depositAccountDao.findBySellerId(fee.getSellerId()); checkState(notNull(account), "deposit.account.not.found"); Long balance = account.getBalance(); fee.setSellerName(account.getSellerName()); fee.setBusiness(account.getBusiness()); fee.setOuterCode(account.getOuterCode()); fee.setShopId(account.getShopId()); fee.setShopName(account.getShopName()); Long id = depositFeeDao.create(fee); // 当支付方式为支付宝时需要创建提现单据 if (equalWith(fee.getType(), DepositFee.Type.INCREMENT.value()) || equalWith(fee.getType(), DepositFee.Type.TECH_SERVICE.value())) { createDepositCash(fee, id); } if (Objects.equal(fee.getType(), DepositFee.Type.TECH_SERVICE.value())) { // 技术服务费不需要更新账户 return id; } else if (Objects.equal(fee.getType(), DepositFee.Type.INCREMENT.value())) { balance += fee.getDeposit(); } else if (Objects.equal(fee.getType(), DepositFee.Type.DEDUCTION.value()) || Objects.equal(fee.getType(), DepositFee.Type.REFUND.value())) { balance -= fee.getDeposit(); } depositAccountDao.updateBal(account.getId(), balance); return id; } private void createDepositCash(DepositFee fee, Long id) { if (equalWith(fee.getPaymentType(), DepositFee.PaymentType.ALIPAY.value())) { DepositFeeCash depositFeeCash = new DepositFeeCash(); depositFeeCash.setDepositId(id); depositFeeCash.setSellerId(fee.getSellerId()); depositFeeCash.setSellerName(fee.getSellerName()); depositFeeCash.setShopId(fee.getShopId()); depositFeeCash.setShopName(fee.getShopName()); depositFeeCash.setStatus(DepositFeeCash.Status.NOT.value()); depositFeeCash.setSynced(DepositFeeCash.Synced.NOT.value()); depositFeeCash.setVouched(DepositFeeCash.Vouched.NOT.value()); depositFeeCash.setCashFee(fee.getDeposit()); depositFeeCash.setBusiness(fee.getBusiness()); depositFeeCash.setOuterCode(fee.getOuterCode()); Integer cashType = Objects.equal(fee.getType(), DepositFee.Type.INCREMENT.value()) ? DepositFeeCash.CashType.DEPOSIT.value() : DepositFeeCash.CashType.TECH_FEE.value(); depositFeeCash.setCashType(cashType); depositFeeCashDao.create(depositFeeCash); } } /** * 标记同步完成 * * @param fees 保证金或技术服务费列表 */ @Transactional public void batchSynced(List<DepositFee> fees) { for (DepositFee fee : fees) { depositFeeDao.synced(fee.getId()); } } /** * 更新保证金或者技术服务费 * * @param origin 原始费用 * @param updating 更新后的费用 * @return 更新后的费用id */ @Transactional public Long updateDeposit(DepositFee origin, DepositFee updating) { checkState(depositFeeDao.update(updating), "deposit.fee.update.fail"); if (equalWith(origin.getPaymentType(), DepositFee.PaymentType.ALIPAY.value())) { // 支付宝提现需要同步修改提现单据 DepositFeeCash cash = depositFeeCashDao.getByDepositId(origin.getId()); checkState(notNull(cash), "deposit.cash.not.found"); DepositFeeCash cashUpdating = new DepositFeeCash(); cashUpdating.setId(cash.getId()); cashUpdating.setCashFee(updating.getDeposit()); checkState(depositFeeCashDao.update(cashUpdating), "deposit.cash.update.fail"); } if (DepositFee.isTechService(origin)) { // 技术服务费不用更新账户 return updating.getId(); } Long originFee = origin.getDeposit(); Long updatingFee = updating.getDeposit(); Long delta = updatingFee - originFee; DepositAccount account = depositAccountDao.findBySellerId(origin.getSellerId()); checkState(notNull(account), "deposit.account.not.found"); Long balance = account.getBalance(); if (DepositFee.isIncrement(origin)) { // 新增 balance += delta; } else if (DepositFee.isDeduction(origin) || DepositFee.isRefund(origin)) { balance -= delta; } else { throw new IllegalStateException("deposit.fee.type.incorrect"); } account.setBalance(balance); checkState(depositAccountDao.updateBal(account.getId(), balance), "deposit.account.update.fail"); return updating.getId(); } @Transactional public void batchSyncedCash(List<DepositFeeCash> cashes) { for (DepositFeeCash cash : cashes) { depositFeeCashDao.synced(cash.getId()); } } }
f1acaf438384aa4839f2cf91d7313660dbeae8c6
53e20ebca11fe9e8818fb9de14b9ff53f7ee3293
/Algorithms/chapter1/DoubleNodeStack.java
861c43047a658d0e2d1efd333376efbb360d6f00
[ "Apache-2.0" ]
permissive
siyehua/Android-Notes
7ef39bad4a3e238f947c5390ffaa00127613d653
926db29810748794269b7166b173acc19b664ce4
refs/heads/master
2021-06-15T09:44:02.479003
2017-03-23T08:44:57
2017-03-23T08:44:57
27,953,395
12
7
null
null
null
null
UTF-8
Java
false
false
4,665
java
package com.example; import java.util.Iterator; /** * Created by huangxk on 2016/12/4. */ public class DoubleNodeStack<T> implements Iterable<T> { @Override public Iterator<T> iterator() { return new MyIterator(); } private class Node { Node next; Node last; T item; } private Node first; int number; public boolean isEmpty() { return number == 0; } public int size() { return number; } public void push(T item) { Node old = first; first = new Node(); first.item = item; first.next = old; if (old != null) old.last = first; number++; } public T pop() { T tmp = first.item; first = first.next; first.last = null; number--; return tmp; } private class MyIterator implements Iterator<T> { private Node current = first; @Override public boolean hasNext() { return current != null; } @Override public T next() { T tmp = current.item; current = current.next; return tmp; } @Override public void remove() { } } public void addHead(T item) { Node node = first; for (int i = 0; i < size() - 1; i++) { node = node.next; } Node newNode = new Node(); newNode.item = item; newNode.last = node; node.next = newNode; number++; } public void addTail(T item) { push(item); } public void removeHead() { Node node = first; for (int i = 0; i < size() - 1; i++) { node = node.next; } node.last.next = null; node.last = null; number--; } public void removeTail() { pop(); } /** * add item in the index's left.<br> * if index < 0 ,the item will add to the left of 0<br> * if index > {@link MyStack#size()} - 1, the item will add to the end. * * @param index index * @param item item */ public void addLeft(int index, T item) { if (index <= 0) { addHead(item); return; } if (index > size() - 1) { addTail(item); return; } Node newNode = new Node(); newNode.item = item; Node node = first; for (int i = index; i < size() - 1; i++) { node = node.next; } newNode.next = node.next; newNode.last = node; node.next.last = newNode; node.next = newNode; number++; } /** * add item in the index's right.<br> * if index < 0 ,the item will add to the left of 0<br> * if index > {@link MyStack#size()} - 1, the item will add to the end. * * @param index index * @param item item */ private void addRight(int index, T item) { if (index < 0) { addHead(item); return; } if (index > size() - 1) { addTail(item); return; } Node newNode = new Node(); newNode.item = item; Node node = first; for (int i = index; i < size() - 1; i++) { node = node.next; } newNode.last = node.last; newNode.next = node; node.last.next = newNode; node.last = newNode; number++; } public boolean remove(int index) { if (index < 0 || index > size() - 1) return false; if (index == 0) removeHead(); else if (index == size() - 1) removeTail(); else { Node node = first; for (int i = index; i < size() - 1; i++) { node = node.next; } node.next.last = node.last; node.last.next = node.next; node.last = null; node.next = null; } return true; } public static void main(String[] args) { DoubleNodeStack<String> doubleNodeStack = new DoubleNodeStack<>(); for (int i = 0; i < 10; i++) { doubleNodeStack.push(i + 1 + ""); } // doubleNodeStack.addHead("add head"); // doubleNodeStack.addTail("add Tail"); // doubleNodeStack.removeHead(); // doubleNodeStack.removeTail(); // doubleNodeStack.addLeft(5, "add left"); // doubleNodeStack.addRight(0, "add right"); System.out.println(doubleNodeStack.remove(2)); for (String str : doubleNodeStack) { System.out.println(str); } } }
[ "624104244" ]
624104244
aa418e8e342a2195cadfdf24a8f27e3a8dd2f848
6957badb2f8dcae20e78192dea5b3f4f65068f3d
/connect/runtime/src/test/java/org/apache/kafka/connect/runtime/rest/entities/PluginInfoTest.java
540c8a4269480033d41781724ab2522e85f93587
[ "Apache-2.0", "CDDL-1.1", "GPL-2.0-only", "BSD-3-Clause", "BSD-2-Clause", "WTFPL", "LicenseRef-scancode-unknown-license-reference", "Classpath-exception-2.0", "EPL-2.0", "MIT", "LicenseRef-scancode-public-domain", "W3C", "CC0-1.0", "GPL-1.0-or-later", "CPL-1.0", "GPL-2.0-or-later", "LicenseRef-scancode-generic-export-compliance", "LicenseRef-scancode-other-permissive", "CC-PDDC", "APSL-2.0", "LicenseRef-scancode-free-unknown", "CDDL-1.0", "EPL-1.0" ]
permissive
dongjinleekr/kafka
1bcdd1ce994cdb8bf820ffcb90e0bfc6e57923b6
63a6130af30536d67fca5802005695a84c875b5e
refs/heads/trunk
2022-07-23T18:15:19.992749
2022-07-07T21:00:05
2022-07-07T21:00:05
69,036,305
1
1
Apache-2.0
2022-06-04T20:01:34
2016-09-23T15:16:20
Java
UTF-8
Java
false
false
1,451
java
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 org.apache.kafka.connect.runtime.rest.entities; import org.apache.kafka.connect.runtime.isolation.DelegatingClassLoader; import org.junit.Test; import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertTrue; public class PluginInfoTest { @Test public void testNoVersionFilter() { PluginInfo.NoVersionFilter filter = new PluginInfo.NoVersionFilter(); assertFalse(filter.equals("1.0")); assertFalse(filter.equals(new Object())); assertFalse(filter.equals(null)); assertTrue(filter.equals(DelegatingClassLoader.UNDEFINED_VERSION)); } }
c484626e2e744e23a198d798aa63dddb42791180
ecc1100029fd5324ba00e64f253b6b3849a43d86
/AppMuestreoINF/Respaldo/src/gob/conafor/suelo/mod/CDProfundidadSuelo.java
0b2246c5b0697d48f2b3b6cd024197733f09cfe4
[]
no_license
nachomartinez30/AppCONAFOR
c09996f31223ba8de507a632e29ab7607eab3d58
577126c876d39c9156e3d64feca258aa603308f4
refs/heads/master
2020-09-23T12:17:32.124843
2017-10-12T21:49:28
2017-10-12T21:49:28
66,490,098
1
0
null
2017-11-07T19:27:38
2016-08-24T18:39:37
Java
UTF-8
Java
false
false
14,191
java
package gob.conafor.suelo.mod; import gob.conafor.conn.dat.LocalConnection; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import javax.swing.JOptionPane; import javax.swing.table.DefaultTableModel; public class CDProfundidadSuelo { private String query; private CEProfundidadSuelo ceProfundidad = new CEProfundidadSuelo(); public List<Integer> getPuntosProfundidad(int sitioID) { List<Integer> listPuntosProfundidad = new ArrayList<>(); for (int i = 1; i < 9; i++) { listPuntosProfundidad.add(i); } query = "SELECT SitioID, Punto FROM SUELO_Profundidad WHERE SitioID= " + sitioID; Connection conn = LocalConnection.getConnection(); try { Statement st = conn.createStatement(); ResultSet rs = st.executeQuery(query); while (rs.next()) { Integer index = rs.getInt(2); listPuntosProfundidad.remove(index); } } catch (SQLException e) { JOptionPane.showMessageDialog(null, "Error! al obtener los puntos de profundidad del suelo ", "Conexion BD", JOptionPane.ERROR_MESSAGE); } finally { try { conn.close(); } catch (SQLException e) { JOptionPane.showMessageDialog(null, "Error! al cerrar la base de datos en los puntos de profundidad del suelo ", "Conexion BD", JOptionPane.ERROR_MESSAGE); } } listPuntosProfundidad.add(0, null); return listPuntosProfundidad; } public List<Integer> getListProfundidadID(int sitioID) { List<Integer> listHojarascaID = new ArrayList<>(); query = "SELECT ProfundidadSueloID, SitioID FROM SUELO_Profundidad WHERE SitioID= " + sitioID + " ORDER BY ProfundidadSueloID ASC"; Connection conn = LocalConnection.getConnection(); try { Statement st = conn.createStatement(); ResultSet rs = st.executeQuery(query); while (rs.next()) { listHojarascaID.add(rs.getInt("ProfundidadSueloID")); } } catch (SQLException e) { JOptionPane.showMessageDialog(null, "Error! al obtener los datos de profundidad de suelo id ", "Conexion BD", JOptionPane.ERROR_MESSAGE); return null; } finally { try { conn.close(); } catch (SQLException e) { JOptionPane.showMessageDialog(null, "Error! al cerrar la base de datos en lista de profundidad de suelo id", "Conexion BD", JOptionPane.ERROR_MESSAGE); } } return listHojarascaID; } public void reenumerarProfundidad(int sitioID) { List<Integer> listProfundidadPuntos = getListProfundidadID(sitioID); Connection conn = LocalConnection.getConnection(); if (listProfundidadPuntos != null) { int size = listProfundidadPuntos.size(); int consecutivo = 1; try { for (int i = 0; i < size; i++) { Statement st = conn.createStatement(); query = "UPDATE SUELO_Profundidad SET Punto= " + consecutivo + " WHERE ProfundidadSueloID= " + listProfundidadPuntos.get(i); st.executeUpdate(query); conn.commit(); consecutivo++; } } catch (SQLException e) { JOptionPane.showMessageDialog(null, "Error! al reenumerar los puntos de profundidad de suelo ", "Conexion BD", JOptionPane.ERROR_MESSAGE); } finally { try { conn.close(); } catch (SQLException e) { JOptionPane.showMessageDialog(null, "Error! al cerrar la base de datos al reenumerar los puntos de profundidad de suelo ", "Conexion BD", JOptionPane.ERROR_MESSAGE); } } } } public CEProfundidadSuelo getDatosProfundidad(int profundidadID) { query = "SELECT ProfundidadSueloID, Punto, Profundidad030, Profundidad3060, PesoTotal030, PesoTotal3060, Equipo030, " + "Equipo3060, Observaciones, Clave030, Clave3060 FROM SUELO_Profundidad WHERE ProfundidadSueloID= " + profundidadID; Connection conn = LocalConnection.getConnection(); try { Statement st = conn.createStatement(); ResultSet rs = st.executeQuery(query); while (rs.next()) { this.ceProfundidad.setPunto(rs.getInt("Punto")); this.ceProfundidad.setProfundidad030(rs.getFloat("Profundidad030")); this.ceProfundidad.setProfundidad3060(rs.getFloat("Profundidad3060")); this.ceProfundidad.setPeso030(rs.getFloat("PesoTotal030")); this.ceProfundidad.setPeso3060(rs.getFloat("PesoTotal3060")); this.ceProfundidad.setEquipo030(rs.getString("Equipo030")); this.ceProfundidad.setEquipo3060(rs.getString("Equipo3060")); this.ceProfundidad.setObservaciones(rs.getString("Observaciones")); this.ceProfundidad.setClave030("Clave030"); this.ceProfundidad.setClave3060("Clave3060"); } return this.ceProfundidad; } catch (SQLException e) { JOptionPane.showMessageDialog(null, "Error! al obtener los datos de profundidad de suelo " + e.getClass().getName() + " : " + e.getMessage(), "Conexion BD", JOptionPane.ERROR_MESSAGE); return null; } finally { try { conn.close(); } catch (SQLException e) { JOptionPane.showMessageDialog(null, "Error! al cerrar la base de datos al obtener la información de profundidad de suelo ", "Conexion BD", JOptionPane.ERROR_MESSAGE); } } } public DefaultTableModel getTablaProfundidad(int sitioID) { query = "SELECT ProfundidadSueloID, SitioID, Punto, Profundidad030, Profundidad3060, PesoTotal030, " + "PesoTotal3060, Equipo030, Equipo3060, Observaciones, Clave030, Clave3060 FROM SUELO_Profundidad"; String[] encabezados = {"ProfundidadID", "SitioID", "Punto", "Profundidad 0-30", "Profundidad 30-60", "Peso total 0-30", "Peso total 30-60", "Equipo 0-30", "Equipo 30-60", "Observaciones", "Clave 0-30", "Clave 30-60"}; DefaultTableModel hojarascaModel = new DefaultTableModel(null, encabezados); Object[] datosHojarasca = new Object[12]; Connection conn = LocalConnection.getConnection(); try { Statement st = conn.createStatement(); ResultSet rs = st.executeQuery(query); while (rs.next()) { datosHojarasca[0] = rs.getInt("ProfundidadSueloID"); datosHojarasca[1] = rs.getInt("SitioID"); datosHojarasca[2] = rs.getInt("Punto"); datosHojarasca[3] = rs.getString("Profundidad030"); datosHojarasca[4] = rs.getString("Profundidad3060"); datosHojarasca[5] = rs.getString("PesoTotal030"); datosHojarasca[6] = rs.getString("PesoTotal3060"); datosHojarasca[7] = rs.getString("Equipo030"); datosHojarasca[8] = rs.getString("Equipo3060"); datosHojarasca[9] = rs.getString("Observaciones"); datosHojarasca[10] = rs.getString("Clave030"); datosHojarasca[11] = rs.getString("Clave3060"); hojarascaModel.addRow(datosHojarasca); } st.close(); rs.close(); return hojarascaModel; } catch (SQLException e) { JOptionPane.showMessageDialog(null, "Error! al obtener los datos de la vista de profundidad suelo ", "Conexion BD", JOptionPane.ERROR_MESSAGE); return null; } finally { try { conn.close(); } catch (SQLException e) { JOptionPane.showMessageDialog(null, "Error! al cerrar la base de datos en para la vista de profundidad suelo ", "Conexion BD", JOptionPane.ERROR_MESSAGE); } } } public void insertProfundidad(CEProfundidadSuelo ceProfundidad) { query = "INSERT INTO SUELO_Profundidad(SitioID, Punto, Profundidad030, Profundidad3060, PesoTotal030, PesoTotal3060, " + "Equipo030, Equipo3060, Observaciones, Clave030, Clave3060)VALUES(" + ceProfundidad.getSitioID() + ", " + ceProfundidad.getPunto() + ", " + ceProfundidad.getProfundidad030() + ", " + ceProfundidad.getProfundidad3060() + ", " + ceProfundidad.getPeso030() + ", " + ceProfundidad.getPeso3060() + ", '" + ceProfundidad.getEquipo030() + "', '" + ceProfundidad.getEquipo3060() + "', '" + ceProfundidad.getObservaciones() + "', '" + ceProfundidad.getClave030() + "', '" + ceProfundidad.getClave3060() + "')"; Connection conn = LocalConnection.getConnection(); try { Statement st = conn.createStatement(); st.executeUpdate(query); conn.commit(); st.close(); } catch (SQLException e) { JOptionPane.showMessageDialog(null, "Error! no se pudo guardar la informacion en profundidad de suelo ", "Conexion BD", JOptionPane.ERROR_MESSAGE); } finally { try { conn.close(); } catch (SQLException e) { JOptionPane.showMessageDialog( null, "Error! al cerrar la base de datos al insertar datos de profundidad de suelo ", "Conexion BD", JOptionPane.ERROR_MESSAGE); } } } public void updateProfundidad(CEProfundidadSuelo ceProfundidad) { query = "UPDATE SUELO_Profundidad SET Profundidad030= " + ceProfundidad.getProfundidad030() + ", Profundidad3060= " + ceProfundidad.getPeso3060() + ", PesoTotal030= " + ceProfundidad.getPeso030() + ", PesoTotal3060= " + ceProfundidad.getPeso3060() + ", Equipo030= '" + ceProfundidad.getEquipo030() + "', Equipo3060= '" + ceProfundidad.getEquipo3060() + "', Observaciones= '" + ceProfundidad.getObservaciones() + "' WHERE ProfundidadSueloID= " + ceProfundidad.getProfundidadSueloID(); Connection conn = LocalConnection.getConnection(); try { Statement st = conn.createStatement(); st.executeUpdate(query); conn.commit(); st.close(); } catch (SQLException e) { JOptionPane.showMessageDialog(null, "Error! no se pudo modificar la información de profundidad de suelo " + e.getClass().getName() + " : " + e.getMessage(), "Conexion BD", JOptionPane.ERROR_MESSAGE); } finally { try { conn.close(); } catch (SQLException e) { JOptionPane.showMessageDialog(null, "Error! al cerrar la base de datos en la modificación de profundidad de suelo " + e.getClass().getName() + " : " + e.getMessage(), "Conexion BD", JOptionPane.ERROR_MESSAGE); } } } public void deleteProfundidad(int profundidadID) { query = "DELETE FROM SUELO_Profundidad WHERE ProfundidadSueloID= " + profundidadID; Connection conn = LocalConnection.getConnection(); try { Statement st = conn.createStatement(); st.executeUpdate(query); conn.commit(); st.close(); } catch (SQLException e) { JOptionPane.showMessageDialog(null, "Error! no se pudo eliminar la información de profundidad de suelo ", "Conexion BD", JOptionPane.ERROR_MESSAGE); } finally { try { conn.close(); } catch (SQLException e) { JOptionPane.showMessageDialog( null, "Error! al cerrar la base de datos al eliminar profundidad de suelo ", "Conexion BD", JOptionPane.ERROR_MESSAGE); } } } public void deleteProfundidadSitio(int sitioID) { query = "DELETE FROM SUELO_Profundidad WHERE SitioID= " + sitioID; Connection conn = LocalConnection.getConnection(); try { Statement st = conn.createStatement(); st.executeUpdate(query); conn.commit(); st.close(); } catch (SQLException e) { JOptionPane.showMessageDialog(null, "Error! no se pudo eliminar la información de profundidad de suelo por sitio", "Conexion BD", JOptionPane.ERROR_MESSAGE); } finally { try { conn.close(); } catch (SQLException e) { JOptionPane.showMessageDialog( null, "Error! al cerrar la base de datos al eliminar profundidad de suelo por sitio", "Conexion BD", JOptionPane.ERROR_MESSAGE); } } } public boolean validarTablaProfundidad(int sitioID) { query = "SELECT * FROM SUELO_Profundidad WHERE SitioID= " + sitioID; boolean vacio = true; Connection conn = LocalConnection.getConnection(); try { Statement st = conn.createStatement(); ResultSet rs = st.executeQuery(query); while (rs.next()) { vacio = false; } } catch (SQLException e) { JOptionPane.showMessageDialog(null, "Error! al validar la presencia de datos en la tabla de profundidad de suelo", "Conexion BD", JOptionPane.ERROR_MESSAGE); } finally { try { conn.close(); } catch (SQLException e) { JOptionPane.showMessageDialog(null, "Error! al cerrar la base de datos en la tabla de profundidad de suelo", "Conexion BD", JOptionPane.ERROR_MESSAGE); } } return vacio; } }
119e51d4a9f5c7e9c184b282ac26075177035b7a
7959128b08113070e2d93fceb239b15a4292c3d4
/src/main/java/com/qiniu/sdk/UpYunClient.java
29481e95aa9774362ade08c92bd623be5787d36d
[ "Apache-2.0" ]
permissive
sxci/qiniu-suits-java
1c61e295fd7905ee7464fd9563bcbe072143cc9a
94f3227d3751ca64a13d7de429f797d35dc328be
refs/heads/master
2020-08-27T22:48:15.052206
2019-10-24T21:58:37
2019-10-24T21:58:37
null
0
0
null
null
null
null
UTF-8
Java
false
false
5,231
java
package com.qiniu.sdk; import com.qiniu.common.SuitsException; import com.qiniu.util.*; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; import java.util.Map; public class UpYunClient { private UpYunConfig config; // 操作员名 private String userName; // 操作员密码 private String password; public UpYunClient(UpYunConfig config, String userName, String password) { this.config = config; this.userName = userName; this.password = CharactersUtils.md5(password); } public String listFiles(String bucket, String directory, String marker, int limit) throws IOException { String uri = "/" + bucket + "/" + URLUtils.getEncodedURI(directory); Map<String, String> headers = new HashMap<String, String>(){{ put("x-list-iter", marker); put("x-list-limit", String.valueOf(limit)); put("Accept", "application/json"); }}; try { return HttpGetAction(uri, headers); } catch (SuitsException e) { if (e.getStatusCode() == 401) { throw new SuitsException(e, "please check name of bucket or user."); } else { throw new SuitsException(e, headers.toString()); } } } public FileItem getFileInfo(String bucket, String key) throws IOException { String uri = "/" + bucket + "/" + URLUtils.getEncodedURI(key); HttpURLConnection conn; URL url = new URL("http://" + UpYunConfig.apiDomain + uri); conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(config.connectTimeout); conn.setReadTimeout(config.readTimeout); conn.setRequestMethod(UpYunConfig.METHOD_HEAD); conn.setUseCaches(false); String date = DatetimeUtils.getGMTDate(); conn.setRequestProperty(UpYunConfig.DATE, date); conn.setRequestProperty(UpYunConfig.AUTHORIZATION, CloudApiUtils.upYunSign(UpYunConfig.METHOD_HEAD, date, uri, userName, password, null)); conn.connect(); int code = conn.getResponseCode(); if (code != 200) throw new SuitsException(code, conn.getResponseMessage()); FileItem fileItem = new FileItem(); fileItem.key = key; try { fileItem.attribute = conn.getHeaderField(UpYunConfig.X_UPYUN_FILE_TYPE); fileItem.size = Long.valueOf(conn.getHeaderField(UpYunConfig.X_UPYUN_FILE_SIZE)); fileItem.lastModified = Long.valueOf(conn.getHeaderField(UpYunConfig.X_UPYUN_FILE_DATE)); } catch (NullPointerException | NumberFormatException e) { throw new SuitsException(e, 404, e.getMessage() + ", the file may be not exists: " + fileItem); } finally { conn.disconnect(); } return fileItem; } public long getBucketUsage(String bucket) throws IOException { String result = HttpGetAction("/" + bucket + "/?usage", null); try { return Long.parseLong(result.trim()); } catch (Exception e) { return -1; } } private String HttpGetAction(String uri, Map<String, String> headers) throws IOException { URL url = new URL("http://" + UpYunConfig.apiDomain + uri); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(config.connectTimeout); conn.setReadTimeout(config.readTimeout); conn.setRequestMethod(UpYunConfig.METHOD_GET); conn.setUseCaches(false); String date = DatetimeUtils.getGMTDate(); conn.setRequestProperty(UpYunConfig.DATE, date); conn.setRequestProperty(UpYunConfig.AUTHORIZATION, CloudApiUtils.upYunSign(UpYunConfig.METHOD_GET, date, uri, userName, password, null)); if (headers != null) { for (Map.Entry<String, String> entry : headers.entrySet()) { conn.setRequestProperty(entry.getKey(), entry.getValue()); } } conn.connect(); int code = conn.getResponseCode(); // is = conn.getInputStream(); // 状态码错误时不能使用 getInputStream() InputStream is = code >= 400 ? conn.getErrorStream() : conn.getInputStream(); InputStreamReader sr = new InputStreamReader(is); BufferedReader br = new BufferedReader(sr); StringBuilder text = new StringBuilder(); try { char[] chars = new char[4096]; int length; while ((length = br.read(chars)) != -1) { text.append(chars, 0, length); } } finally { try { conn.disconnect(); br.close(); sr.close(); is.close(); } catch (IOException e) { br = null; sr = null; is = null; } } if (code == 200) { return text.toString(); } else { throw new SuitsException(code, text.toString()); } } }
32596e4fda38953b96262e8daaf0a1b6e1590301
8af1164bac943cef64e41bae312223c3c0e38114
/results-java/naver--pinpoint/990b945ded9a599be283dfeeb969f71a96fafd14/after/EndPoint.java
aed495ffd955fe184afd7c59b6f9c39bfba5fdab
[]
no_license
fracz/refactor-extractor
3ae45c97cc63f26d5cb8b92003b12f74cc9973a9
dd5e82bfcc376e74a99e18c2bf54c95676914272
refs/heads/master
2021-01-19T06:50:08.211003
2018-11-30T13:00:57
2018-11-30T13:00:57
87,353,478
0
0
null
null
null
null
UTF-8
Java
false
false
392
java
package com.profiler.context; public class EndPoint { private final String ip; private final int port; public EndPoint(String ip, int port) { this.ip = ip; this.port = port; } public String toString() { return "{ip=" + ip + ", port=" + port + "}"; } public com.profiler.context.gen.Endpoint toThrift() { return new com.profiler.context.gen.Endpoint(ip, (short) port); } }
eeb5f249d2d6a305c81b05e60345b3638b87f18d
d7e93a4418c47424936bd292bf1eea1aa60fdada
/src/simulation/Simulation.java
965d05f1a2423f6567085af524dee7f8e296df85
[ "MIT" ]
permissive
dtbinh/simulation-p3dx
35f9a72305c6458496dbf6e6db03e916bd477324
054c94c9b224647f685e2b4b5386f446a0c2e3e4
refs/heads/master
2020-12-28T21:28:47.492565
2016-03-16T22:48:55
2016-03-16T22:48:55
63,956,598
1
0
null
2016-07-22T13:44:41
2016-07-22T13:44:40
null
UTF-8
Java
false
false
1,805
java
/** * Copyright (c) 2014 Saúl Piña <[email protected]>, Jorge Parra <[email protected]>. * * This file is part of SimulationP3DX. * * SimulationP3DX is licensed under The MIT License. * For full copyright and license information please see the LICENSE file. */ package simulation; import simulation.interfaces.Architecture; import app.Log; import app.Translate; import app.vrep.Client; public class Simulation extends Thread { private Architecture architecture; private boolean stop; private long delay; public static final long STANDARD_DELAY = 50l; public long getDelay() { return delay; } public void setDelay(long delay) { this.delay = delay; } public Architecture getArchitecture() { return architecture; } public void setArchitecture(Architecture architecture) { this.architecture = architecture; } public Simulation(long delay, Architecture architecture) { this.architecture = architecture; this.delay = delay; stop = true; } public Simulation(Architecture architecture) { this(STANDARD_DELAY, architecture); } @Override public void run() { while (Client.isConnect() && !stop) { architecture.simulate(); try { Thread.sleep(delay); } catch (InterruptedException e) { e.printStackTrace(); } } if (!Client.isConnect()) stopSimulation(); } @Override public synchronized void start() { Log.info(Client.class, Translate.get("INFO_INITSIMULATION") + " " + architecture.getClass().getName()); init(); stop = false; super.start(); } public void stopSimulation() { stop = true; Log.info(Client.class, Translate.get("INFO_STOPSIMULATION") + " " + architecture.getClass().getName()); } public boolean isRunning() { return !stop; } public void init() { architecture.init(); } }
423ddc7d94e42f685a116a5aeb709e3d40751b63
71b9e781af3a7c4c55e69f96f555cf6388113e5f
/in-action/itcast-netty/src/main/java/top/imyzt/learning/netty/message/Message.java
d14946321dece3d18b7b2c8f0f2a8509f3c30b92
[ "Apache-2.0" ]
permissive
imyzt/learning-technology-code
67231e38a33798552c00507a87082970451a729b
8c01f8b6aa15ca78c1c86015e49e9ffbe10e29c3
refs/heads/master
2023-07-24T22:22:45.799759
2023-07-08T15:23:22
2023-07-08T15:23:22
185,972,999
7
12
Apache-2.0
2023-06-19T15:18:03
2019-05-10T10:58:58
Java
UTF-8
Java
false
false
3,846
java
package top.imyzt.learning.netty.message; import lombok.Data; import top.imyzt.learning.netty.message.req.RpcRequestMessage; import top.imyzt.learning.netty.message.resp.RpcResponseMessage; import java.io.Serializable; import java.util.HashMap; import java.util.Map; /** * 消息对象 * @author imyzt */ @Data public abstract class Message implements Serializable { /** * 根据消息类型字节,获得对应的消息 class * @param messageType 消息类型字节 * @return 消息 class */ public static Class<? extends Message> getMessageClass(int messageType) { return messageClasses.get(messageType); } private int sequenceId; private int messageType; public abstract int getMessageType(); public static final int LoginRequestMessage = 0; public static final int LoginResponseMessage = 1; public static final int ChatRequestMessage = 2; public static final int ChatResponseMessage = 3; public static final int GroupCreateRequestMessage = 4; public static final int GroupCreateResponseMessage = 5; public static final int GroupJoinRequestMessage = 6; public static final int GroupJoinResponseMessage = 7; public static final int GroupQuitRequestMessage = 8; public static final int GroupQuitResponseMessage = 9; public static final int GroupChatRequestMessage = 10; public static final int GroupChatResponseMessage = 11; public static final int GroupMembersRequestMessage = 12; public static final int GroupMembersResponseMessage = 13; public static final int PingMessage = 14; public static final int PongMessage = 15; /** * 请求类型 byte 值 */ public static final int RPC_MESSAGE_TYPE_REQUEST = 101; /** * 响应类型 byte 值 */ public static final int RPC_MESSAGE_TYPE_RESPONSE = 102; private static final Map<Integer, Class<? extends Message>> messageClasses = new HashMap<>(); static { messageClasses.put(LoginRequestMessage, top.imyzt.learning.netty.message.req.LoginRequestMessage.class); messageClasses.put(LoginResponseMessage, top.imyzt.learning.netty.message.resp.LoginResponseMessage.class); messageClasses.put(ChatRequestMessage, top.imyzt.learning.netty.message.req.ChatRequestMessage.class); messageClasses.put(ChatResponseMessage, top.imyzt.learning.netty.message.resp.ChatResponseMessage.class); messageClasses.put(GroupCreateRequestMessage, top.imyzt.learning.netty.message.req.GroupCreateRequestMessage.class); messageClasses.put(GroupCreateResponseMessage, top.imyzt.learning.netty.message.resp.GroupCreateResponseMessage.class); messageClasses.put(GroupJoinRequestMessage, top.imyzt.learning.netty.message.req.GroupJoinRequestMessage.class); messageClasses.put(GroupJoinResponseMessage, top.imyzt.learning.netty.message.resp.GroupJoinResponseMessage.class); messageClasses.put(GroupQuitRequestMessage, top.imyzt.learning.netty.message.req.GroupQuitRequestMessage.class); messageClasses.put(GroupQuitResponseMessage, top.imyzt.learning.netty.message.resp.GroupQuitResponseMessage.class); messageClasses.put(GroupChatRequestMessage, top.imyzt.learning.netty.message.req.GroupChatRequestMessage.class); messageClasses.put(GroupChatResponseMessage, top.imyzt.learning.netty.message.resp.GroupChatResponseMessage.class); messageClasses.put(GroupMembersRequestMessage, top.imyzt.learning.netty.message.req.GroupMembersRequestMessage.class); messageClasses.put(GroupMembersResponseMessage, top.imyzt.learning.netty.message.resp.GroupMembersResponseMessage.class); messageClasses.put(RPC_MESSAGE_TYPE_REQUEST, RpcRequestMessage.class); messageClasses.put(RPC_MESSAGE_TYPE_RESPONSE, RpcResponseMessage.class); } }
c2483bf119e356382cd01b93e91e2006d404e60f
74dd63d7d113e2ff3a41d7bb4fc597f70776a9d9
/timss-facade/src/main/java/com/timss/attendance/vo/StatVo.java
723c88aa2b4acd33438f5f51dff5b3588b2f364e
[]
no_license
gspandy/timssBusiSrc
989c7510311d59ec7c9a2bab3b04f5303150d005
a5d37a397460a7860cc221421c5f6e31b48cac0f
refs/heads/master
2023-08-14T02:14:21.232317
2017-02-16T07:18:21
2017-02-16T07:18:21
null
0
0
null
null
null
null
UTF-8
Java
false
false
20,563
java
package com.timss.attendance.vo; import java.io.Serializable; import java.util.Date; /** * * @title: 考勤统计表 * @description: {desc} * @company: gdyd * @className: StatBean.java * @author: fengzt * @createDate: 2014年9月12日 * @updateUser: fengzt * @version: 1.0 */ public class StatVo implements Serializable { /** * */ private static final long serialVersionUID = -556307543822522251L; /** * id */ private int id; /** * 工号 */ private String userId; /** * 姓名 */ private String userName; /** * 统计年份 */ private int yearLeave; /** * 年假 */ private double annualLevel; /** * 给转上一年年假天数 */ private double annualRemain; /** * 给转上一年补休天数 */ private double compensateRemain; /** * 事假 */ private double enventLeave; /** * 病假 */ private double sickLeave; /** * 婚假 */ private double marryLeave; /** * 产假 */ private double birthLeave; /** * 其他 */ private double otherLeave; /** * 加班天数合计 */ private double overTime; /** * 已补休 */ private double compensateLeave; /** * 未补休 */ private double noCompensateLeave; /** * 创建日期 */ private Date createDate; /** * 站点id */ private String siteId; /** * 部门ID */ private String deptId; /** * 部门名称 */ private String deptName; /** * 请假天数合计 */ private double countDays; /** * 流程状态 */ private String status; /** * 用户状态 */ private String userStatus; /** * 可享受年假 */ private double annual; /** * 开始时间 */ private Date startDate; /** * 结束时间 */ private Date endDate; /** * 核减年假 */ private double subAnualLeave; /** * 核减备注 */ private String remark1; /** * 结转备注 */ private String remark2; /** * 请假类型8 */ private double category_8; /** * 请假类型9 */ private double category_9; /** * 请假类型10 */ private double category_10; /** * 请假类型11 */ private double category_11; /** * 请假类型12 */ private double category_12; /** * 请假类型13 */ private double category_13; /** * 请假类型14 */ private double category_14; /** * 请假类型15 */ private double category_15; /** * 请假类型16 */ private double category_16; /** * 请假类型17 */ private double category_17; public double getCategory_8() { return category_8; } public void setCategory_8(double category_8) { this.category_8 = category_8; } public double getCategory_9() { return category_9; } public void setCategory_9(double category_9) { this.category_9 = category_9; } public double getCategory_10() { return category_10; } public void setCategory_10(double category_10) { this.category_10 = category_10; } public double getCategory_11() { return category_11; } public void setCategory_11(double category_11) { this.category_11 = category_11; } public double getCategory_12() { return category_12; } public void setCategory_12(double category_12) { this.category_12 = category_12; } public double getCategory_13() { return category_13; } public void setCategory_13(double category_13) { this.category_13 = category_13; } public double getCategory_14() { return category_14; } public void setCategory_14(double category_14) { this.category_14 = category_14; } public double getCategory_15() { return category_15; } public void setCategory_15(double category_15) { this.category_15 = category_15; } public double getCategory_16() { return category_16; } public void setCategory_16(double category_16) { this.category_16 = category_16; } public double getCategory_17() { return category_17; } public void setCategory_17(double category_17) { this.category_17 = category_17; } public String getRemark1() { return remark1; } public void setRemark1(String remark1) { this.remark1 = remark1; } public String getRemark2() { return remark2; } public void setRemark2(String remark2) { this.remark2 = remark2; } public double getSubAnualLeave() { return subAnualLeave; } public void setSubAnualLeave(double subAnualLeave) { this.subAnualLeave = subAnualLeave; } public Date getStartDate() { return startDate; } public void setStartDate(Date startDate) { this.startDate = startDate; } public Date getEndDate() { return endDate; } public void setEndDate(Date endDate) { this.endDate = endDate; } public double getAnnual() { return annual; } public void setAnnual(double annual) { this.annual = annual; } public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId; } public double getNoCompensateLeave() { return noCompensateLeave; } public void setNoCompensateLeave(double noCompensateLeave) { this.noCompensateLeave = noCompensateLeave; } public double getCountDays() { return countDays; } public void setCountDays(double countDays) { this.countDays = countDays; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getUserStatus() { return userStatus; } public void setUserStatus(String userStatus) { this.userStatus = userStatus; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public int getYearLeave() { return yearLeave; } public void setYearLeave(int yearLeave) { this.yearLeave = yearLeave; } public double getAnnualLevel() { return annualLevel; } public void setAnnualLevel(double annualLevel) { this.annualLevel = annualLevel; } public double getAnnualRemain() { return annualRemain; } public void setAnnualRemain(double annualRemain) { this.annualRemain = annualRemain; } public double getCompensateRemain() { return compensateRemain; } public void setCompensateRemain(double compensateRemain) { this.compensateRemain = compensateRemain; } public double getEnventLeave() { return enventLeave; } public void setEnventLeave(double enventLeave) { this.enventLeave = enventLeave; } public double getSickLeave() { return sickLeave; } public void setSickLeave(double sickLeave) { this.sickLeave = sickLeave; } public double getMarryLeave() { return marryLeave; } public void setMarryLeave(double marryLeave) { this.marryLeave = marryLeave; } public double getBirthLeave() { return birthLeave; } public void setBirthLeave(double birthLeave) { this.birthLeave = birthLeave; } public double getOtherLeave() { return otherLeave; } public void setOtherLeave(double otherLeave) { this.otherLeave = otherLeave; } public double getOverTime() { return overTime; } public void setOverTime(double overTime) { this.overTime = overTime; } public double getCompensateLeave() { return compensateLeave; } public void setCompensateLeave(double compensateLeave) { this.compensateLeave = compensateLeave; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public String getSiteId() { return siteId; } public void setSiteId(String siteId) { this.siteId = siteId; } public String getDeptId() { return deptId; } public void setDeptId(String deptId) { this.deptId = deptId; } public String getDeptName() { return deptName; } public void setDeptName(String deptName) { this.deptName = deptName; } @Override public int hashCode() { final int prime = 31; int result = 1; long temp; temp = Double.doubleToLongBits( annual ); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits( annualLevel ); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits( annualRemain ); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits( birthLeave ); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits( category_10 ); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits( category_11 ); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits( category_12 ); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits( category_13 ); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits( category_14 ); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits( category_15 ); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits( category_16 ); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits( category_17 ); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits( category_8 ); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits( category_9 ); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits( compensateLeave ); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits( compensateRemain ); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits( countDays ); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + ((createDate == null) ? 0 : createDate.hashCode()); result = prime * result + ((deptId == null) ? 0 : deptId.hashCode()); result = prime * result + ((deptName == null) ? 0 : deptName.hashCode()); result = prime * result + ((endDate == null) ? 0 : endDate.hashCode()); temp = Double.doubleToLongBits( enventLeave ); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + id; temp = Double.doubleToLongBits( marryLeave ); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits( noCompensateLeave ); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits( otherLeave ); result = prime * result + (int) (temp ^ (temp >>> 32)); temp = Double.doubleToLongBits( overTime ); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + ((remark1 == null) ? 0 : remark1.hashCode()); result = prime * result + ((remark2 == null) ? 0 : remark2.hashCode()); temp = Double.doubleToLongBits( sickLeave ); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + ((siteId == null) ? 0 : siteId.hashCode()); result = prime * result + ((startDate == null) ? 0 : startDate.hashCode()); result = prime * result + ((status == null) ? 0 : status.hashCode()); temp = Double.doubleToLongBits( subAnualLeave ); result = prime * result + (int) (temp ^ (temp >>> 32)); result = prime * result + ((userId == null) ? 0 : userId.hashCode()); result = prime * result + ((userName == null) ? 0 : userName.hashCode()); result = prime * result + ((userStatus == null) ? 0 : userStatus.hashCode()); result = prime * result + yearLeave; return result; } @Override public boolean equals(Object obj) { if ( this == obj ) return true; if ( obj == null ) return false; if ( getClass() != obj.getClass() ) return false; StatVo other = (StatVo) obj; if ( Double.doubleToLongBits( annual ) != Double.doubleToLongBits( other.annual ) ) return false; if ( Double.doubleToLongBits( annualLevel ) != Double.doubleToLongBits( other.annualLevel ) ) return false; if ( Double.doubleToLongBits( annualRemain ) != Double.doubleToLongBits( other.annualRemain ) ) return false; if ( Double.doubleToLongBits( birthLeave ) != Double.doubleToLongBits( other.birthLeave ) ) return false; if ( Double.doubleToLongBits( category_10 ) != Double.doubleToLongBits( other.category_10 ) ) return false; if ( Double.doubleToLongBits( category_11 ) != Double.doubleToLongBits( other.category_11 ) ) return false; if ( Double.doubleToLongBits( category_12 ) != Double.doubleToLongBits( other.category_12 ) ) return false; if ( Double.doubleToLongBits( category_13 ) != Double.doubleToLongBits( other.category_13 ) ) return false; if ( Double.doubleToLongBits( category_14 ) != Double.doubleToLongBits( other.category_14 ) ) return false; if ( Double.doubleToLongBits( category_15 ) != Double.doubleToLongBits( other.category_15 ) ) return false; if ( Double.doubleToLongBits( category_16 ) != Double.doubleToLongBits( other.category_16 ) ) return false; if ( Double.doubleToLongBits( category_17 ) != Double.doubleToLongBits( other.category_17 ) ) return false; if ( Double.doubleToLongBits( category_8 ) != Double.doubleToLongBits( other.category_8 ) ) return false; if ( Double.doubleToLongBits( category_9 ) != Double.doubleToLongBits( other.category_9 ) ) return false; if ( Double.doubleToLongBits( compensateLeave ) != Double.doubleToLongBits( other.compensateLeave ) ) return false; if ( Double.doubleToLongBits( compensateRemain ) != Double.doubleToLongBits( other.compensateRemain ) ) return false; if ( Double.doubleToLongBits( countDays ) != Double.doubleToLongBits( other.countDays ) ) return false; if ( createDate == null ) { if ( other.createDate != null ) return false; } else if ( !createDate.equals( other.createDate ) ) return false; if ( deptId == null ) { if ( other.deptId != null ) return false; } else if ( !deptId.equals( other.deptId ) ) return false; if ( deptName == null ) { if ( other.deptName != null ) return false; } else if ( !deptName.equals( other.deptName ) ) return false; if ( endDate == null ) { if ( other.endDate != null ) return false; } else if ( !endDate.equals( other.endDate ) ) return false; if ( Double.doubleToLongBits( enventLeave ) != Double.doubleToLongBits( other.enventLeave ) ) return false; if ( id != other.id ) return false; if ( Double.doubleToLongBits( marryLeave ) != Double.doubleToLongBits( other.marryLeave ) ) return false; if ( Double.doubleToLongBits( noCompensateLeave ) != Double.doubleToLongBits( other.noCompensateLeave ) ) return false; if ( Double.doubleToLongBits( otherLeave ) != Double.doubleToLongBits( other.otherLeave ) ) return false; if ( Double.doubleToLongBits( overTime ) != Double.doubleToLongBits( other.overTime ) ) return false; if ( remark1 == null ) { if ( other.remark1 != null ) return false; } else if ( !remark1.equals( other.remark1 ) ) return false; if ( remark2 == null ) { if ( other.remark2 != null ) return false; } else if ( !remark2.equals( other.remark2 ) ) return false; if ( Double.doubleToLongBits( sickLeave ) != Double.doubleToLongBits( other.sickLeave ) ) return false; if ( siteId == null ) { if ( other.siteId != null ) return false; } else if ( !siteId.equals( other.siteId ) ) return false; if ( startDate == null ) { if ( other.startDate != null ) return false; } else if ( !startDate.equals( other.startDate ) ) return false; if ( status == null ) { if ( other.status != null ) return false; } else if ( !status.equals( other.status ) ) return false; if ( Double.doubleToLongBits( subAnualLeave ) != Double.doubleToLongBits( other.subAnualLeave ) ) return false; if ( userId == null ) { if ( other.userId != null ) return false; } else if ( !userId.equals( other.userId ) ) return false; if ( userName == null ) { if ( other.userName != null ) return false; } else if ( !userName.equals( other.userName ) ) return false; if ( userStatus == null ) { if ( other.userStatus != null ) return false; } else if ( !userStatus.equals( other.userStatus ) ) return false; if ( yearLeave != other.yearLeave ) return false; return true; } @Override public String toString() { return "StatVo [id=" + id + ", userId=" + userId + ", userName=" + userName + ", yearLeave=" + yearLeave + ", annualLevel=" + annualLevel + ", annualRemain=" + annualRemain + ", compensateRemain=" + compensateRemain + ", enventLeave=" + enventLeave + ", sickLeave=" + sickLeave + ", marryLeave=" + marryLeave + ", birthLeave=" + birthLeave + ", otherLeave=" + otherLeave + ", overTime=" + overTime + ", compensateLeave=" + compensateLeave + ", noCompensateLeave=" + noCompensateLeave + ", createDate=" + createDate + ", siteId=" + siteId + ", deptId=" + deptId + ", deptName=" + deptName + ", countDays=" + countDays + ", status=" + status + ", userStatus=" + userStatus + ", annual=" + annual + ", startDate=" + startDate + ", endDate=" + endDate + ", subAnualLeave=" + subAnualLeave + ", remark1=" + remark1 + ", remark2=" + remark2 + ", category_8=" + category_8 + ", category_9=" + category_9 + ", category_10=" + category_10 + ", category_11=" + category_11 + ", category_12=" + category_12 + ", category_13=" + category_13 + ", category_14=" + category_14 + ", category_15=" + category_15 + ", category_16=" + category_16 + ", category_17=" + category_17 + "]"; } }
c934f8db605167a02f081373da9c9aa7e99738c6
cfba631fda1652e49a27061e33e382f0f4c0c4d7
/src/com/javarush/test/level16/lesson13/bonus03/Solution.java
f1cc0c89017d3519871f2b9ff7884fe5e733f84c
[]
no_license
Vertugo/JavaRush
ea2c59f4add543250e88c626d4661a9ae2d3b091
f4bc939789082364c57a89a60ae510cdc5f3bbd7
refs/heads/master
2021-01-18T22:23:33.837379
2016-06-27T16:20:45
2016-06-27T16:20:45
60,384,423
0
0
null
null
null
null
UTF-8
Java
false
false
1,851
java
package com.javarush.test.level16.lesson13.bonus03; /* Отдебажим все на свете Разобраться, что делает програма. Почитать про UncaughtExceptionHandler - это важно. Еще раз внимательно посмотреть программу. Разобраться - продебажить - почему наш OurUncaughtExceptionHandler не срабатывает. Исправить ошибку, т.е. все должно работать. :) Ожидаемый результат в произвольном порядке: Нить 1: My exception message Нить 2: My exception message */ public class Solution { public static Thread.UncaughtExceptionHandler handler = new OurUncaughtExceptionHandler(); public static void main(String[] args) { TestedThread commonThread = new TestedThread(handler); Thread threadA = new Thread(commonThread, "Нить 1"); Thread threadB = new Thread(commonThread, "Нить 2"); threadA.start(); threadB.start(); threadA.interrupt(); threadB.interrupt(); } public static class TestedThread extends Thread { public TestedThread(UncaughtExceptionHandler handler) { Thread.setDefaultUncaughtExceptionHandler(handler); start(); } public void run() { try { Thread.sleep(3000); } catch (InterruptedException x) { throw new RuntimeException("My exception message"); } } } public static class OurUncaughtExceptionHandler implements Thread.UncaughtExceptionHandler { @Override public void uncaughtException(Thread t, Throwable e) { System.out.println(t.getName() + ": " + e.getMessage()); } } }
43bddbe84b1a6ff07f7cd1f3469fe0d88d7a4ab9
e716128333435e83b1714e4a417fd99769fb4ffe
/05二叉树/src/com/study/Test/IC.java
64913cbcd73f9fc0e4bdd1274356722addd29ed3
[]
no_license
13669005514/study-data
29ebd20ff7e67f6fb19cb84edadbbba95883f75a
d134ddbb31819cf737cd110cd79d01d68a8958d3
refs/heads/master
2023-06-07T08:01:32.795958
2021-07-06T12:43:37
2021-07-06T12:43:37
357,488,089
0
0
null
null
null
null
UTF-8
Java
false
false
68
java
package com.study.Test; public interface IC { void testC(); }
938d4bb7b37536e17ee6870848e308f4388df030
e0e7e724382e479698f76687fa3ade184a450c10
/app/src/main/java/android/example/com/imageexample/Modal/EstateJson/JsonEstateHolder.java
220c28d34653dd6aa7a30a9dfcc1f8f146fcf3fe
[]
no_license
TuonglLe/RealEstate
480f8b2ac12fd85ec33f6cc9f00b4ee2e9982e94
448cf8f0d1a21a5178c71799c6b16cc90b42065a
refs/heads/master
2020-03-21T22:49:10.867130
2017-07-10T13:32:10
2017-07-10T13:32:10
96,650,708
0
0
null
null
null
null
UTF-8
Java
false
false
1,399
java
package android.example.com.imageexample.Modal.EstateJson; import android.example.com.imageexample.Modal.Estate.Estate; import android.example.com.imageexample.Utils.Utils; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class JsonEstateHolder { @JsonProperty("results") private JsonEstate[] jsonEstates; public JsonEstateHolder() { } public JsonEstate[] getJsonEstates() { return jsonEstates; } public void setJsonEstates(JsonEstate[] jsonEstates) { this.jsonEstates = jsonEstates; } public Estate getFirstEstate() { if(jsonEstates != null && jsonEstates.length > 0) { JsonEstate jsonEstate = jsonEstates[0]; Estate estate = new Estate.Builder() .setLat( jsonEstate.getGeometry().getNativeLocation().getLat()) .setLng( jsonEstate.getGeometry().getNativeLocation().getLng()) .setPrice(Utils.getRandom(Estate.MIN_PRICE, Estate.MAX_PRICE)) .setPlaceId(jsonEstate.getPlaceId()) .setAddress(jsonEstate.getAddress()) .setPostalCode(jsonEstate.getPostalCode()) .build(); return estate; } else { return null; } } }
79f16d05c5beb0bddd20bd414ddb1f661fd42be7
eaec4795e768f4631df4fae050fd95276cd3e01b
/src/cmps252/HW4_2/UnitTesting/record_1273.java
4a4d3e770a3ae12baad81c2cf1c339f8a88b1728
[ "MIT" ]
permissive
baraabilal/cmps252_hw4.2
debf5ae34ce6a7ff8d3bce21b0345874223093bc
c436f6ae764de35562cf103b049abd7fe8826b2b
refs/heads/main
2023-01-04T13:02:13.126271
2020-11-03T16:32:35
2020-11-03T16:32:35
307,839,669
1
0
MIT
2020-10-27T22:07:57
2020-10-27T22:07:56
null
UTF-8
Java
false
false
2,487
java
package cmps252.HW4_2.UnitTesting; import static org.junit.jupiter.api.Assertions.*; import java.io.FileNotFoundException; import java.util.List; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Tag; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import cmps252.HW4_2.Customer; import cmps252.HW4_2.FileParser; @Tag("0") class Record_1273 { private static List<Customer> customers; @BeforeAll public static void init() throws FileNotFoundException { customers = FileParser.getCustomers(Configuration.CSV_File); } @Test @DisplayName("Record 1273: FirstName is Stanley") void FirstNameOfRecord1273() { assertEquals("Stanley", customers.get(1272).getFirstName()); } @Test @DisplayName("Record 1273: LastName is Mechanic") void LastNameOfRecord1273() { assertEquals("Mechanic", customers.get(1272).getLastName()); } @Test @DisplayName("Record 1273: Company is Mabes Clothing & Athl Apprl") void CompanyOfRecord1273() { assertEquals("Mabes Clothing & Athl Apprl", customers.get(1272).getCompany()); } @Test @DisplayName("Record 1273: Address is 2052 E Vernon Ave") void AddressOfRecord1273() { assertEquals("2052 E Vernon Ave", customers.get(1272).getAddress()); } @Test @DisplayName("Record 1273: City is Los Angeles") void CityOfRecord1273() { assertEquals("Los Angeles", customers.get(1272).getCity()); } @Test @DisplayName("Record 1273: County is Los Angeles") void CountyOfRecord1273() { assertEquals("Los Angeles", customers.get(1272).getCounty()); } @Test @DisplayName("Record 1273: State is CA") void StateOfRecord1273() { assertEquals("CA", customers.get(1272).getState()); } @Test @DisplayName("Record 1273: ZIP is 90058") void ZIPOfRecord1273() { assertEquals("90058", customers.get(1272).getZIP()); } @Test @DisplayName("Record 1273: Phone is 323-234-6158") void PhoneOfRecord1273() { assertEquals("323-234-6158", customers.get(1272).getPhone()); } @Test @DisplayName("Record 1273: Fax is 323-234-3064") void FaxOfRecord1273() { assertEquals("323-234-3064", customers.get(1272).getFax()); } @Test @DisplayName("Record 1273: Email is [email protected]") void EmailOfRecord1273() { assertEquals("[email protected]", customers.get(1272).getEmail()); } @Test @DisplayName("Record 1273: Web is http://www.stanleymechanic.com") void WebOfRecord1273() { assertEquals("http://www.stanleymechanic.com", customers.get(1272).getWeb()); } }
729b12bf214ed10a1b4cb56d4a5a3a116661642d
b13cac0b5d884c729a87b09aff0082489489932c
/app/src/main/java/com/edwin/android/cinerd/moviedetail/MovieDetailActivity.java
5f2e13073f92cbc213efdfc99b590fc5c50a4ee7
[]
no_license
edwin9870/CineRD
dd940f426b46d183c478a62d5f34dbb24447934b
e683ceb86464884422a2638fbb09a13928ddeb0f
refs/heads/master
2021-08-08T19:41:52.732006
2017-09-22T02:17:36
2017-09-22T02:17:36
96,147,846
0
0
null
2017-07-13T01:27:48
2017-07-03T20:26:34
Java
UTF-8
Java
false
false
2,414
java
package com.edwin.android.cinerd.moviedetail; import android.app.FragmentManager; import android.app.FragmentTransaction; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.MenuItem; import com.edwin.android.cinerd.R; import com.edwin.android.cinerd.configuration.di.ApplicationModule; import com.edwin.android.cinerd.configuration.di.DaggerDatabaseComponent; import com.edwin.android.cinerd.configuration.di.DatabaseComponent; import com.edwin.android.cinerd.movieposter.MoviePosterFragment; import javax.inject.Inject; public class MovieDetailActivity extends AppCompatActivity { public static final String TAG = MovieDetailActivity.class.getSimpleName(); public static final String BUNDLE_MOVIE_ID = "BUNDLE_MOVIE_ID"; @Inject MovieDetailPresenter moviePosterPresenter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_movie_detail); long movieId = getIntent().getExtras().getLong(BUNDLE_MOVIE_ID, 0); Log.d(TAG, "movieId: " + movieId); MovieDetailFragment movieDetailFragment = (MovieDetailFragment) getFragmentManager().findFragmentById(R.id.fragment_movie_detail); if(movieDetailFragment == null) { FragmentManager fragmentManager = getFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); movieDetailFragment = MovieDetailFragment.newInstance(movieId); fragmentTransaction.add(R.id.fragment_movie_detail, movieDetailFragment); fragmentTransaction.commit(); } Log.d(TAG, "Injection movie poster presenter"); DatabaseComponent databaseComponent = DaggerDatabaseComponent.builder().applicationModule (new ApplicationModule(getApplication())).build(); DaggerMovieDetailComponent.builder().databaseComponent(databaseComponent) .movieDetailPresenterModule(new MovieDetailPresenterModule(movieDetailFragment)) .build().inject(this); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); } return super.onOptionsItemSelected(item); } }
569e0030c6855356f07dc176f93bf534f57d1713
200894e62450b79d11390985c65a310a9fc01bec
/6차 통합erp(물류,인사,회계)전체팀과제 nexacro+spring+mybatis/57thERP/src/main/java/kr/co/seoulit/sys/serviceFacade/BaseServiceFacade.java
f549c015c69403d95fc3fceba1bfacdbcafa00a1
[]
no_license
uneejo/uneejoRepo
8c04e62496d5ac8049ec9a09217d623b7d3da880
e2f7c25f521cc7e0c54ed0ee26707892be25a6a3
refs/heads/master
2022-12-31T11:32:59.175575
2019-06-26T14:20:46
2019-06-26T14:20:46
176,685,478
0
0
null
2022-12-16T01:48:05
2019-03-20T08:11:23
Java
UTF-8
Java
false
false
2,544
java
package kr.co.seoulit.sys.serviceFacade; import java.util.HashMap; import java.util.List; import java.util.Map; import kr.co.seoulit.hr.emp.to.EmployeeTO; import kr.co.seoulit.sys.exception.DeptCodeNotFoundException; import kr.co.seoulit.sys.exception.IdNotFoundException; import kr.co.seoulit.sys.exception.PwMissmatchException; import kr.co.seoulit.sys.to.AuthorityTO; import kr.co.seoulit.sys.to.BaseYearTO; import kr.co.seoulit.sys.to.BusinessPlaceTO; import kr.co.seoulit.sys.to.CodeDetailTO; import kr.co.seoulit.sys.to.CodeTO; import kr.co.seoulit.sys.to.CompanyTO; import kr.co.seoulit.sys.to.CustomerTO; import kr.co.seoulit.sys.to.DepartmentTO; import kr.co.seoulit.sys.to.MenuAuthorityTO; import kr.co.seoulit.sys.to.MenuTO; public interface BaseServiceFacade { public void batchCustomer(List<CustomerTO> batchCustomerList); //거래처 배치프로세스 public void batchBusinessPlace(List<BusinessPlaceTO> batchBusinessPlaceList); //사업처 배치프로세스 public void updateCompanyInfo(List<CompanyTO> companyInfo); //회사정보 수정 public void batchDept(List<DepartmentTO> batchDeptList); //부서 배치프로세스 public List<DepartmentTO> findAllDeptList(); //부서 전체조회 public List<CustomerTO> findCustomerList(); //거래처조회 public List<CompanyTO> findCompanyList(); // 회사정보 조회 public List<CodeTO> findCodeList(); // 코드리스트 조회 public List<CodeTO> batchCodeListProcess(List<CodeTO> codeList); // 코드리스트 tnwjd public List<CodeDetailTO> findCodeDetailList(); // 상세코드리스트 조회 public List<BaseYearTO> findBaseYearList(Map<String,Object> vList); //기초연도조회 public void batchDetailCodeProcess(List<CodeDetailTO> codeDetailList); // DetailCode 변경저장 public List<MenuTO> findMenuList(); public String findSequenceNo(String findSeq); public HashMap<String, Object> accessToAuthority(HashMap<String, Object> loginInfo) throws IdNotFoundException, PwMissmatchException, DeptCodeNotFoundException; public List<BusinessPlaceTO> findBusinessPlaceList(); public List<DepartmentTO> findDepartmentList(Map<String,Object> vList); public List<AuthorityTO> findAuthorityList(); /*로그인*/ public EmployeeTO checkLogin(HashMap<String, Object> loginInfo) throws IdNotFoundException, PwMissmatchException, DeptCodeNotFoundException; public List<MenuAuthorityTO> findMenuAuthorityList(String authorityCode); //로그인 사원의 권한 public String takeSerialCodeTest(HashMap<String, Object> findSeq); }
f7530ed788b93262b0874e8490e874c054c3b42a
a12d2605f40faa4582f88fa01662232a03691027
/tag/10_11_2008_UltimaVersioneSenzaDB_Release_1.0/MsnServer/src/chatserver/threads/ServerAcceptor.java
289c70aff396b6f8175019d361ca2e943298ab19
[]
no_license
gigiigig/Java-Chat
e55280fb0667e039cb798d7e267bc4b18d90dffc
f28a98be362be4c525f793b58529c3ac79c8f30d
refs/heads/master
2020-05-18T08:40:21.146251
2009-10-12T16:38:07
2009-10-12T16:38:07
null
0
0
null
null
null
null
UTF-8
Java
false
false
7,951
java
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package chatserver.threads; import chatcommons.Client; import chatcommons.datamessage.MESSAGE; import chatcommons.datamessage.MessageManger; import chatserver.*; import chatserver.helper.ServerWriter; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; import java.net.SocketException; import java.util.List; import javax.swing.SwingWorker; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import static chatcommons.Commands.*; /** * * @author Administrator */ public class ServerAcceptor extends SwingWorker { private int numPort; private ChatServerView cv; private boolean active; private ServerSocket ss; private Log log = LogFactory.getLog(this.getClass()); public ServerAcceptor(int numPort, ChatServerView cv, boolean active) { super(); this.numPort = numPort; this.cv = cv; this.active = active; } public boolean isActive() { return active; } public void setActive(boolean active) { this.active = active; try { // System.out.println("Active = false"); if (!active) { ss.close(); } } catch (IOException ex) { log.error(ex); } } @Override protected Object doInBackground() throws Exception { try { ServerSocket ss2 = new ServerSocket(numPort); this.ss = ss2; // cv.setServerSocket(ss); Socket clientSocket = null; while (active) { if (!active) { break; } try { clientSocket = ss.accept(); } catch (SocketException e) { log.error(e.getMessage()); break; } cv.getChatText().setText(cv.getChatText().getText().concat("Server - Accepted new Socket on port : " + clientSocket.getPort() + " from ip : "+clientSocket.getInetAddress()+"\n")); log.debug("Server - Accepted new Socket on port : " + clientSocket.getPort() + " from ip : "+clientSocket.getInetAddress()+"\n"); //variabili String nick = ""; String line = ""; ServerWriter sw = new ServerWriter(cv); //leggo il nick e scrivo che s'è connesso sulla chat InputStream is = clientSocket.getInputStream(); BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8")); line = in.readLine(); //richiesta di aggiungere un socket try { MESSAGE message = MessageManger.parseXML(line); log.debug("received MESSAGE : " + MessageManger.messageToStringFormatted(message)); if (message.getType().equals(COMMAND) && message.getName().equals(Command.ADDFILESOCKET)) { String sender = message.getParameters().getParameter().get(0).getValue(); log.debug("add socket to client : " + sender); Client client = null; for (Client elem : cv.getClients()) { if (elem.getNick().equals(sender)) { client = elem; } } client.setFileSenderSocket(clientSocket); ServerReaderXML srxml = new ServerReaderXML(client, cv, ServerReaderXML.FILEREADER); // sr.execute(); srxml.execute(); message.getParameters().getParameter().get(0).setValue(Command.OK); MessageManger.directWriteMessage(message, clientSocket.getOutputStream()); continue; } nick = message.getParameters().getParameter().get(0).getValue(); //verifico se il nick è connesso boolean connesso = false; List<Client> clients = cv.getClients(); for (Client client : clients) { if (client.getNick().equals(nick)) { //se c'è già invio NOK connesso = true; break; } } //invio la rispsta d3el controllo al client //se è connesso scrivo nock e finisco MESSAGE response = MessageManger.createCommand(Command.CONNECT, null); if (connesso) { MessageManger.addParameter(response, "response", Command.KO); MessageManger.directWriteMessage(response, clientSocket.getOutputStream()); clientSocket.close(); //ok starto il colient } else { //il nick è disponibile e scrivo OK MessageManger.addParameter(response, "response", Command.OK); MessageManger.directWriteMessage(response, clientSocket.getOutputStream()); //aspetto che il client dica di aver avviato il tred reader //impedisce che vengano persi dei nick connessi String respSt = in.readLine(); response = MessageManger.parseXML(respSt); log.debug(nick+" response = " + MessageManger.messageToStringFormatted(response)); if (response.getParameters().getParameter().get(0).getValue().equals(Command.OK)) { //dico a tutti di aggiungerlo MESSAGE toSend = MessageManger.createCommand(Command.ADDUSER, null); MessageManger.addParameter(toSend, "nick", nick); log.debug("writeAll : " + toSend); sw.writeAll(toSend); //creo l'oggetto client e lo aggiungo alla lista Client client = new Client(clientSocket, nick); synchronized (cv.getClients()) { cv.getClients().add(client); } //invio al client la lista di utenti connessi for (Client elem : cv.getClients()) { if (elem != client) { toSend = MessageManger.createCommand(Command.ADDUSER, null); MessageManger.addParameter(toSend, "nick", elem.getNick()); sw.writeToClient(nick, toSend); } } //aggiorno la tabella cv.refreshTable(); // ServerReader sr = new ServerReader(client, cv); ServerReaderXML srxml = new ServerReaderXML(client, cv, ServerReaderXML.MAINREADER); // sr.execute(); srxml.execute(); } } } catch (Exception e) { log.debug(e); } } log.info("Chiusura ServerAccptor Thread"); return null; } catch (IOException ex) { log.error(ex); return null; } } }
[ "Administrator@2a2a0caa-3540-4b53-89ca-458ca4f19e0f" ]
Administrator@2a2a0caa-3540-4b53-89ca-458ca4f19e0f
1b54aafa3270d462d2e00e76757a2cce05747192
47f8685b905ed2926ad10e55b49f7f1ed56b0bbd
/java/thebetweenlands/client/render/block/BlockSwampWaterRenderer.java
80bacbe934758885a42effb242cd2bfb55a7cbf0
[]
no_license
Alexander175/The-Betweenlands
98b93bbb840c6be5819c942076cc42bf98259e39
e2e4a6127ace1e4040eb72cf0333f5fd8238cd98
refs/heads/master
2021-01-15T13:07:50.584417
2015-04-26T20:59:46
2015-04-26T20:59:46
null
0
0
null
null
null
null
UTF-8
Java
false
false
10,293
java
package thebetweenlands.client.render.block; import org.lwjgl.input.Mouse; import net.minecraft.block.Block; import net.minecraft.block.BlockLiquid; import net.minecraft.block.material.Material; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.util.IIcon; import net.minecraft.util.MathHelper; import net.minecraft.util.MovingObjectPosition; import net.minecraft.world.IBlockAccess; import thebetweenlands.blocks.terrain.BlockSwampWater; import thebetweenlands.client.render.block.water.IWaterRenderer; import thebetweenlands.proxy.ClientProxy.BlockRenderIDs; import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; public class BlockSwampWaterRenderer implements ISimpleBlockRenderingHandler { @Override public void renderInventoryBlock(Block block, int metadata, int modelID, RenderBlocks renderer) { IWaterRenderer specialRenderer = ((BlockSwampWater)block).getSpecialRenderer(); if(specialRenderer != null) { specialRenderer.renderInventoryBlock(block, metadata, modelID, renderer); } } @Override public boolean renderWorldBlock(IBlockAccess blockAccess, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) { Tessellator tessellator = Tessellator.instance; int colorMultiplier = block.colorMultiplier(blockAccess, x, y, z); float colorR = (float)(colorMultiplier >> 16 & 255) / 255.0F; float colorG = (float)(colorMultiplier >> 8 & 255) / 255.0F; float colorB = (float)(colorMultiplier & 255) / 255.0F; boolean isBreakingBlock = renderer.overrideBlockTexture != null; boolean renderTop = block.shouldSideBeRendered(blockAccess, x, y + 1, z, 1); boolean renderBottom = block.shouldSideBeRendered(blockAccess, x, y - 1, z, 0); boolean[] renderSides = new boolean[] {block.shouldSideBeRendered(blockAccess, x, y, z - 1, 2), block.shouldSideBeRendered(blockAccess, x, y, z + 1, 3), block.shouldSideBeRendered(blockAccess, x - 1, y, z, 4), block.shouldSideBeRendered(blockAccess, x + 1, y, z, 5)}; IWaterRenderer specialRenderer = ((BlockSwampWater)block).getSpecialRenderer(); if(specialRenderer != null) { tessellator.setBrightness(blockAccess.getLightBrightnessForSkyBlocks(x, y, z, 0)); specialRenderer.renderWorldBlock(blockAccess, x, y, z, block, modelId, renderer); } if (isBreakingBlock || !renderTop && !renderBottom && !renderSides[0] && !renderSides[1] && !renderSides[2] && !renderSides[3]) { return false; } else { boolean flag2 = false; float f3 = 0.5F; float colorMult = 1.0F; tessellator.setColorOpaque_F(colorMult * colorR, colorMult * colorG, colorMult * colorB); float f5 = 0.8F; float f6 = 0.6F; double d0 = 0.0D; double d1 = 1.0D; int i1 = blockAccess.getBlockMetadata(x, y, z); Material material = block.getMaterial(); double wch = (double)getLiquidHeight(blockAccess, x, y, z, Material.water); double wzh = (double)getLiquidHeight(blockAccess, x, y, z + 1, Material.water); double wxzh = (double)getLiquidHeight(blockAccess, x + 1, y, z + 1, Material.water); double wxh = (double)getLiquidHeight(blockAccess, x + 1, y, z, Material.water); double minHeightSub = 0.0010000000474974513D; float f9; float f10; float f11; if (renderer.renderAllFaces || renderTop) { flag2 = true; IIcon iicon = renderer.getBlockIconFromSideAndMetadata(block, 1, i1); float f7 = 0.0f; if(material == Material.water || material == Material.lava) { f7 = (float)BlockLiquid.getFlowDirection(blockAccess, x, y, z, material); } else { f7 = (float)((BlockSwampWater)block).getFlowDirection(blockAccess, x, y, z); } if (f7 > -999.0F) { iicon = renderer.getBlockIconFromSideAndMetadata(block, 2, i1); } wch -= minHeightSub; wzh -= minHeightSub; wxzh -= minHeightSub; wxh -= minHeightSub; double d7; double d8; double d10; double d12; double d14; double d16; double d18; double d20; if (f7 < -999.0F) { d7 = (double)iicon.getInterpolatedU(0.0D); d14 = (double)iicon.getInterpolatedV(0.0D); d8 = d7; d16 = (double)iicon.getInterpolatedV(16.0D); d10 = (double)iicon.getInterpolatedU(16.0D); d18 = d16; d12 = d10; d20 = d14; } else { f9 = MathHelper.sin(f7) * 0.25F; f10 = MathHelper.cos(f7) * 0.25F; f11 = 8.0F; d7 = (double)iicon.getInterpolatedU((double)(8.0F + (-f10 - f9) * 16.0F)); d14 = (double)iicon.getInterpolatedV((double)(8.0F + (-f10 + f9) * 16.0F)); d8 = (double)iicon.getInterpolatedU((double)(8.0F + (-f10 + f9) * 16.0F)); d16 = (double)iicon.getInterpolatedV((double)(8.0F + (f10 + f9) * 16.0F)); d10 = (double)iicon.getInterpolatedU((double)(8.0F + (f10 + f9) * 16.0F)); d18 = (double)iicon.getInterpolatedV((double)(8.0F + (f10 - f9) * 16.0F)); d12 = (double)iicon.getInterpolatedU((double)(8.0F + (f10 - f9) * 16.0F)); d20 = (double)iicon.getInterpolatedV((double)(8.0F + (-f10 - f9) * 16.0F)); } tessellator.setBrightness(block.getMixedBrightnessForBlock(blockAccess, x, y, z)); tessellator.setColorOpaque_F(colorMult * colorR, colorMult * colorG, colorMult * colorB); tessellator.addVertexWithUV((double)(x + 0), (double)y + wch, (double)(z + 0), d7, d14); tessellator.addVertexWithUV((double)(x + 0), (double)y + wzh, (double)(z + 1), d8, d16); tessellator.addVertexWithUV((double)(x + 1), (double)y + wxzh, (double)(z + 1), d10, d18); tessellator.addVertexWithUV((double)(x + 1), (double)y + wxh, (double)(z + 0), d12, d20); tessellator.addVertexWithUV((double)(x + 0), (double)y + wch, (double)(z + 0), d7, d14); tessellator.addVertexWithUV((double)(x + 1), (double)y + wxh, (double)(z + 0), d12, d20); tessellator.addVertexWithUV((double)(x + 1), (double)y + wxzh, (double)(z + 1), d10, d18); tessellator.addVertexWithUV((double)(x + 0), (double)y + wzh, (double)(z + 1), d8, d16); } if (renderer.renderAllFaces || renderBottom) { if(blockAccess.getBlock(x, y-1, z) instanceof BlockSwampWater == false) { tessellator.setBrightness(block.getMixedBrightnessForBlock(blockAccess, x, y - 1, z)); tessellator.setColorOpaque_F(colorMult * colorR, colorMult * colorG, colorMult * colorB); renderer.renderFaceYNeg(block, (double)x, (double)y + minHeightSub, (double)z, renderer.getBlockIconFromSide(block, 0)); flag2 = true; } } for (int k1 = 0; k1 < 4; ++k1) { int l1 = x; int j1 = z; if (k1 == 0) { j1 = z - 1; } if (k1 == 1) { ++j1; } if (k1 == 2) { l1 = x - 1; } if (k1 == 3) { ++l1; } IIcon iicon1 = renderer.getBlockIconFromSideAndMetadata(block, k1 + 2, i1); if (renderer.renderAllFaces || renderSides[k1]) { double d9; double d11; double d13; double d15; double d17; double d19; if (k1 == 0) { d9 = wch; d11 = wxh; d13 = (double)x; d17 = (double)(x + 1); d15 = (double)z + minHeightSub; d19 = (double)z + minHeightSub; } else if (k1 == 1) { d9 = wxzh; d11 = wzh; d13 = (double)(x + 1); d17 = (double)x; d15 = (double)(z + 1) - minHeightSub; d19 = (double)(z + 1) - minHeightSub; } else if (k1 == 2) { d9 = wzh; d11 = wch; d13 = (double)x + minHeightSub; d17 = (double)x + minHeightSub; d15 = (double)(z + 1); d19 = (double)z; } else { d9 = wxh; d11 = wxzh; d13 = (double)(x + 1) - minHeightSub; d17 = (double)(x + 1) - minHeightSub; d15 = (double)z; d19 = (double)(z + 1); } flag2 = true; float f8 = iicon1.getInterpolatedU(0.0D); f9 = iicon1.getInterpolatedU(8.0D); f10 = iicon1.getInterpolatedV((1.0D - d9) * 16.0D * 0.5D); f11 = iicon1.getInterpolatedV((1.0D - d11) * 16.0D * 0.5D); float f12 = iicon1.getInterpolatedV(8.0D); tessellator.setBrightness(block.getMixedBrightnessForBlock(blockAccess, l1, y, j1)); float f13 = 1.0F; f13 *= k1 < 2 ? f5 : f6; tessellator.setColorOpaque_F(colorMult * f13 * colorR, colorMult * f13 * colorG, colorMult * f13 * colorB); tessellator.addVertexWithUV(d13, (double)y + d9, d15, (double)f8, (double)f10); tessellator.addVertexWithUV(d17, (double)y + d11, d19, (double)f9, (double)f11); tessellator.addVertexWithUV(d17, (double)(y + 0), d19, (double)f9, (double)f12); tessellator.addVertexWithUV(d13, (double)(y + 0), d15, (double)f8, (double)f12); tessellator.addVertexWithUV(d13, (double)(y + 0), d15, (double)f8, (double)f12); tessellator.addVertexWithUV(d17, (double)(y + 0), d19, (double)f9, (double)f12); tessellator.addVertexWithUV(d17, (double)y + d11, d19, (double)f9, (double)f11); tessellator.addVertexWithUV(d13, (double)y + d9, d15, (double)f8, (double)f10); } } renderer.renderMinY = d0; renderer.renderMaxY = d1; return flag2; } } public float getLiquidHeight(IBlockAccess blockAccess, int x, int y, int z, Material liquidMaterial) { int l = 0; float f = 0.0F; for (int sb = 0; sb < 4; ++sb) { int xp = x - (sb & 1); int zp = z - (sb >> 1 & 1); if (blockAccess.getBlock(xp, y + 1, zp).getMaterial() == liquidMaterial) { return 1.0F; } if(blockAccess.getBlock(xp, y, zp) instanceof BlockSwampWater) { f += 1.1 - ((BlockSwampWater)blockAccess.getBlock(xp, y, zp)).getQuantaPercentage(blockAccess, xp, y, zp); ++l; } else { Material material = blockAccess.getBlock(xp, y, zp).getMaterial(); if (material == liquidMaterial) { int l1 = blockAccess.getBlockMetadata(xp, y, zp); if (l1 >= 8 || l1 == 0) { f += BlockLiquid.getLiquidHeightPercent(l1) * 10.0F; l += 10; } f += BlockLiquid.getLiquidHeightPercent(l1); ++l; } else if (!material.isSolid()) { ++f; ++l; } } } return 1.0F - f / (float)l; } @Override public boolean shouldRender3DInInventory(int modelId) { return true; } @Override public int getRenderId() { return BlockRenderIDs.SWAMP_WATER.id(); } }
9720a7f82d8ce89dedbf0b04af87530bc18de751
7a8a12efa7caf74bf45feedcbfa1dc14404d28b8
/src/one/lindegaard/MobHunting/Version.java
1e43948bea09929de5eea7b58149b5f99ba3c46d
[]
no_license
Connierific/MobHunting
d9fd0c0b7c4c9863d143caadb28bd363955bde38
03f404ffcb805dba3fd506e531e1d55d00d080bc
refs/heads/master
2021-01-11T20:27:03.026662
2017-02-03T14:35:41
2017-02-03T14:35:41
79,118,715
0
0
null
2017-02-03T14:35:43
2017-01-16T13:02:45
Java
UTF-8
Java
false
false
1,243
java
package one.lindegaard.MobHunting; public class Version implements Comparable<Version> { private String version; public final String get() { return this.version; } public Version(String version) { if (version == null) throw new IllegalArgumentException("Version can not be null"); if (!version.matches("v?n[0-9]+(\\.[0-9]+)*")) throw new IllegalArgumentException("Invalid version format"); this.version = version; } @Override public int compareTo(Version that) { if (that == null) return 1; String[] thisParts = this.get().split("v?n[0-9]+(\\.[0-9]+)*"); String[] thatParts = that.get().split("v?n[0-9]+(\\.[0-9]+)*"); int length = Math.max(thisParts.length, thatParts.length); for (int i = 0; i < length; i++) { int thisPart = i < thisParts.length ? Integer.parseInt(thisParts[i]) : 0; int thatPart = i < thatParts.length ? Integer.parseInt(thatParts[i]) : 0; if (thisPart < thatPart) return -1; if (thisPart > thatPart) return 1; } return 0; } @Override public boolean equals(Object that) { if (this == that) return true; if (that == null) return false; if (this.getClass() != that.getClass()) return false; return this.compareTo((Version) that) == 0; } }
1ec2a11adbbed7839e2b556ed061392d95f3d32b
b5329ad4d7bf69d9bb7d84c8319158c14e5c99aa
/src/tsgen/src/main/java/br/ufscar/dc/compiladores/tsgen/tsgenGenerator.java
246236f4eff5fc2bf2192f09e4ecc2e559640cf6
[]
no_license
joaovicmendes/ts-api-generator
384138e3b9f95978f32c5aeb1c6f715cda2e221a
35d6aa87f114cce7da11d44c7866f89b512c35b2
refs/heads/main
2023-09-02T18:47:46.876625
2021-11-21T14:30:26
2021-11-21T14:30:26
427,732,484
1
0
null
null
null
null
UTF-8
Java
false
false
7,025
java
package br.ufscar.dc.compiladores.tsgen; import br.ufscar.dc.compiladores.parser.tsgenBaseVisitor; import br.ufscar.dc.compiladores.parser.tsgenParser; import org.antlr.v4.runtime.Token; import java.util.HashMap; import java.util.Map; public class tsgenGenerator extends tsgenBaseVisitor<Void> { Map<String, ModelClass> models; Map<String, Endpoint> endpoints; public StringBuilder outputCode; @Override public Void visitProgram(tsgenParser.ProgramContext ctx) { models = new HashMap<>(); endpoints = new HashMap<>(); outputCode = new StringBuilder(); outputCode.append("import express from 'express';\n"); outputCode.append("import { Sequelize, Model, DataTypes } from 'sequelize';\n\n"); outputCode.append("const port = process.env.PORT || 3000;\n"); outputCode.append("const app = express();\n"); outputCode.append("app.use(express.json());\n"); outputCode.append("const sequelize = new Sequelize('sqlite::memory:');\n\n"); super.visitProgram(ctx); outputCode.append("app.listen(port, () => {\n"); outputCode.append(" console.log(`Server running at localhost:${port}`);\n"); outputCode.append("});\n"); return null; } @Override public Void visitModels(tsgenParser.ModelsContext ctx) { outputCode.append("// model\n"); super.visitModels(ctx); outputCode.append("const initModel = async () => {\n"); outputCode.append(" await sequelize.sync();\n"); outputCode.append("}\n"); outputCode.append("initModel();\n"); outputCode.append("// model-end\n\n"); return null; } @Override public Void visitModel(tsgenParser.ModelContext ctx) { String id = ctx.IDENT().getText(); ModelClass modelClass = new ModelClass(); for (var field : ctx.fields) { String fieldName = field.ident.getText(); Type type = Utils.mapStringToType( field.type.getText() ); modelClass.add(type, fieldName); } models.put(id, modelClass); outputCode.append("class "); outputCode.append(id); outputCode.append(" extends Model {};\n"); outputCode.append(id); outputCode.append(".init({\n"); for (var field : modelClass.fields) { outputCode.append(" "); outputCode.append(field.id()); outputCode.append(": "); outputCode.append(Utils.mapTypeToSequelize(field.type())); outputCode.append(",\n"); } outputCode.append(" }, {sequelize, modelName: '"); outputCode.append(id); outputCode.append("'}\n"); outputCode.append(");\n\n"); return super.visitModel(ctx); } @Override public Void visitEndpoints(tsgenParser.EndpointsContext ctx) { outputCode.append("// endpoints\n"); super.visitEndpoints(ctx); outputCode.append("// endpoints-end\n\n"); return null; } @Override public Void visitEndpoint(tsgenParser.EndpointContext ctx) { String id = ctx.IDENT().getText(); Endpoint currEndpoint = new Endpoint(); for (var route : ctx.routes) { String uri = route.STRING().getText(); Route.Method method = Utils.mapStringToMethod(route.method().getText()); currEndpoint.add(method, uri); } endpoints.put(id, currEndpoint); for (var route : currEndpoint.routes) { generateRouteCode(id, route); } return super.visitEndpoint(ctx); } private void generateRouteCode(String id, Route route) { switch (route.method) { case GET: generateGetCode(id, route.uri); break; case POST: generatePostCode(id, route.uri); break; case PUT: generatePutCode(id, route.uri); break; case DELETE: generateDeleteCode(id, route.uri); break; } } private void generateGetCode(String id, String uri) { outputCode.append("app.get("); outputCode.append(uri); outputCode.append(", async (req, res) => {\n"); outputCode.append(" const variable = await "); outputCode.append(id); String routeId = Utils.extractRouteId(uri); if (routeId == null) { outputCode.append(".findAll();\n"); } else { outputCode.append(".findOne({\n"); outputCode.append(" where: {\n"); outputCode.append(" "); outputCode.append(routeId); outputCode.append(": req.params."); outputCode.append(routeId); outputCode.append("\n }\n"); outputCode.append(" });\n"); } outputCode.append(" res.status(200).send(JSON.stringify(variable));\n"); outputCode.append("});\n\n"); } private void generatePostCode(String id, String uri) { outputCode.append("app.post("); outputCode.append(uri); outputCode.append(", async (req, res) => {\n"); outputCode.append(" const variable = await "); outputCode.append(id); outputCode.append(".create(req.body);\n"); outputCode.append(" res.status(200).send(JSON.stringify(variable));\n"); outputCode.append("});\n\n"); } private void generatePutCode(String id, String uri) { outputCode.append("app.put("); outputCode.append(uri); outputCode.append(", async (req, res) => {\n"); outputCode.append(" "); outputCode.append(id); String routeId = Utils.extractRouteId(uri); outputCode.append(".update(req.body, {\n"); outputCode.append(" where: {\n"); outputCode.append(" "); outputCode.append(routeId); outputCode.append(": req.params."); outputCode.append(routeId); outputCode.append("\n }\n"); outputCode.append(" });\n"); outputCode.append(" res.status(200).send();\n"); outputCode.append("});\n\n"); } private void generateDeleteCode(String id, String uri) { outputCode.append("app.delete("); outputCode.append(uri); outputCode.append(", async (req, res) => {\n"); outputCode.append(" "); outputCode.append(id); String routeId = Utils.extractRouteId(uri); outputCode.append(".destroy({\n"); outputCode.append(" where: {\n"); outputCode.append(" "); outputCode.append(routeId); outputCode.append(": req.params."); outputCode.append(routeId); outputCode.append("\n }\n"); outputCode.append(" });\n"); outputCode.append(" res.status(200).send();\n"); outputCode.append("});\n\n"); } }
9db01ee6c1d20cb605d524758f2eaad9e1ed9615
bf2966abae57885c29e70852243a22abc8ba8eb0
/aws-java-sdk-s3control/src/main/java/com/amazonaws/services/s3control/model/LifecycleConfiguration.java
922dc52f51ee11e6c862037f80149c293cf31250
[ "Apache-2.0" ]
permissive
kmbotts/aws-sdk-java
ae20b3244131d52b9687eb026b9c620da8b49935
388f6427e00fb1c2f211abda5bad3a75d29eef62
refs/heads/master
2021-12-23T14:39:26.369661
2021-07-26T20:09:07
2021-07-26T20:09:07
246,296,939
0
0
Apache-2.0
2020-03-10T12:37:34
2020-03-10T12:37:33
null
UTF-8
Java
false
false
4,947
java
/* * Copyright 2016-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.s3control.model; import java.io.Serializable; import javax.annotation.Generated; /** * <p> * The container for the Outposts bucket lifecycle configuration. * </p> * * @see <a href="http://docs.aws.amazon.com/goto/WebAPI/s3control-2018-08-20/LifecycleConfiguration" target="_top">AWS * API Documentation</a> */ @Generated("com.amazonaws:aws-java-sdk-code-generator") public class LifecycleConfiguration implements Serializable, Cloneable { /** * <p> * A lifecycle rule for individual objects in an Outposts bucket. * </p> */ private java.util.List<LifecycleRule> rules; /** * <p> * A lifecycle rule for individual objects in an Outposts bucket. * </p> * * @return A lifecycle rule for individual objects in an Outposts bucket. */ public java.util.List<LifecycleRule> getRules() { return rules; } /** * <p> * A lifecycle rule for individual objects in an Outposts bucket. * </p> * * @param rules * A lifecycle rule for individual objects in an Outposts bucket. */ public void setRules(java.util.Collection<LifecycleRule> rules) { if (rules == null) { this.rules = null; return; } this.rules = new java.util.ArrayList<LifecycleRule>(rules); } /** * <p> * A lifecycle rule for individual objects in an Outposts bucket. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if any). Use * {@link #setRules(java.util.Collection)} or {@link #withRules(java.util.Collection)} if you want to override the * existing values. * </p> * * @param rules * A lifecycle rule for individual objects in an Outposts bucket. * @return Returns a reference to this object so that method calls can be chained together. */ public LifecycleConfiguration withRules(LifecycleRule... rules) { if (this.rules == null) { setRules(new java.util.ArrayList<LifecycleRule>(rules.length)); } for (LifecycleRule ele : rules) { this.rules.add(ele); } return this; } /** * <p> * A lifecycle rule for individual objects in an Outposts bucket. * </p> * * @param rules * A lifecycle rule for individual objects in an Outposts bucket. * @return Returns a reference to this object so that method calls can be chained together. */ public LifecycleConfiguration withRules(java.util.Collection<LifecycleRule> rules) { setRules(rules); return this; } /** * Returns a string representation of this object. This is useful for testing and debugging. Sensitive data will be * redacted from this string using a placeholder value. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getRules() != null) sb.append("Rules: ").append(getRules()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof LifecycleConfiguration == false) return false; LifecycleConfiguration other = (LifecycleConfiguration) obj; if (other.getRules() == null ^ this.getRules() == null) return false; if (other.getRules() != null && other.getRules().equals(this.getRules()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getRules() == null) ? 0 : getRules().hashCode()); return hashCode; } @Override public LifecycleConfiguration clone() { try { return (LifecycleConfiguration) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException("Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
[ "" ]
345b37d6ca13594e0eec75f1e36f31b48f3fd6ae
563325e9d6b4196c789066b4ebbebae84021e86d
/src/test/java/com/marom/recipe/converters/CategoryToCategoryCommandTest.java
986c212e179013f668e6553617e1018575861a67
[]
no_license
marom/RecipesCollection
a265ac6db80061aac4aec090ab79f4682eabf522
a6a41ac43294c3c40aca69da935588adbf4c3294
refs/heads/master
2020-04-24T22:57:40.987515
2019-03-11T17:16:24
2019-03-11T17:16:24
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,193
java
package com.marom.recipe.converters; import com.marom.recipe.commands.CategoryCommand; import com.marom.recipe.domain.Category; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class CategoryToCategoryCommandTest { public static final Long ID_VALUE = new Long(1L); public static final String DESCRIPTION = "descript"; CategoryToCategoryCommand convter; @Before public void setUp() throws Exception { convter = new CategoryToCategoryCommand(); } @Test public void testNullObject() throws Exception { assertNull(convter.convert(null)); } @Test public void testEmptyObject() throws Exception { assertNotNull(convter.convert(new Category())); } @Test public void convert() throws Exception { //given Category category = new Category(); category.setId(ID_VALUE); category.setDescription(DESCRIPTION); //when CategoryCommand categoryCommand = convter.convert(category); //then assertEquals(ID_VALUE, categoryCommand.getId()); assertEquals(DESCRIPTION, categoryCommand.getDescription()); } }
3a8a033487fc4ed01e20e79541c773c9133b46b2
4cde67c3355ee7bb74b98a0e934161c44c70eead
/microservicecloud/microservicecloud-eureka-7002/src/main/java/com/atguigu/springcloud/EurekaServer7002_App.java
584dc9a54d6f3db9b888d2e4620fe2a6dbc0ae68
[]
no_license
mikasamikodu/java_project
678f9edcbdbb01b6484f032c721df3cd83ffe626
39af08ee7d0543fb1b8dba30b0cc1fec99345b0e
refs/heads/master
2022-12-27T22:17:55.784040
2020-12-18T13:03:30
2020-12-18T13:03:30
206,045,260
1
0
null
2022-12-16T02:51:17
2019-09-03T09:55:36
Python
UTF-8
Java
false
false
493
java
package com.atguigu.springcloud; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.cloud.netflix.eureka.server.EnableEurekaServer; @SpringBootApplication @EnableEurekaServer//EurekaServer服务器端启动类,接受其它微服务注册进来 public class EurekaServer7002_App { public static void main(String[] args) { SpringApplication.run(EurekaServer7002_App.class, args); } }
30866b9e3908071c575b54728969f4d1faae984e
427693c309f24ed51af7a1bf1718bdc24650d434
/dictionary-server/src/DictionaryServer.java
b00e6897244d9ee563abaf20c2f6aac2a13587fe
[]
no_license
GulerayGizemFELEK/dictionary
5df8e9d49b76d33983d94faf661656edebf9e822
120375935064f15211bb9e713ddf8ed5e6d6ef1d
refs/heads/master
2020-11-28T18:37:06.339073
2016-09-08T19:14:23
2016-09-08T19:14:23
67,732,812
0
0
null
null
null
null
ISO-8859-9
Java
false
false
3,767
java
import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.RandomAccessFile; import java.net.ServerSocket; import java.net.Socket; import java.util.HashMap; import java.util.Map.Entry; public class DictionaryServer { private HashMap<String,String> _dictionary = new HashMap<String,String>(); public DictionaryServer(){ try { readDictionary(); runServer(); } catch (IOException e) { e.printStackTrace(); } } private void runServer() throws IOException{ ServerSocket dictionarySocket = new ServerSocket(2008); System.out.println("Sunucu uygulaması 2008 kapı adresinde gelen bağlantıları bekliyor."); while(true){ Socket gelenBaglanti = dictionarySocket.accept(); System.out.println(gelenBaglanti.getRemoteSocketAddress().toString()+ " adresinden yeni bir bağlantı alındı."); runClient(gelenBaglanti); } } private void runClient(final Socket istemci) throws IOException{ /* İstemci için yeni bir iş parçacığı yaratalım */ new Thread(new Runnable(){ public void run() { /* Buradaki method asenkronize olarak çalışacak */ try { /* İstemciden veri okumak ve yazmak için, * okuyucu ve yazıcı yaratalım. */ System.out.println("İstemci asenkronize olarak çalışıyor."); InputStream gelenAkis = istemci.getInputStream(); OutputStream gidenAkis = istemci.getOutputStream(); BufferedReader okuyucu = new BufferedReader(new InputStreamReader(gelenAkis)); BufferedWriter yazici = new BufferedWriter(new OutputStreamWriter(gidenAkis)); String gelenIstek = null; /* İstemciden gelen istekleri oku */ while((gelenIstek =okuyucu.readLine()) != null){ System.out.println(istemci.getRemoteSocketAddress() + " istemcisinden gelen istek : " + gelenIstek); String cevap = null; /* Önce kelimeyi ingilizce varsayıp, türkçeye çevirmeye çalışalım */ cevap = eslesenTurkceKelimeyiBul(gelenIstek); /* Eğer eşleşen kelime bulunamadıysa, kelimeyi türkçe varsayıp ingilizceye çevirmeye çalışalım */ if(cevap == null) cevap = eslesenIngilizceKelimeyiBul(gelenIstek); /* Bulunan cevabı istemciye gönderelim */ yazici.write(cevap+"\r\n"); yazici.flush(); } /* Döngü bittiğine göre istemci bağlantıyı kapatmış olmalı, * yazıcımızı ve okuyucumuzu kapatalım. */ okuyucu.close(); yazici.close(); System.out.println("İstemci bağlantısı koptu."); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }).start(); } private void readDictionary() throws IOException{ RandomAccessFile raf = new RandomAccessFile("dictionary.txt","r"); String line = ""; while((line = raf.readLine()) != null){ String[] ayrilan = line.split(" "); String en = ayrilan[0]; String tr = ayrilan[1]; _dictionary.put(en, tr); } } private String eslesenTurkceKelimeyiBul(String ingilizceKelime){ for(Entry<String, String> entry : _dictionary.entrySet()) { String enDeger = entry.getKey(); if(enDeger.compareTo(ingilizceKelime) == 0) return entry.getValue(); } return null; } private String eslesenIngilizceKelimeyiBul(String turkceKelime){ for(Entry<String, String> entry : _dictionary.entrySet()) { String trDeger = entry.getValue(); if(trDeger.compareTo(turkceKelime) == 0) return entry.getKey(); } return null; } public static void main(String[] args) { // TODO Auto-generated method stub DictionaryServer abc = new DictionaryServer(); } }
9b1886160ba1454c303f4ab3ad4986c30781d858
733e1e95ba1f758c33dd24d48682be10e800c8d7
/src/main/java/br/com/ifce/controller/RTecnicoResultadoController.java
c07a3deb41ca42ee73e14020d0f7ccb2c933e7a8
[]
no_license
MardonioEng/BadCodeClinic
f22bf4867a291a9f4bfc15609e0eb112fce36094
d93f0a5054fdb8f3177cc4b0abe0787cb0d8aede
refs/heads/master
2022-12-16T14:16:10.732400
2020-09-28T13:19:26
2020-09-28T13:19:26
297,795,665
1
0
null
null
null
null
UTF-8
Java
false
false
935
java
package br.com.ifce.controller; import java.net.URL; import java.util.ResourceBundle; import com.jfoenix.controls.JFXButton; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.control.ComboBox; import javafx.scene.control.TextField; public class RTecnicoResultadoController implements Initializable { @FXML private TextField tfNome; @FXML private TextField tfCpf; @FXML private TextField tfDataNascimento; @FXML private TextField tfRg; @FXML private ComboBox<?> cbSexo; @FXML private TextField tfComorbidade; @FXML private ComboBox<?> cbConclusao; @FXML private TextField tfDataExame; @FXML private JFXButton btnSair; @FXML private JFXButton btnSalvar; @Override public void initialize(URL location, ResourceBundle resources) { } @FXML void onBtnSairAction(ActionEvent event) { } @FXML void onBtnSalvarAction(ActionEvent event) { } }
c3410ece03f2bed487ecced002ed9b4e2034fe7c
c6cb3392dba28b0b3e1ffe8b9def1ecc972c6246
/Praew25.java
82aa4854f81063a674d833d5ee334deb94be92e4
[]
no_license
praew06/java_pyramid
20c74f0ef8d6887abd806c95c30cd9958c319b80
26bf1d7290714d904ca52196249c0ad079d90af4
refs/heads/master
2020-07-15T19:51:25.848513
2019-09-01T06:21:11
2019-09-01T06:21:11
205,637,645
0
0
null
null
null
null
UTF-8
Java
false
false
474
java
public class Praew25 { public static void main(String den[]){ int Praew=5; for(int P=1;P<=Praew;P++){ for(int j=P;j<Praew;j++){ System.out.print("*"); } for(int j=1;j<=P*2-1;j++){ System.out.print(Praew-P+1); } for(int j=P;j<=Praew;j++){ System.out.print("*"); } System.out.println(); } } }
38d49bbc0bab8a4619e860d29d2275ce39240301
81f9299db901e5e41eb684454937df5d111320d5
/app/src/androidTest/java/com/websarva/wings/android/baseballstartinglineup/ExampleInstrumentedTest.java
bf4aa766718b026bc0bf95341e704b87914969dc
[]
no_license
korosaka/baseball_lineup_EN_new
22ab7dfe170550344b0594d0bd4ad6e5b500814b
bc4926be0d4453b3fdc4c61ac277684a5755fc3f
refs/heads/develop
2022-12-15T20:48:41.711416
2020-09-13T16:06:37
2020-09-13T16:06:37
294,063,528
0
0
null
2020-09-13T16:04:29
2020-09-09T09:18:28
Java
UTF-8
Java
false
false
814
java
package com.websarva.wings.android.baseballstartinglineup; import android.content.Context; import androidx.test.platform.app.InstrumentationRegistry; import androidx.test.ext.junit.runners.AndroidJUnit4; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.*; /** * Instrumented test, which will execute on an Android device. * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ @RunWith(AndroidJUnit4.class) public class ExampleInstrumentedTest { @Test public void useAppContext() { // Context of the app under test. Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext(); assertEquals("com.websarva.wings.android.baseballstartinglineup", appContext.getPackageName()); } }
3e254928569bd588878794727285b52cbf1c8c5e
907ea8b2e3af5035ee640c95c646d6a04a192d41
/xTotem/src/be/ac/ulg/montefiore/run/totem/scenario/model/jaxb/GenerateIntraTM.java
a58dc430fa4202c9e780ea7e11edf1f7a487fb17
[]
no_license
cuchy/TTools
8869ee47d3c489d95fa2c8b454757aee521cd705
37527c5a60360f0ddef7398a34296ab332810e0c
refs/heads/master
2021-01-11T10:39:05.100786
2016-11-05T21:25:29
2016-11-05T21:25:29
72,948,537
0
1
null
null
null
null
UTF-8
Java
false
false
2,061
java
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v1.0.4-b18-fcs // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2008.03.28 at 12:33:07 CET // package be.ac.ulg.montefiore.run.totem.scenario.model.jaxb; /** * Java content class for generateIntraTM element declaration. * <p>The following schema fragment specifies the expected content contained within this java content object. (defined at file:/home/hakan/svn-totem/totem/trunk/run-totem/src/resources/scenario/Scenario-v1_3.xsd line 635) * <p> * <pre> * &lt;element name="generateIntraTM"> * &lt;complexType> * &lt;complexContent> * &lt;extension base="{http://jaxb.model.scenario.totem.run.montefiore.ulg.ac.be}eventType"> * &lt;attribute name="BGPbaseDirectory" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="BGPdirFileName" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="NETFLOWbaseDirectory" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="NETFLOWdirFileName" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="clusterFileName" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;attribute name="minutes" use="required" type="{http://www.w3.org/2001/XMLSchema}int" /> * &lt;attribute name="samplingRate" use="required" type="{http://www.w3.org/2001/XMLSchema}int" /> * &lt;attribute name="trafficMatrixFileName" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * &lt;/element> * </pre> * */ public interface GenerateIntraTM extends javax.xml.bind.Element, be.ac.ulg.montefiore.run.totem.scenario.model.jaxb.GenerateIntraTMType { }
19ea83ede8dbd10749abc0c2ccc876e580fb767d
d4b565b5cd2bc8c57ac777e8aa529cf375d8b6da
/src/main/java/com/leeo/web/service/ResourceService.java
e28d65c0a42f40fdb487c8df23995bbaa25a3fd6
[ "Apache-2.0" ]
permissive
Leeo1124/test
6c88b9217fe274b1c685133edd9f2e62ee33241b
671c2b34dc4a75e64888e52739b6bd09107f74dc
refs/heads/master
2021-01-10T16:57:28.870201
2017-05-03T08:48:29
2017-05-03T08:48:29
47,324,309
1
0
null
null
null
null
UTF-8
Java
false
false
2,202
java
package com.leeo.web.service; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.leeo.web.entity.Resource; import com.leeo.web.repository.BaseRepository; import com.leeo.web.repository.ResourceRepository; @Service @Transactional public class ResourceService extends BaseService<Resource, Long> { private ResourceRepository resourceRepository; @Autowired @Override public void setRepository(BaseRepository<Resource, Long> resourceRepository) { this.baseRepository = resourceRepository; this.resourceRepository = (ResourceRepository) resourceRepository; } @Transactional(readOnly = true) public String findResourceIdentity(Resource resource) { if (resource == null) { return null; } StringBuilder s = new StringBuilder(resource.getIdentity()); boolean hasResourceIdentity = !StringUtils.isEmpty(resource .getIdentity()); Resource parent = findOne(resource.getParentId()); while (parent != null) { if (!StringUtils.isEmpty(parent.getIdentity())) { s.insert(0, parent.getIdentity() + ":"); hasResourceIdentity = true; } parent = findOne(parent.getParentId()); } //如果用户没有声明 资源标识 且父也没有,那么就为空 if (!hasResourceIdentity) { return ""; } //如果最后一个字符是: 因为不需要,所以删除之 int length = s.length(); if (length > 0 && s.lastIndexOf(":") == length - 1) { s.deleteCharAt(length - 1); } //如果有儿子 最后拼一个* boolean hasChildren = false; for (Resource r : this.resourceRepository.findAll()) { if (resource.getId().equals(r.getParentId())) { hasChildren = true; break; } } if (hasChildren) { s.append(":*"); } return s.toString(); } }
6548de2fbb6c6bd022c189fb5f93f4e601eb448b
0e20b8a8146b876b98fe2f3870a37d98747e6b72
/Login/src/jp/co/aforce/beans/LoginBean.java
3e99946e6aa24d69974ac2daced7a6dda68a98b5
[]
no_license
git-fuji-hub/kensyu
d93a4961a36f78d27668d666198314015834a01a
746d35accc293faa233fb9150eee7e9397028639
refs/heads/master
2020-06-02T10:39:35.190101
2019-06-10T08:43:10
2019-06-10T08:43:10
191,129,861
0
0
null
null
null
null
UTF-8
Java
false
false
725
java
package jp.co.aforce.beans; import java.io.Serializable; @SuppressWarnings("serial") public class LoginBean implements Serializable { private String username; private String password; private String msg; private String emsg; public LoginBean() { } public String getUsername(){ return username; } public void setUsername(String username) { this.username = username; } public String getPassword(){ return password; } public void setPassword(String password) { this.password = password; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg=msg; } public String getEmsg() { return emsg; } public void setEmsg(String emsg) { this.emsg=emsg; } }
a709eb38e4641cc09b6fe61c8b24f0a959e306c8
c365cefc686447a89cce936756595c578bd4a8c9
/MarsRoverSW/src/test/java/com/assignment/MarsRoverSW/service/MarsRoverServiceTest.java
f8df8d69237f877f4adfe1d888dca24e53244cc1
[]
no_license
MuhammadSafwan/MarsRoverProject
3ac92a8517d155f3ed2d4a18d1481779d0333d96
485fedad276f39cb640e447d22e197e97209b7ab
refs/heads/master
2020-09-11T18:00:12.746085
2019-11-16T18:57:12
2019-11-16T18:57:12
222,146,006
0
0
null
null
null
null
UTF-8
Java
false
false
2,950
java
/** * */ package com.assignment.MarsRoverSW.service; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyList; import static org.mockito.Mockito.when; import java.util.Arrays; import java.util.List; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import com.assignment.MarsRoverSW.exception.InvalidInputException; import com.assignment.MarsRoverSW.model.Rover; import com.assignment.MarsRoverSW.service.MarsRoverService; import com.assignment.MarsRoverSW.validator.MarsRoverValidator; /** * @author safwan * */ @RunWith(MockitoJUnitRunner.class) public class MarsRoverServiceTest { @Mock private MarsRoverValidator marsRoverValidator; @InjectMocks private MarsRoverService marsRoverService; @Test public void shallReturnSingleRover() { String gridDimension = "5 5"; List<String> roverStartingCoordinates = Arrays.asList("5 5 S"); List<String> roverInstructions = Arrays.asList("MRM"); when(marsRoverValidator.isValidGridDimension(any())).thenReturn(true); when(marsRoverValidator.isValidRoverPositions(anyList())).thenReturn(true); when(marsRoverValidator.isValidRoverInstructions(anyList())).thenReturn(true); Rover resultRover = new Rover(4, 4, "W"); List<Rover> result = marsRoverService.getRover(gridDimension, roverStartingCoordinates, roverInstructions); assertThat(result.get(0)).isEqualTo(resultRover); } @Test public void shallReturnMultipleRover() { String gridDimension = "5 5"; List<String> roverStartingCoordinates = Arrays.asList("1 2 N", "3 3 E"); List<String> roverInstructions = Arrays.asList("LMLMLMLMM", "MMRMMRMRRM"); when(marsRoverValidator.isValidGridDimension(any())).thenReturn(true); when(marsRoverValidator.isValidRoverPositions(anyList())).thenReturn(true); when(marsRoverValidator.isValidRoverInstructions(anyList())).thenReturn(true); Rover rover1 = new Rover(1, 3, "N"); Rover rover2 = new Rover(5, 1, "E"); List<Rover> result = marsRoverService.getRover(gridDimension, roverStartingCoordinates, roverInstructions); assertThat(result.get(0)).isEqualTo(rover1); assertThat(result.get(1)).isEqualTo(rover2); } @Test(expected = InvalidInputException.class) public void shallThrowInvalidGridDimensionInputException() { when(marsRoverValidator.isValidGridDimension(any())).thenReturn(false); marsRoverService.getRover("5 N", Arrays.asList("1 2 N"), Arrays.asList("LMLM")); } @Test(expected = InvalidInputException.class) public void shallThrowInvalidRoverPositionInputException() { when(marsRoverValidator.isValidGridDimension(any())).thenReturn(true); when(marsRoverValidator.isValidRoverPositions(anyList())).thenReturn(false); marsRoverService.getRover("5 5", Arrays.asList("1 2 S"), Arrays.asList("LMLM")); } }
07551662f3c22e95ba3c74fa14e52f5b3bc7d043
9e3910dcacb475d25f636e007e7d101fd509d4b7
/app/src/main/java/com/example/xingxiaoyu/fdstory/MenuFragment.java
99aa671c98278339727fcf9d72dc5bfd80525685
[]
no_license
XINGXIAOYU/FoodStory
d710e6b4045848e681cfcbb32f675803190d40f9
6c0bd58e19984efac049da71efc5e20f55e9aa5c
refs/heads/master
2021-01-20T03:30:34.879982
2017-05-09T03:39:54
2017-05-09T03:39:54
89,553,287
0
0
null
null
null
null
UTF-8
Java
false
false
4,141
java
package com.example.xingxiaoyu.fdstory; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.ListView; import android.widget.Toast; import com.example.xingxiaoyu.fdstory.entity.MenuItemInfo; import com.example.xingxiaoyu.fdstory.util.ParseInput; import com.example.xingxiaoyu.fdstory.util.WebIP; import org.json.JSONArray; import org.json.JSONObject; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import butterknife.Bind; import butterknife.ButterKnife; /** * Created by xingxiaoyu on 17/5/6. */ public class MenuFragment extends Fragment { @Bind(R.id.recipes) ListView menu; List<MenuItemInfo> menuItemList = new ArrayList<MenuItemInfo>(); private ReadInfoTask task; //adapter private BaseAdapter mBaseAdapter; public static MenuFragment newInstance(int id) { MenuFragment fragment = new MenuFragment(); Bundle args = new Bundle(); args.putInt("article_id", id); fragment.setArguments(args); return fragment; } public MenuFragment() { } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_recipelist, container, false); ButterKnife.bind(this, view); task = new ReadInfoTask(); task.execute((Void) null); return view; } //根据用户的ID获取我的收藏相关信息 public class ReadInfoTask extends AsyncTask<Void, Void, Boolean> { @Override protected Boolean doInBackground(Void... params) { HttpURLConnection conn = null; InputStream is = null; try { String path = "http://" + WebIP.IP + "/FDStoryServer/getMenuInfo"; path = path + "?articleID=" + getArguments().getInt("article_id"); conn = (HttpURLConnection) new URL(path).openConnection(); conn.setConnectTimeout(3000); // 设置超时时间 conn.setReadTimeout(3000); conn.setDoInput(true); conn.setRequestMethod("GET"); // 设置获取信息方式 conn.setRequestProperty("Charset", "UTF-8"); // 设置接收数据编码格式 if (conn.getResponseCode() == 200) { is = conn.getInputStream(); String responseData = ParseInput.parseInfo(is); //转换成json数据处理 JSONArray jsonArray = new JSONArray(responseData); for (int i = 0; i < jsonArray.length(); i++) { //一个循环代表一个对象 JSONObject jsonObject = jsonArray.getJSONObject(i); String image = jsonObject.getString("menuItemImage"); String text = jsonObject.getString("menuItemText"); menuItemList.add(new MenuItemInfo(image, text)); } return true; } } catch (Exception e) { e.printStackTrace(); } finally { // 意外退出时进行连接关闭保护 if (conn != null) { conn.disconnect(); } } return false; } @Override protected void onPostExecute(final Boolean success) { task = null; if (success) { initAdapter(); } } } private void initAdapter() { mBaseAdapter = new MenuAdapter(getActivity(), menuItemList); menu.setAdapter(mBaseAdapter); } }
5633030c79f7d394ab5cdd00fb0a7da81a5f0644
0ffe05470dcb2393233998df130168b6c2d3171e
/sell_service/src/main/java/cn/shendu/service/PermissionService.java
4729467dfce7feffccea8d6c2b75c8dfafa532d7
[]
no_license
LMengu/sell
5c91ace289e55aad9febf0298986d83813f96319
56d3ea75954fe8ea494fdd1b2f11aa83dafc31ba
refs/heads/master
2022-12-22T07:16:08.334240
2019-11-15T09:31:01
2019-11-15T09:31:01
218,760,254
0
0
null
2022-12-15T23:44:47
2019-10-31T12:24:54
JavaScript
UTF-8
Java
false
false
339
java
package cn.shendu.service; import cn.shendu.domain.Permission; import java.util.List; public interface PermissionService { List<Permission> findAll()throws Exception; void save(Permission permission) throws Exception; Permission findById(Integer id) throws Exception; void deleteById(Integer id) throws Exception; }
60eab3826a720983294da0890540d8ad73ba5d90
e9d420540e66248b1b1bf4a605cace7033dd75a4
/src/main/java/kumbhar/akshay/joke/jokeapp/JokeappApplication.java
c0e80a029b518143f693a8bf052999f84c114739
[]
no_license
KumbharAkshay/jokesapp
ab491e8d32a626fc8ffb577e5eca3934fd9e0374
26f95446a6eb8638f54202a721863ed2b5280303
refs/heads/master
2020-05-18T18:33:55.685017
2019-05-02T15:01:03
2019-05-02T15:01:03
184,589,646
0
0
null
null
null
null
UTF-8
Java
false
false
323
java
package kumbhar.akshay.joke.jokeapp; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class JokeappApplication { public static void main(String[] args) { SpringApplication.run(JokeappApplication.class, args); } }
1fd36cf6e6465063c80f4b52317ae08b1bd10103
8438f34124fa65d4deb5b6d35ad1eb50cfcd383f
/JavaDayTwo/src/com/example/exceptions/ExceptionDriver.java
240fcbbbfcd8f8b17ea2eb0c28126f2e5a725486
[]
no_license
210927-UTA-SH-Java-React-EM/EthansNotesAndExamples
aa68c625889579cb89954ef81761d50039f4d926
4df4e4dae6e1e13756b256950527a0d0dc36ba77
refs/heads/main
2023-08-30T18:40:54.256970
2021-11-12T17:23:06
2021-11-12T17:23:06
400,269,065
0
0
null
2021-11-12T18:02:12
2021-08-26T18:31:12
Java
UTF-8
Java
false
false
1,333
java
package com.example.exceptions; import java.io.FileNotFoundException; import java.io.IOException; public class ExceptionDriver { public static void main(String args[]) { /* try { throwManyExceptions(4); } catch (FileNotFoundException e) { System.out.println("FileNotFound was caught"); } catch(IOException e) { System.out.println("IOException was caught"); } catch(Exception e) { System.out.println("Some other exception was caught"); } finally { System.out.println("This block of code will run no matter what"); } */ Bicycle bike = new Bicycle(); System.out.println("gear: " + bike.gear + ", speed: " + bike.speed); bike.speedUp(24); System.out.println("gear: " + bike.gear + ", speed: " + bike.speed); bike.speedUp(2); System.out.println("gear: " + bike.gear + ", speed: " + bike.speed); try { bike.slowDown(26); } catch (NegativeSpeedException e) { bike.speed = 0; bike.gear = 1; e.printStackTrace(); } System.out.println("gear: " + bike.gear + ", speed: " + bike.speed); } public static void throwManyExceptions(int i) throws Exception { switch(i) { case 1: throw new IOException(); case 2: throw new ClassNotFoundException(); case 3: throw new FileNotFoundException(); default: throw new Exception(); } } }
060874b872b55106a67c5fbae7c2961260e142a3
866c2e75f8acea74ef185e2ba83b5e9c0bf158a8
/yama-repository/yama-repository-jpa/src/main/java/org/meruvian/yama/repository/jpa/commons/JpaFileInfo.java
f81780e89e1475eb4cb8842722d15c01cf378626
[]
no_license
dianw/yama
dee6f78083176109456d1680e4fb8cc2aa1aab48
603de098a3e0636cc43967f9339de068f55aa012
refs/heads/master
2020-12-28T19:57:26.124793
2014-07-08T07:28:26
2014-07-08T07:28:26
23,788,408
0
0
null
null
null
null
UTF-8
Java
false
false
2,495
java
/** * Copyright 2014 Meruvian * * 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 org.meruvian.yama.repository.jpa.commons; import java.io.InputStream; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.Table; import javax.persistence.Transient; import org.meruvian.yama.repository.commons.FileInfo; import org.meruvian.yama.repository.jpa.DefaultJpaPersistence; import org.meruvian.yama.repository.jpa.JpaLogInformation; /** * @author Dian Aditya * */ @Entity @Table(name = "yama_file_info") public class JpaFileInfo extends DefaultJpaPersistence implements FileInfo { private String originalName; private String contentType; private String path; private long size = 0; private InputStream dataBlob; public JpaFileInfo() {} public JpaFileInfo(FileInfo info) { this.id = info.getId(); this.logInformation = new JpaLogInformation(info.getLogInformation()); this.originalName = info.getOriginalName(); this.contentType = info.getContentType(); this.path = info.getPath(); this.size = info.getSize(); this.dataBlob = info.getDataBlob(); } @Override @Column(name = "content_type") public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } @Override @Transient public InputStream getDataBlob() { return dataBlob; } public void setDataBlob(InputStream dataBlob) { this.dataBlob = dataBlob; } @Override @Column(name = "original_name", nullable = false) public String getOriginalName() { return originalName; } public void setOriginalName(String originalName) { this.originalName = originalName; } @Override @Column(nullable = false) public String getPath() { return path; } public void setPath(String path) { this.path = path; } @Override @Column(nullable = false) public long getSize() { return size; } public void setSize(long size) { this.size = size; } }
b8057ee0c0cde6896f7bbdb851842b17360008bb
4d601dd0c3065cd8c906dd8e4e5394da4105aa39
/core/src/main/java/hashengineering/difficulty/FrankoGravityWell/fgw.java
4b8cc0e315d03f9e22ec6db0b9254ae46070a83b
[ "Apache-2.0" ]
permissive
HashEngineering/frankoj
58e229053f0c590d2400de422be8a6f2ae3c1f77
2162442518ed6c3efeb02ba0a48d50b060bb1b41
refs/heads/master
2021-01-13T02:02:35.014976
2015-01-28T05:56:56
2015-01-28T05:56:56
14,674,081
0
0
null
null
null
null
UTF-8
Java
false
false
1,909
java
package hashengineering.difficulty.FrankoGravityWell; import java.lang.UnsatisfiedLinkError; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Created by HashEngineering on 3/7/14. * * Updated on 4/15/2014 for the Franko Gravity Well (includes a fix for the KGW time warp exploit) * * Native implimentation requires three methods to be called * - init - before the loop * - loop2 - for each iteration of the loop * - close - at the end of the loop and it returns the calculated difficulty */ public class fgw { private static final Logger log = LoggerFactory.getLogger(fgw.class); private static boolean native_library_loaded = false; static { try { System.loadLibrary("fgw"); native_library_loaded = true; } catch(NoSuchMethodError e) { //catches an error on 4.4.2; we don't know why this happens yet. log.info(e.getMessage()); } catch(UnsatisfiedLinkError e) { //no need to do anything here, the native_library_loaded value will be false log.info(e.getMessage()); } catch(Exception e) { } } public static boolean isNativeLibraryLoaded() { return native_library_loaded; } public static native byte[] KimotoGravityWell_close(); public static native int KimotoGravityWell_init(long _TargetBlocksSpacingSeconds, long _PastBlocksMin, long _PastBlocksMax, double deviationDenominator, long _LatestBlockTime); //public static native int KimotoGravityWell_loop(int i, byte[] BlockReadingDiff, int BlockReadingHeight, long BlockReadingTime, long BlockLastSolvedTime); public static native int KimotoGravityWell_loop2(int i, long BlockReadingDiff, int BlockReadingHeight, long BlockReadingTime, long BlockLastSolvedTime); //todo::Refactor the entire algorithm here (native and hybrid) }
3ddac6462fb13bf6ef69fa5cfa2db41cb188f5dc
6db5d80dd9221803aa2e444dd28d5031e5ec3232
/src/in/sahildave/gazetti/news_activities/WebsiteListActivity.java
91a7d74e3034a116d13ca31288693281dffe8b82
[ "MIT" ]
permissive
singhajay7/Gazetti_Newspaper_Reader
edf8fc9846c93d2be24d7ff566d48c534f215e58
900ed2d6cee0a5268f0ecd08944410924dfe34e8
refs/heads/master
2021-01-17T08:48:09.308294
2014-12-04T12:20:26
2014-12-04T12:20:26
null
0
0
null
null
null
null
UTF-8
Java
false
false
13,776
java
package in.sahildave.gazetti.news_activities; import android.annotation.SuppressLint; import android.content.Intent; import android.content.res.Configuration; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.support.v4.app.ActionBarDrawerToggle; import android.support.v4.view.GravityCompat; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBarActivity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import com.crashlytics.android.Crashlytics; import in.sahildave.gazetti.R; import in.sahildave.gazetti.news_activities.WebsiteDetailFragment.LoadArticleCallback; import in.sahildave.gazetti.news_activities.WebsiteListFragment.ItemSelectedCallback; import in.sahildave.gazetti.news_activities.adapter.NavDrawerListAdapter; import in.sahildave.gazetti.news_activities.adapter.NewsAdapter; import in.sahildave.gazetti.preference.SettingsActivity; @SuppressLint("NewApi") public class WebsiteListActivity extends ActionBarActivity implements ItemSelectedCallback, LoadArticleCallback { private static final String TAG = "MasterDetail"; private static final String TAG_ASYNC = "ASYNC"; public boolean mTwoPane; // For NavDrawer private DrawerLayout mDrawerLayout; private ListView mDrawerList; private ActionBarDrawerToggle mDrawerToggle; private CharSequence mDrawerTitle; private CharSequence mTitle; private LinearLayout mLeftDrawer; private String[] mDrawerItems; private int[] mActionBarColors; private int currentColor; WebsiteListFragment mlistFragment; // Intent variables from Home Screen String npId; String catId; String npName; String catName; private ArticleLoadingCallback articleLoadingCallback; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //Log.d(TAG, "Activity onCreate"); setContentView(R.layout.activity_website_list); mActionBarColors = getResources().getIntArray(R.array.action_bar_colors); currentColor = getResources().getColor(R.color.actionbar_default_color); Bundle extras = getIntent().getExtras(); try { if (extras != null) { //Log.d(TAG, "Activity retaining extras"); npId = extras.getString("npId"); catId = extras.getString("catId"); npName = extras.getString("npName"); catName = extras.getString("catName"); currentColor = mActionBarColors[Integer.parseInt(catId) - 1]; } } catch (NumberFormatException e) { Crashlytics.logException(e); } if (savedInstanceState != null) { //Log.d(TAG, "Activity retaining savedInstanceState"); npName = savedInstanceState.getString("npName"); catId = savedInstanceState.getString("catId"); currentColor = savedInstanceState.getInt("color"); catName = savedInstanceState.getString("catName"); } // mActionBarColors = // getResources().getIntArray(R.array.action_bar_colors); setTitle(npName + " - " + catName); setColor(currentColor); if (findViewById(R.id.website_detail_container) != null) { // Log.d(TAG, "Activity twoPane true"); mTwoPane = true; } mlistFragment = (WebsiteListFragment) getSupportFragmentManager().findFragmentByTag("listContent"); if (mlistFragment == null) { mlistFragment = new WebsiteListFragment(); Bundle layoutBundle = new Bundle(); layoutBundle.putBoolean("mTwoPane", mTwoPane); layoutBundle.putString("npId", npId); layoutBundle.putString("npName", npName); layoutBundle.putString("catId", catId); layoutBundle.putInt("color", currentColor); mlistFragment.setArguments(layoutBundle); getSupportFragmentManager().beginTransaction() .add(R.id.website_list_container, mlistFragment, "listContent").commit(); } articleLoadingCallback = new ArticleLoadingCallback(this); // Make Navigation Drawer makeNavDrawer(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); //Log.d(TAG, "Activity saving savedInstanceState"); outState.putString("npName", npName); outState.putString("catId", catId); outState.putInt("color", currentColor); outState.putString("catName", catName); } @Override public void onItemSelected(String headlineText, NewsAdapter newsAdapter) { try { if(headlineText!=null){ if (mTwoPane) { Bundle arguments = new Bundle(); arguments.putString("npName", npName); arguments.putString("catName", catName); arguments.putInt("actionBarColor", currentColor); arguments.putString(WebsiteDetailFragment.HEADLINE_CLICKED, headlineText); WebsiteDetailFragment detailFragment = new WebsiteDetailFragment(); detailFragment.setArguments(arguments); getSupportFragmentManager().beginTransaction() .replace(R.id.website_detail_container, detailFragment, "detail").commit(); } else { Intent detailIntent = new Intent(this, WebsiteDetailActivity.class); detailIntent.putExtra("npName", npName); detailIntent.putExtra("catName", catName); detailIntent.putExtra(WebsiteDetailFragment.HEADLINE_CLICKED, headlineText); detailIntent.putExtra("ActionBarColor", currentColor); detailIntent.putExtra("ActionBarTitle", npName + " - " + catName); startActivity(detailIntent); } } else { Crashlytics.log("Headline clicked is null ? " + (null == headlineText)); } } catch (Exception e) { Crashlytics.logException(e); } } /****************************/ /***** CALLBACK METHODS *****/ /** * ************************ */ @Override public void onPreExecute(View rootView) { articleLoadingCallback.onPreExecute(rootView); } @Override public void setHeaderStub(View headerStub) { articleLoadingCallback.setHeaderStub(headerStub); } @Override public void onPostExecute(String[] result, String mArticlePubDate) { articleLoadingCallback.onPostExecute(result, mArticlePubDate); } @Override public void articleNotFound(String mArticleUrl) { // WebViewFragment webViewFragment = (WebViewFragment) getSupportFragmentManager().findFragmentByTag("webViewFragment"); // if(webViewFragment==null){ articleLoadingCallback.articleNotFound(mArticleUrl); // } } /** * ************************************** */ @Override public boolean onOptionsItemSelected(MenuItem item) { // The action bar home/up action should open or closeUtilObject the drawer. // ActionBarDrawerToggle will take care of this. return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item); } @Override public boolean onPrepareOptionsMenu(Menu menu) { // If the nav drawer is open, hide action items related to the content // view return super.onPrepareOptionsMenu(menu); } /** * When using the ActionBarDrawerToggle, you must call it during * onPostCreate() and onConfigurationChanged()... */ @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. mDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); // Pass any configuration change to the drawer toggls mDrawerToggle.onConfigurationChanged(newConfig); } private void makeNavDrawer() { /* * Making NavBar - START */ mTitle = mDrawerTitle = getTitle(); mDrawerLayout = (DrawerLayout) findViewById(R.id.nav_drawer_layout); mLeftDrawer = (LinearLayout) findViewById(R.id.left_drawer); mDrawerList = (ListView) findViewById(R.id.nav_list_slidermenu); mDrawerItems = getResources().getStringArray(R.array.nav_drawer_items); // set a custom shadow that overlays the main content when the drawer // opens mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START); NavDrawerListAdapter navAdapter = new NavDrawerListAdapter(this, mDrawerItems); mDrawerList.setAdapter(navAdapter); // New NavBar _ OVER // enable ActionBar app icon to behave as action to toggle nav drawer getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setHomeButtonEnabled(true); // ActionBarDrawerToggle ties together the the proper interactions // between the sliding drawer and the action bar app icon mDrawerToggle = new ActionBarDrawerToggle(this, /* host Activity */ mDrawerLayout, /* DrawerLayout object */ R.drawable.ic_navigation_drawer, /* * nav drawer image to replace 'Up' * caret */ R.string.drawer_open, /* "open drawer" description for accessibility */ R.string.drawer_close /* "closeUtilObject drawer" description for accessibility */ ) { public void onDrawerClosed(View view) { getSupportActionBar().setTitle(mTitle); invalidateOptionsMenu(); // creates call to // onPrepareOptionsMenu() } public void onDrawerOpened(View drawerView) { getSupportActionBar().setTitle(mDrawerTitle); invalidateOptionsMenu(); // creates call to // onPrepareOptionsMenu() } }; /* * Making NavBar - END */ // Nav Drawer Home Button listener TextView navBarHeaderView = (TextView) findViewById(R.id.nav_bar_header); navBarHeaderView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { onBackPressed(); } }); // Nav List listener mDrawerList.setOnItemClickListener(new ListView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //Log.d(TAG, "Drawer onItemClick - " + position + " - " + mDrawerItems[position]); mlistFragment = new WebsiteListFragment(); Bundle layoutBundle = new Bundle(); catId = String.valueOf(position + 1); catName = mDrawerItems[position]; layoutBundle.putBoolean("mTwoPane", mTwoPane); layoutBundle.putString("npId", npId); layoutBundle.putString("catId", catId); layoutBundle.putInt("color", mActionBarColors[position]); mlistFragment.setArguments(layoutBundle); getSupportFragmentManager().beginTransaction() .replace(R.id.website_list_container, mlistFragment, "listContent").commit(); // update selected item and title, then closeUtilObject the drawer mDrawerList.setItemChecked(position, true); mDrawerList.setSelection(position); setTitle(npName + " - " + mDrawerItems[position]); setColor(mActionBarColors[position]); //Log.d(TAG, position + " - " + mActionBarColors[position]); mDrawerLayout.closeDrawer(mLeftDrawer); } }); // Nav List Footer options listeners LinearLayout navBarSettingsView = (LinearLayout) findViewById(R.id.settings); // LinearLayout navBarSendFeedbackView = (LinearLayout) findViewById(R.id.send_feedback); navBarSettingsView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent settingIntent = new Intent(WebsiteListActivity.this, SettingsActivity.class); settingIntent.putExtra("ActionBarColor", currentColor); startActivity(settingIntent); mDrawerLayout.closeDrawer(mLeftDrawer); } }); // navBarSendFeedbackView.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // mDrawerLayout.closeDrawer(mLeftDrawer); // } // }); } @Override public void setTitle(CharSequence title) { mTitle = title; getSupportActionBar().setTitle(mTitle); } public void setColor(int colorId) { getSupportActionBar().setDisplayShowTitleEnabled(false); getSupportActionBar().setBackgroundDrawable(new ColorDrawable(colorId)); getSupportActionBar().setDisplayShowTitleEnabled(true); currentColor = colorId; } }
7b7302e814f0afa9d4ba9fd60fd80026a9f48eef
0316efccc0d745d23592f297deacbae7db487d38
/src/main/java/com/javatpoint/batch/reader/SlaveReader.java
642c5ee80c64da915dd19c399e998aeaca1d3b24
[]
no_license
V01d3m0rt/spring-boot-hello-world-example
e089c58b18731c87c3437f2265daf1281e91da5a
74f6524586ca25bf5fd66b6c4518adb22fb92311
refs/heads/master
2022-12-05T06:29:29.823615
2020-08-25T18:31:04
2020-08-25T18:31:04
290,143,825
0
0
null
null
null
null
UTF-8
Java
false
false
530
java
package com.javatpoint.batch.reader; import java.util.Queue; import org.springframework.batch.core.StepExecution; import org.springframework.batch.core.annotation.BeforeStep; import org.springframework.batch.item.ItemReader; import com.michaelcgood.model.ComputerSystem; public class SlaveReader implements ItemReader<ComputerSystem> { private Queue<ComputerSystem> queue; public SlaveReader(Queue<ComputerSystem> queue) { this.queue = queue; } @Override public ComputerSystem read() { return queue.poll(); } }
441fc23867fea2a8e9474838ba2ed1c58bf635d1
52d41f19c7c94127edf4e95bc2376a8e06c711b1
/action/src/test/java/io/cettia/asity/action/SimpleActionsTest.java
953b50361cf19e370875c22480c4cb0b8a0b3fb2
[ "Apache-2.0" ]
permissive
cettia/asity
438f43463ccb4c4f02dc4a752485986512c103fa
53fe447aa870d4b167dbf55d0431853680bffa21
refs/heads/master
2023-03-08T22:07:14.276771
2021-04-18T15:57:27
2021-04-18T15:57:27
32,444,134
30
0
Apache-2.0
2020-10-13T04:46:09
2015-03-18T07:26:13
Java
UTF-8
Java
false
false
1,003
java
/* * Copyright 2015 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 * * 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 io.cettia.asity.action; import io.cettia.asity.action.Actions.Options; /** * @author Donghwan Kim */ public class SimpleActionsTest extends ActionsTestBase { @Override protected <T> Actions<T> createActions() { return new SimpleActions<>(); } @Override protected <T> Actions<T> createActions(Options options) { return new SimpleActions<>(options); } }
9a2e3c23665e60d7defaca06990d0b1c0b4a7610
edc6e80a29a4bdbe04f4d9d509c1f79fd0215b38
/List.java
11c9cdb0f7226c4f4e24aff42552fc72d31f6b09
[]
no_license
Aadit017/code_sharing
c117841e1ce34366e84c8e2af7442131e2e1c02a
dea62f2f1a412acfe060c155dca797e8e22a3ed0
refs/heads/master
2023-03-31T00:27:35.036431
2021-03-24T08:24:15
2021-03-24T08:24:15
298,953,277
1
0
null
2020-09-27T04:32:28
2020-09-27T04:32:28
null
UTF-8
Java
false
false
572
java
import java.util.*; class List { public static void main (String args[]) { int n = 5; ArrayList arrli = new ArrayList (n); for (int i=1; i<=n; i++) arrli.add(i); // Printing elements System.out.println(arrli); // Remove element at index 3 arrli.remove(3); // Displaying ArrayList after deletion System.out.println(arrli); // Printing elements one by one for (int i=0; i<arrli.size(); i++) System.out.print(arrli.get(i)+" "); } }
5a70c446ef2be4c1611ac6531b6dcee53ff7a498
3b85db026f3aa749cff2a7ccf8cca2b62246140a
/src/rewriter/com/newrelic/com/google/common/util/concurrent/TimeLimiter.java
2dfe49346ab4253a73791d4d9d2a6e1841d8da39
[]
no_license
chenhq/newrelic_ref
9255cf81572d89309a17989c09e42b0d00db126d
792d7c84dd231fec170894b233996c744f8c318d
refs/heads/master
2021-01-10T19:01:40.257458
2014-12-26T08:39:09
2014-12-26T08:39:09
null
0
0
null
null
null
null
UTF-8
Java
false
false
703
java
package com.newrelic.com.google.common.util.concurrent; import com.newrelic.com.google.common.annotations.Beta; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; @Beta public abstract interface TimeLimiter { public abstract <T> T newProxy(T paramT, Class<T> paramClass, long paramLong, TimeUnit paramTimeUnit); public abstract <T> T callWithTimeout(Callable<T> paramCallable, long paramLong, TimeUnit paramTimeUnit, boolean paramBoolean) throws Exception; } /* Location: /home/think/Downloads/newrelic-android-4.120.0/lib/class.rewriter.jar * Qualified Name: com.newrelic.com.google.common.util.concurrent.TimeLimiter * JD-Core Version: 0.6.2 */
4a91def0212ddd3bab18af2748604e97acdf57f7
6c0b75c1a3bf5288cae2782c23e821ed238499ec
/src/main/java/io/brainkaster/paperless/repositories/FournisseurRepository.java
56fa1d0c96dbf29a8f702aae8ccbf205399cdcb5
[]
no_license
Emowpy/paperless-refs
305349e3f205b64bdf77e4666881c13e3926d1c0
c6f998585c79dfa6854d6fa1e86c70dbc209ae55
refs/heads/master
2020-12-25T07:51:50.949637
2016-06-10T14:48:37
2016-06-10T14:48:37
60,854,169
0
0
null
null
null
null
UTF-8
Java
false
false
322
java
package io.brainkaster.paperless.repositories; import io.brainkaster.paperless.referentiel.Fournisseur; import org.springframework.data.repository.PagingAndSortingRepository; /** * Created by melbakkali on 21/04/2016. */ public interface FournisseurRepository extends PagingAndSortingRepository<Fournisseur, Long> { }
4725d31fd0507a2099e63c1414e79f26d4476872
97c3a9e7a698e5693aaa7dd9b0a39812f355bb27
/moxidriver/InternetReceiver.java
61f71c35ee2611c03885de4cd2a80fcc0cae7dfd
[]
no_license
dbrax/MOXI
5021affe79c81a24a3c00e034d7400208509c9db
4f948c2dbaf0fa262946e965ff10c5679d1ff2b4
refs/heads/master
2021-01-21T21:54:29.066386
2016-05-17T06:26:32
2016-05-17T06:26:32
53,577,515
0
0
null
null
null
null
UTF-8
Java
false
false
1,640
java
package tz.co.delis.www.moxidriver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.widget.Toast; /** * Created by Kapten on 3/31/2016. */ public class InternetReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { ConnectivityManager conn = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo networkInfo = conn.getActiveNetworkInfo(); // checks to see if the device has a Wi-Fi connection. if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) { // If device has its Wi-Fi connection // Toast.makeText(context, "Wifi Connected", Toast.LENGTH_SHORT).show(); // If the setting is ANY network and there is a network connection // (which by process of elimination would be mobile), } else if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_MOBILE) { // Toast.makeText(context, "Mobile Connected", Toast.LENGTH_SHORT).show(); // Otherwise, the app can't download content--either because there is no network // connection (mobile or Wi-Fi), or because the pref setting is WIFI, and there // is no Wi-Fi connection. // Sets refreshDisplay to false. } else { Toast.makeText(context, "LOST INTERNET CONNECTION", Toast.LENGTH_SHORT).show(); } } }
d74bae54ff1f0318bdfb2c56e2d752cdeb93dc7b
9366f62a367a57adbb876617d1f6a8d01ad337e9
/JavaBase/src/main/java/java021_arithmetic/RadixSort.java
e29a01c5b7afc965193c9856a30d393ca2b6bad3
[]
no_license
BrightAssistor/javaSe
944fe1a397c2280e94851582831ac76060cfacaf
6d3ef01d5bd9c83d066cacef0306f8ba866a0759
refs/heads/master
2022-10-24T17:30:32.969721
2020-04-30T07:53:48
2020-04-30T07:53:48
159,803,997
0
0
null
2022-10-05T19:16:34
2018-11-30T10:00:19
Java
UTF-8
Java
false
false
988
java
package java021_arithmetic; public class RadixSort { public static void main(String[] args) { int[] data = { 73, 22, 93, 43, 55, 14, 28, 65, 39, 81, 33, 100 }; RadixSort.sort(data, 3); for (int i = 0; i < data.length; i++) { System.out.print(data[i] + ""); } } public static void sort(int[] number, int d) { // d表示最大的数有多少位 int k = 0; int n = 1; int m = 1; // 控制键值排序依据在哪一位 int[][] temp = new int[10][number.length]; // 数组的第一维表示可能的余数0-9 int[] order = new int[10]; // 数组orderp[i]用来表示该位是i的数的个数 while (m <= d) { for (int i = 0; i < number.length; i++) { int lsd = ((number[i] / n) % 10); temp[lsd][order[lsd]] = number[i]; order[lsd]++; } for (int i = 0; i < 10; i++) { if (order[i] != 0) for (int j = 0; j < order[i]; j++) { number[k] = temp[i][j]; k++; } order[i] = 0; } n *= 10; k = 0; m++; } } }
9eb0d1b302288c2a98059c7270f98261727ad97b
bd5fedce0fe8c58dd3cacad7d4831134bd4cbe0a
/src/main/java/com/myhomepage/homepage/dao/UserDaoImpl.java
41a9fe40e6460efbc6fafae3a765ebbd2482cd93
[]
no_license
abelshaw85/movie-catalogue
97a576ff99090fa8a1ecf16278f3d885cfe0aca0
c98f0737a6bebeeaa506ad2cf56de39ad88e465a
refs/heads/master
2023-03-04T08:06:36.586702
2021-02-19T11:10:38
2021-02-19T11:10:38
339,731,763
0
0
null
null
null
null
UTF-8
Java
false
false
1,024
java
package com.myhomepage.homepage.dao; import javax.persistence.EntityManager; import org.hibernate.Session; import org.hibernate.query.Query; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import com.myhomepage.homepage.entity.User; @Repository public class UserDaoImpl implements UserDao { @Autowired private EntityManager entityManager; @Override public User findByUserName(String userName) { // Current Hibernate session Session currentSession = entityManager.unwrap(Session.class); // Retrieve user from database Query<User> query = currentSession.createQuery("from User where userName=:userName", User.class); query.setParameter("userName", userName); User user = null; try { user = query.getSingleResult(); } catch (Exception e) { user = null; } return user; } @Override public void save(User user) { Session currentSession = entityManager.unwrap(Session.class); currentSession.saveOrUpdate(user); } }
d778a96dbe5a613d1a1d799343c3380c63aa8eeb
96ca02a85d3702729076cb59ff15d069dfa8232b
/advert/src/com/dvnchina/advertDelivery/bean/config/PlatformConfigBean.java
0307dc521706f24ec37994b586fd5df348da05ad
[]
no_license
Hurson/mysql
4a1600d9f580ac086ff9472095ed6fa58fb11830
3db53442376485a310c76ad09d6cf71143f38274
refs/heads/master
2021-01-10T17:55:50.003989
2016-03-11T11:36:15
2016-03-11T11:36:15
54,877,514
0
1
null
null
null
null
UTF-8
Java
false
false
251
java
package com.dvnchina.advertDelivery.bean.config; /** * 平台地址配置实体Bean * * @author Administrator * */ public class PlatformConfigBean extends CommonConfigBean { private static final long serialVersionUID = 1L; }
[ "zhengguojin@d881c268-5c81-4d69-b6ac-ed4e9099e0f2" ]
zhengguojin@d881c268-5c81-4d69-b6ac-ed4e9099e0f2
162f9719d0f13dede88721354c1d097c65f3e1b7
74aecd052e899063f34b3275b1a7d35088b3b95d
/demo/src/main/java/com/example/demo/MyNameController.java
36817b06c2fc3a889e70bb3e22f1c747aab075c6
[]
no_license
Isabelle-1/ExamTwenty
4f18825980c90dcc6838788caaf1886e2f7cad93
2ea20cd6748ae0f2bd7e26fa754afee2a5527313
refs/heads/main
2023-06-20T04:33:04.004341
2021-07-23T02:31:00
2021-07-23T02:31:00
388,653,944
0
0
null
null
null
null
UTF-8
Java
false
false
589
java
package com.example.demo; import com.example.demo.MyName; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class MyNameController { @GetMapping("/myName") public String myName(@RequestParam(name="name", required=false, defaultValue="Isabelle") String name, Model model) { model.addAttribute("name", name); return "Isabelle"; } }
350ceea35264098df5b42cc2b429aa415017d12d
61e6d88d82b693b130206a20972b43985e5adbaa
/Oops/service/payment/src/main/java/com/example/server/MobilePay.java
b593b25d9054907be8367d71e7232ee96088e3b8
[]
no_license
xiguaapp/Oops-beta
0b9d95e02e4f5cc250a18bd62ad54b881cac8ddc
0230a1c3c4d09c6bd2c6ac8883078afb9ee36cc2
refs/heads/main
2023-02-24T04:10:05.678836
2021-01-28T10:13:07
2021-01-28T10:13:07
332,764,054
1
0
null
null
null
null
UTF-8
Java
false
false
64
java
//package com.example.server; // //public class MobilePay { //}
c632a23b18d4770114f14b9fdf2df144b3f5ee85
89952a03ccf5163b749b72d05c1305cffb3590d4
/simple-facebook/src/main/java/com/sromku/simple/fb/Permission.java
1d5b033a5dd0181080206aa182c5adc392016e71
[ "Apache-2.0" ]
permissive
gritsoftwares/Facebook-Frost
64dd2d5c2b5da3ce827597079fb4af345dfe9fac
5d5ac83b7e39cd9d76a6a6e688bbd969231efc9f
refs/heads/master
2020-12-02T06:29:40.863183
2016-06-26T02:09:21
2016-06-26T02:09:21
null
0
0
null
null
null
null
UTF-8
Java
false
false
14,993
java
package com.sromku.simple.fb; import com.sromku.simple.fb.entities.Profile; import java.util.ArrayList; import java.util.Collection; import java.util.List; /** * All facebook permissions. * * @author sromku * @version Graph API v2.4 */ public enum Permission { /** * This permission not longer in use in latest graph versions. * Please us Permission#USER_ABOUT_ME instead. * * Provides access to a subset of items that are part of a person's public * profile. These {@link Profile} fields can be retrieved by using this * permission:<br> * <ul> * <li>{@link Profile.Properties#ID ID}</li> * <li>{@link Profile.Properties#NAME NAME}</li> * <li>{@link Profile.Properties#FIRST_NAME FIRST_NAME}</li> * <li>{@link Profile.Properties#LAST_NAME LAST_NAME}</li> * <li>{@link Profile.Properties#LINK LINK}</li> * <li>{@link Profile.Properties#GENDER GENDER}</li> * <li>{@link Profile.Properties#LOCALE LOCALE}</li> * <li>{@link Profile.Properties#AGE_RANGE AGE_RANGE}</li> * </ul> * */ @Deprecated PUBLIC_PROFILE("public_profile", Type.READ), /** * Provides access to {@link Profile.Properties#BIO BIO} property of the * {@link Profile} */ USER_ABOUT_ME("user_about_me", Type.READ), /** * Provides access to all common books actions published by any app the * person has used. This includes books they've read, want to read, rated or * quoted. */ USER_ACTIONS_BOOKS("user_actions.books", Type.READ), /** * Provides access to all common Open Graph fitness actions published by any * app the person has used. This includes runs, walks and bikes actions. */ USER_ACTIONS_FITNESS("user_actions.fitness", Type.READ), /** * Provides access to all common Open Graph music actions published by any * app the person has used. This includes songs they've listened to, and * playlists they've created. */ USER_ACTIONS_MUSIC("user_actions.music", Type.READ), /** * Provides access to all common Open Graph news actions published by any * app the person has used which publishes these actions. This includes news * articles they've read or news articles they've published. */ USER_ACTIONS_NEWS("user_actions.news", Type.READ), /** * Provides access to all common Open Graph video actions published by any * app the person has used which publishes these actions. This includes * videos they've watched, videos they've rated and videos they want to * watch. */ USER_ACTIONS_VIDEO("user_actions.video", Type.READ), /** * This permission not longer in use in latest graph versions. * * Provides access to a person's list of activities as listed on their * Profile. This is a subset of the pages they have liked, where those pages * represent particular interests. This information is accessed through the * activities connection on the user node. */ @Deprecated USER_ACTIVITIES("user_activities", Type.READ), /** * Access the date and month of a person's birthday. This may or may not * include the person's year of birth, dependent upon their privacy settings * and the access token being used to query this field. */ USER_BIRTHDAY("user_birthday", Type.READ), /** * Provides access to {@link Profile.Properties#EDUCATION EDUCATION} * property of the {@link Profile} */ USER_EDUCATION_HISTORY("user_education_history", Type.READ), /** * Provides read-only access to the Events a person is hosting or has RSVP'd * to. */ USER_EVENTS("user_events", Type.READ), /** * Provides access the list of friends that also use your app. In order for * a person to show up in one person's friend list, <b>both people</b> must * have decided to share their list of friends with your app and not * disabled that permission during login. */ USER_FRIENDS("user_friends", Type.READ), /** * Provides access to read a person's game activity (scores, achievements) * in any game the person has played. */ USER_GAMES_ACTIVITY("user_games_activity", Type.READ), /** * This permission not longer in use in latest graph versions. * Please us Permission#USER_MANAGED_GROUPS instead. * * Enables your app to read the Groups a person is a member of through the * groups edge on the User object. This permission does not allow you to * create groups on behalf of a person. It is not possible to create groups * via the Graph API */ @Deprecated USER_GROUPS("user_groups", Type.READ), /** * Enables your app to read the Groups a person is a member of through the * groups edge on the User object. This permission does not allow you to * create groups on behalf of a person. It is not possible to create groups * via the Graph API */ USER_MANAGED_GROUPS("user_managed_groups", Type.READ), /** * Provides access to a person's hometown location through the hometown * field on the User object. This is set by the user on the Profile. */ USER_HOMETOWN("user_hometown", Type.READ), /** * This permission not longer in use in latest graph versions. * * Provides access to the list of interests in a person's Profile. This is a * subset of the pages they have liked which represent particular interests. */ @Deprecated USER_INTERESTS("user_interests", Type.READ), /** * Provides access to the list of all Facebook Pages and Open Graph objects * that a person has liked. This list is available through the likes edge on * the User object. */ USER_LIKES("user_likes", Type.READ), /** * Provides access to a person's current city through the location field on * the User object. The current city is set by a person on their Profile. */ USER_LOCATION("user_location", Type.READ), /** * Provides access to the photos a person has uploaded or been tagged in. * This is available through the photos edge on the User object. */ USER_PHOTOS("user_photos", Type.READ), /** * Provides access to a person's relationship status, significant other and * family members as fields on the User object. */ USER_RELATIONSHIPS("user_relationships", Type.READ), /** * Provides access to a person's relationship interests as the interested_in * field on the User object. */ USER_RELATIONSHIP_DETAILS("user_relationship_details", Type.READ), /** * Provides access to a person's religious and political affiliations. */ USER_RELIGION_POLITICS("user_religion_politics", Type.READ), /** * Provides access to a person's statuses. These are posts on Facebook which * don't include links, videos or photos. */ USER_STATUS("user_status", Type.READ), /** * Provides access to the Places a person has been tagged at in photos, * videos, statuses and links. */ USER_TAGGED_PLACES("user_tagged_places", Type.READ), /** * Provides access to the videos a person has uploaded or been tagged in */ USER_VIDEOS("user_videos", Type.READ), /** * Provides access to the person's personal website URL via the website * field on the {@link Profile} entity. */ USER_WEBSITE("user_website", Type.READ), /** * Provides access to a person's work history and list of employers via the * work field on the {@link Profile} entity. */ USER_WORK_HISTORY("user_work_history", Type.READ), /** * This permission not longer in use in latest graph versions. * Please us Permission#READ_CUSTOM_FRIENDLISTS instead. * * Provides access to the names of custom lists a person has created to organize their friends. * This is useful for rendering an audience selector when someone is publishing stories * to Facebook from your app. * * This permission does not give access to a list of person's friends. If you want to access * a person's friends who also use your app, you should use the user_friends permission. */ @Deprecated READ_FRIENDLISTS("read_friendlists", Type.READ), /** * Provides access to the names of custom lists a person has created to organize their friends. * This is useful for rendering an audience selector when someone is publishing stories * to Facebook from your app. * * This permission does not give access to a list of person's friends. If you want to access * a person's friends who also use your app, you should use the user_friends permission. */ READ_CUSTOM_FRIENDLISTS("read_custom_friendlists", Type.READ), /** * Provides read-only access to the Insights data for Pages, Apps and web * domains the person owns. */ READ_INSIGHTS("read_insights", Type.READ), /** * This permission not longer in use in latest graph versions. * * Provides the ability to read the messages in a person's Facebook Inbox * through the inbox edge and the thread node */ @Deprecated READ_MAILBOX("read_mailbox", Type.READ), /** * This permission not longer in use in latest graph versions. * Please us Permission#USER_POSTS instead. * * Provides access to read the posts in a person's News Feed, or the posts * on their Profile. */ @Deprecated READ_STREAM("read_stream", Type.READ), /** * Provides the ability to read from the Page Inboxes of the Pages managed * by a person. This permission is often used alongside the manage_pages * permission. * * This permission does not let your app read the page owner's mailbox. It * only applies to the page's mailbox. */ READ_PAGE_MAILBOX("read_page_mailboxes", Type.READ), /** * Provides access to the person's primary email address via the * {@link Profile.Properties#EMAIL} property on the {@link Profile} object.<br> * <br> * <b>Note:</b><br> * Even if you request the email permission it is not guaranteed you will * get an email address. For example, if someone signed up for Facebook with * a phone number instead of an email address, the email field may be empty. */ EMAIL("email", Type.READ), /** * Provides access to the posts on a person's Timeline. Includes their own posts, * posts they are tagged in, and posts other people make on their Timeline. */ USER_POSTS("user_posts", Type.READ), /** * Provides the access to Ads Insights API to pull ads report information for ad * accounts you have access to. */ ADS_READ("ads_read", Type.READ), /** * Provides read-only access to the Audience Network Insights data for Apps the person owns. */ READ_AUDIENCE_NETWORK_INSIGHTS("read_audience_network_insights", Type.READ), /** * Provides access to publish Posts, Open Graph actions, achievements, * scores and other activity on behalf of a person using your app. */ PUBLISH_ACTION("publish_actions", Type.PUBLISH), /** * Provides the ability to set a person's attendee status on Facebook Events * (e.g. attending, maybe, or declined). This permission does not let you * invite people to an event. This permission does not let you update an * event's details. This permission does not let you create an event. There * is no way to create an event via the API as of Graph API v2.0. */ RSVP_EVENT("rsvp_event", Type.PUBLISH), /** * This permission not longer in use in latest graph versions. * * Enables your app to read a person's notifications and mark them as read. * This permission does not let you send notifications to a person. */ @Deprecated MANAGE_NOTIFICATIONS("manage_notifications", Type.PUBLISH), /** * Enables your app to retrieve Page Access Tokens for the Pages and Apps * that the person administrates. */ MANAGE_PAGES("manage_pages", Type.PUBLISH); /** * Permission type enum: <li>READ</li> <li>PUBLISH</li><br> */ public static enum Type { PUBLISH, READ; }; public static enum Role { /** * Manage admins<br> * Full Admin */ ADMINISTER, /** * Edit the Page and add apps<br> * Full Admin, Content Creator */ EDIT_PROFILE, /** * Create posts as the Page<br> * Full Admin, Content Creator */ CREATE_CONTENT, /** * Respond to and delete comments, send messages as the Page<br> * Full Admin, Content Creator, Moderator */ MODERATE_CONTENT, /** * Create ads and unpublished page posts<br> * Full Admin, Content Creator, Moderator, Ads Creator */ CREATE_ADS, /** * View Insights<br> * Full Admin, Content Creator, Moderator, Ads Creator, Insights Manager */ BASIC_ADMIN } private final String mValue; private final Type mType; private Permission(String value, Type type) { mValue = value; mType = type; } public String getValue() { return mValue; } public Type getType() { return mType; } public static Permission fromValue(String permissionValue) { for (Permission permission : values()) { if (permission.mValue.equals(permissionValue)) { return permission; } } return null; } public static List<Permission> convert(Collection<String> rawPermissions) { if (rawPermissions == null) { return null; } List<Permission> permissions = new ArrayList<Permission>(); for (Permission permission : values()) { if (rawPermissions.contains(permission.getValue())) { permissions.add(permission); } } return permissions; } public static List<String> convert(List<Permission> permissions) { if (permissions == null) { return null; } List<String> rawPermissions = new ArrayList<String>(); for (Permission permission : permissions) { rawPermissions.add(permission.getValue()); } return rawPermissions; } public static List<String> fetchPermissions(List<Permission> permissions, Type type) { List<String> perms = new ArrayList<String>(); for (Permission permission : permissions) { if (type.equals(permission.getType())) { perms.add(permission.getValue()); } } return perms; } }
e69370f1723ff86d7e97c1d636127b2021897147
d5871e6fbb5a2170a66fce7c0fb577d0a8d9925f
/src/main/java/net/haesleinhuepf/clijx/framor/implementations/TopHatFrameProcessor.java
1a551d083eb8a5ed1f3448e0e238a3246ababae6
[ "BSD-3-Clause" ]
permissive
clij/clijx
d730d9cda6db608a6a8a7517b15476f23ae18039
1c591a1a6f173fd6eb457587c6ef4088c59cdfb6
refs/heads/master
2022-09-03T12:35:22.553705
2022-07-17T16:36:05
2022-07-17T16:36:17
246,394,884
4
7
NOASSERTION
2022-03-11T13:38:19
2020-03-10T19:55:41
Java
UTF-8
Java
false
false
2,506
java
package net.haesleinhuepf.clijx.framor.implementations; import ij.IJ; import ij.ImagePlus; import ij.gui.GenericDialog; import ij.plugin.filter.PlugInFilter; import ij.process.ImageProcessor; import net.haesleinhuepf.clij.clearcl.ClearCLBuffer; import net.haesleinhuepf.clij2.CLIJ2; import net.haesleinhuepf.clijx.framor.AbstractFrameProcessor; import net.haesleinhuepf.clijx.framor.FrameProcessor; import net.haesleinhuepf.clijx.framor.Framor; public class TopHatFrameProcessor extends AbstractFrameProcessor implements PlugInFilter { private Integer radiusX = 10; private Integer radiusY = 10; private Integer radiusZ = 10; public TopHatFrameProcessor(){} public TopHatFrameProcessor(Integer radiusX, Integer radiusY, Integer radiusZ) { this.radiusX = radiusX; this.radiusY = radiusY; this.radiusZ = radiusZ; } @Override public ImagePlus process(ImagePlus imp) { CLIJ2 clij2 = getCLIJ2(); ClearCLBuffer input = clij2.push(imp); ClearCLBuffer output = clij2.create(input); if (imp.getNSlices() > 1) { clij2.topHatBox(input, output, radiusX, radiusY, 0); } else { clij2.topHatBox(input, output, radiusX, radiusY, radiusZ); } ImagePlus result = clij2.pull(output); input.close(); output.close(); return result; } @Override public FrameProcessor duplicate() { TopHatFrameProcessor frameProcessor = new TopHatFrameProcessor(radiusX, radiusY, radiusZ); frameProcessor.setCLIJ2(getCLIJ2()); return frameProcessor; } @Override public long getMemoryNeedInBytes(ImagePlus imp) { return imp.getBitDepth() / 8 * imp.getWidth() * imp.getHeight() * imp.getNSlices() * 2; } @Override public int setup(String arg, ImagePlus imp) { return DOES_ALL; } @Override public void run(ImageProcessor ip) { GenericDialog gd = new GenericDialog("Top-hat background subtraction (CLIJxf)"); gd.addNumericField("Sigma x", radiusX); gd.addNumericField("Sigma y", radiusY); gd.addNumericField("Sigma z", radiusZ); gd.showDialog(); if (gd.wasCanceled()) { return; } radiusX = (int)gd.getNextNumber(); radiusY = (int)gd.getNextNumber(); radiusZ = (int)gd.getNextNumber(); new Framor(IJ.getImage(), new TopHatFrameProcessor(radiusX, radiusY, radiusZ)).getResult().show(); } }
77cacb085400d21ae953f6dd49bcf39bfa2aba06
76bbf4355458bdb0a5e0636004aab21fda9def61
/projet_TP/fr/n7/stl/block/ast/impl/ArrayAssignmentImpl.java
21b50a049ecdc97821c4740eafe52458b3d47552
[]
no_license
sligoo/STDL
d384b9f7e7b42c54b203850d432504cf4be651cd
20d124fcdbdef5e3c3a650bd4be549b7cc0526f1
refs/heads/master
2021-07-10T18:15:53.659574
2017-10-11T07:04:46
2017-10-11T07:04:46
86,471,854
0
0
null
null
null
null
UTF-8
Java
false
false
1,034
java
package fr.n7.stl.block.ast.impl; import fr.n7.stl.block.ast.Assignable; import fr.n7.stl.block.ast.Expression; import fr.n7.stl.tam.ast.Fragment; import fr.n7.stl.tam.ast.Library; import fr.n7.stl.tam.ast.TAMFactory; /** * @author Sacha Liguori * */ public class ArrayAssignmentImpl extends ArrayAccessImpl implements Assignable { /** * @param _array * @param _index */ public ArrayAssignmentImpl(Expression _array, Expression _index) { super(_array, _index); } /* (non-Javadoc) * @see fr.n7.stl.block.ast.impl.ArrayAccessImpl#getCode(fr.n7.stl.tam.ast.TAMFactory) */ @Override public Fragment getCode(TAMFactory _factory) { Fragment fragment = _factory.createFragment(); fragment.append(this.array.getCode(_factory)); fragment.add(_factory.createLoadI(this.getType().length())); fragment.append(this.index.getCode(_factory)); fragment.add(_factory.createLoadL(this.getType().length())); fragment.add(Library.IMul); fragment.add(Library.IAdd); return fragment; } }
7d2927edf818f16d723603c750bdc33f31a48e4a
d7ec1ca68c96e77ec6699ea4d36c7b9235841bb8
/src/viewing/spielstaende/SpeicherRahmen.java
db999530b72602f57f88ae58f54ce256216f145f
[]
no_license
Lanksas/AbschlussProjectWIFI
6386980365e727a656916dc9fa682d1e42209cad
ef6ec0c9403f248091feeef97e294202f3ff78b3
refs/heads/master
2022-06-21T09:40:57.357852
2020-05-06T11:44:13
2020-05-06T11:44:13
261,741,020
0
0
null
null
null
null
UTF-8
Java
false
false
1,312
java
package viewing.spielstaende; import controller.Controller; import viewing.spielRahmen.MainRahmen; import viewing.spielRahmen.einstellungenRahmen.OptionenRahmen; import javax.swing.*; import java.awt.*; public class SpeicherRahmen extends JFrame { public SpeicherRahmen(Controller pController, MainRahmen mr) { JLabel infoLabel = new JLabel("Bitte Namen eingeben:"); JTextField nameField = new JTextField(); JButton saveButton = new JButton("Speichern"); JButton abbrechenButton = new JButton("Abbrechen"); Panel buttonPanel = new Panel(); buttonPanel.setLayout(new GridLayout(1,2)); buttonPanel.add(saveButton); buttonPanel.add(abbrechenButton); abbrechenButton.addActionListener(e -> {dispose(); new OptionenRahmen(pController, mr); }); saveButton.addActionListener(e -> { pController.newSave(nameField.getText()); dispose(); }); this.setTitle("Speichern"); this.setLayout(new GridLayout(3, 1)); this.add(infoLabel); this.add(nameField); this.add(buttonPanel); this.setSize(250, 200); this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); this.setLocationRelativeTo(null); this.setVisible(true); } }
0e07fe1a91b4157ce37d52b8f0978de131b59a43
e29c2e104a00d230c74e1c0bf02c826bc4002e0c
/src/TwitterView.java
55bb890763a9574da265078417cb63c04fa9cf13
[]
no_license
sandyman17/TwitterReplica
cdfa08764f82f449e07267cdc78078b5dcba9f65
557bab00f1c555f9d348d610f677071e1c2232d7
refs/heads/master
2022-11-27T02:35:54.158764
2020-07-28T02:50:37
2020-07-28T02:50:37
283,079,942
0
0
null
null
null
null
UTF-8
Java
false
false
2,223
java
import javax.swing.*; /** * TwitterView * * Serves the view portion of the MVC paradigm, controls the overall look (front end) of the entire message board. * Combines the four 'tabs' (AddTweet, EditTweet ...) together into one cohesive GUI. * * @author Purdue CS * * @version April 20, 2020 * */ public final class TwitterView { private JPanel mainPanel; private AddTweet addTweet; private DeleteTweet deleteTweet; private EditTweet editTweet; private SearchTweet searchTweet; private JTabbedPane mainTabbedPane; /** Default constructor for TwitterView*/ public TwitterView() { this.addTweet = new AddTweet(); this.editTweet = new EditTweet(); this.deleteTweet = new DeleteTweet(); this.searchTweet = new SearchTweet(); /** Put all the "add, edit, delete, search" tabs to one main Twitter message board Feed 'menu' */ this.mainTabbedPane.add("Add", this.addTweet.getMainPanel()); this.mainTabbedPane.add("Edit", this.editTweet.getMainPanel()); this.mainTabbedPane.add("Delete", this.deleteTweet.getMainPanel()); this.mainTabbedPane.add("Search", this.searchTweet.getMainPanel()); } /** Standard accessor methods for the private variables in TwitterView.java */ /** Get the JTabbedPane component * * @return mainTabbedPane */ public JTabbedPane getMainTabbedPane() { return this.mainTabbedPane; } /** Get the AddTweet component * * @return addTweet */ public AddTweet getAddTweet() { return this.addTweet; } /** Get the EditTweet component * * @return editTweet */ public EditTweet getEditTweet() { return this.editTweet; } /** Get the DeleteTweet component * * @return deleteTweet */ public DeleteTweet getDeleteTweet() { return this.deleteTweet; } /** Get the SearchTweet component * * @return searchTweet */ public SearchTweet getSearchTweet() { return this.searchTweet; } /** Get the JPanel component * * @return mainPanel */ public JPanel getMainPanel() { return this.mainPanel; } }
7f8d411ef8b6f12b144462d9d5d8df0ca9cd46e7
4730f78c9ee8a9ed8dd8ec702961c1ed7e381888
/src/leetcode/firstMissingPositive.java
920705d417ee0d743dc9942d0f789ebaca1631e7
[]
no_license
Md-Milton/LeetCodeSolution
ba852a8ae9934a3afa13c81a8ec0c1c46bf5e09d
3852cef415c8a96f9fdad0cac42076df46a821f8
refs/heads/master
2023-07-04T19:53:46.650804
2021-08-26T18:26:06
2021-08-26T18:26:06
291,403,386
2
0
null
null
null
null
UTF-8
Java
false
false
948
java
/* * 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 leetcode; /** * * @author milton */ public class firstMissingPositive { public int firstMissingPositive(int[] nums) { if(nums.length==0) return 1; int i=0; while(i<nums.length){ if(nums[i]>0 && nums[i]<=nums.length && nums[i]!=nums[nums[i]-1]){ int index = nums[i]-1; int temp = nums[i]; nums[i] = nums[index]; nums[index] = temp; } else{ i++; } for(i=0;i<nums.length;i++){ if(nums[i]!=i+1) return i+1; } } return nums.length+1; } }
[ "milton@DESKTOP-7KGO5UF" ]
milton@DESKTOP-7KGO5UF
2bfd0e58e5cf5d420496a25ac3effc298d6dcda7
1a9c044174d5db3d1dcaf29a40efeef54e3772ac
/spring-reactive/src/test/java/com/spring/reactive/fluxandmono/FluxAndMonoTest.java
ceee66ac9dc5fb566fc94950510696d43a2c74cf
[]
no_license
lalitrnagpal/spring-reactive
f6c3d05de925a36bbdefee406376e94be8182394
94bb8c090242a94473511113d5638b5514b816cf
refs/heads/main
2023-02-18T08:41:24.554509
2021-01-18T09:44:04
2021-01-18T09:44:04
330,615,452
1
0
null
null
null
null
UTF-8
Java
false
false
1,885
java
package com.spring.reactive.fluxandmono; import org.junit.jupiter.api.Test; import reactor.core.publisher.Flux; import reactor.test.StepVerifier; public class FluxAndMonoTest { @Test public void fluxTestWithoutError() { Flux<String> stringFlux = Flux.just("Spring", "Spring Boot", "Spring Reactive") .log(); StepVerifier.create(stringFlux) .expectNext("Spring") .expectNext("Spring Boot") .expectNext("Spring Reactive") .verifyComplete(); } @Test public void fluxTestElementsWithoutError() { Flux<String> stringFlux = Flux.just("Spring", "Spring Boot", "Spring Reactive") .concatWith(Flux.error(new RuntimeException("Runtime Exception occurred"))) .log(); StepVerifier.create(stringFlux) .expectNext("Spring") .expectNext("Spring Boot") .expectNext("Spring Reactive") .verifyError(); StepVerifier.create(stringFlux) .expectNext("Spring") .expectNext("Spring Boot") .expectNext("Spring Reactive") .expectError(RuntimeException.class) .verify(); StepVerifier.create(stringFlux) .expectNext("Spring") .expectNext("Spring Boot") .expectNext("Spring Reactive") .expectErrorMessage("Runtime Exception occurred") .verify(); } @Test public void fluxTestElementsCount() { Flux<String> stringFlux = Flux.just("Spring", "Spring Boot", "Spring Reactive") .concatWith(Flux.error(new RuntimeException("Runtime Exception occurred"))) .log(); StepVerifier.create(stringFlux) .expectNextCount(5) .expectError(); } @Test public void fluxTestElements() { Flux<String> stringFlux = Flux.just("Spring", "Spring Boot", "Spring Reactive") .log(); StepVerifier.create(stringFlux) .expectNext("Spring", "Spring Boot", "Spring Reactive") .verifyComplete(); } }
2d5cd6a19a51adddc6aefd95b59984d862ac50f1
96224e564d31565bc06c4f4b6881a36c56c6d35b
/src/main/java/com/bluewise/common/exception/user/UserPasswordRetryLimitCountException.java
e0956b513149839e02270f45844091d670a9cff5
[]
no_license
vivwangsc/xmgl
6d7fc26bfd59b2d1fdd34d6edab896fb3850bd43
41a8cfb51a45491eecd5358d2332993974409c43
refs/heads/master
2020-04-10T17:46:50.269804
2018-12-19T00:01:40
2018-12-19T00:01:40
70,388,983
0
0
null
null
null
null
UTF-8
Java
false
false
403
java
package com.bluewise.common.exception.user; /** * 用户错误记数异常类 * * @author bluewise */ public class UserPasswordRetryLimitCountException extends UserException { private static final long serialVersionUID = 1L; public UserPasswordRetryLimitCountException(int retryLimitCount) { super("user.password.retry.limit.count", new Object[] { retryLimitCount }); } }
bde3e7bfbd83003d066afe602acb1b067dbb0622
6482753b5eb6357e7fe70e3057195e91682db323
/com/google/common/base/CommonPattern.java
45ed0e21f81adfafa9a32f879ea42e0da08abe81
[]
no_license
TheShermanTanker/Server-1.16.3
45cf9996afa4cd4d8963f8fd0588ae4ee9dca93c
48cc08cb94c3094ebddb6ccfb4ea25538492bebf
refs/heads/master
2022-12-19T02:20:01.786819
2020-09-18T21:29:40
2020-09-18T21:29:40
296,730,962
0
1
null
null
null
null
UTF-8
Java
false
false
417
java
package com.google.common.base; import com.google.common.annotations.GwtCompatible; @GwtCompatible abstract class CommonPattern { abstract CommonMatcher matcher(final CharSequence charSequence); abstract String pattern(); abstract int flags(); public abstract String toString(); public abstract int hashCode(); public abstract boolean equals(final Object object); }
af476627ab167187e42978fbfed9ba718f43ba95
2560cb46332a0099d18d0cbc95837af7241089b3
/src/com/lans/filter/EncodingFilter.java
25797955721b853c5201560baadfc76d90ab5b1e
[]
no_license
LanSunSL/mvc-GoodsProject
a693775f9428d7fea8f7c9f612ed54ef950d264b
c34e9a00d1c79baf0e1856186ab899d8d8306469
refs/heads/master
2021-01-20T03:29:59.017861
2017-04-28T16:53:08
2017-04-28T16:53:08
89,550,230
0
0
null
null
null
null
UTF-8
Java
false
false
1,017
java
package com.lans.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; import javax.servlet.annotation.WebInitParam; @WebFilter(urlPatterns="/*", initParams={ @WebInitParam(name="charset", value="UTF-8") }) public class EncodingFilter implements Filter { private String charset; @Override public void init(FilterConfig filterConfig) throws ServletException { this.charset = filterConfig.getInitParameter("charset"); if (charset == null || "".equals(charset)) { charset = "UTF-8"; } } @Override public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { req.setCharacterEncoding(charset); resp.setCharacterEncoding(charset); chain.doFilter(req, resp); } }
bc31e1986e4761db2523d3004618b04f96997852
dd2c08aef04c22f4e4fe65b95a78668cf54526f1
/src/main/java/com/custom/slf4j/CustomLogger.java
fc1c0a8a68fee5d128ee660e65ca7cef40efa85d
[]
no_license
JohnnyLe/CustomLogSfl4j
e252c0d298764fc19a8a5d80a62d867ec99ebcb9
b8c2470aa9701408870104cf0a66b85fe66334e8
refs/heads/master
2020-03-24T09:06:33.388203
2018-07-27T20:02:32
2018-07-27T20:02:32
142,618,703
0
0
null
null
null
null
UTF-8
Java
false
false
13,636
java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.custom.slf4j; import org.slf4j.Logger; import org.slf4j.Marker; import org.springframework.stereotype.Component; /** * * @author johnny */ @Component // This is custom Log implement to save log into Database other other service API public class CustomLogger implements Logger{ @Override public String getName() { return "CustomLogger"; } @Override public boolean isTraceEnabled() { return false; // // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void trace(String string) { //// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void trace(String string, Object o) { //// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void trace(String string, Object o, Object o1) { //// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void trace(String string, Object... os) { //// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void trace(String string, Throwable thrwbl) { //// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public boolean isTraceEnabled(Marker marker) { return false; //// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void trace(Marker marker, String string) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void trace(Marker marker, String string, Object o) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void trace(Marker marker, String string, Object o, Object o1) { //// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void trace(Marker marker, String string, Object... os) { //// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void trace(Marker marker, String string, Throwable thrwbl) { //// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public boolean isDebugEnabled() { return false; } @Override public void debug(String string) { //// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void debug(String string, Object o) { System.out.println(string + o); //// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void debug(String string, Object o, Object o1) { //// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void debug(String string, Object... os) { //// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void debug(String string, Throwable thrwbl) { //// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public boolean isDebugEnabled(Marker marker) { return false; //// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void debug(Marker marker, String string) { //// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void debug(Marker marker, String string, Object o) { //// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void debug(Marker marker, String string, Object o, Object o1) { //// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void debug(Marker marker, String string, Object... os) { //// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void debug(Marker marker, String string, Throwable thrwbl) { //// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public boolean isInfoEnabled() { return true; //// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void info(String string) { //// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void info(String string, Object o) { System.out.println(string + o); //// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void info(String string, Object o, Object o1) { //// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void info(String string, Object... os) { //// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void info(String string, Throwable thrwbl) { //// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public boolean isInfoEnabled(Marker marker) { return true; //// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void info(Marker marker, String string) { //// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void info(Marker marker, String string, Object o) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void info(Marker marker, String string, Object o, Object o1) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void info(Marker marker, String string, Object... os) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void info(Marker marker, String string, Throwable thrwbl) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public boolean isWarnEnabled() { return false; // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void warn(String string) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void warn(String string, Object o) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void warn(String string, Object... os) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void warn(String string, Object o, Object o1) { //// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void warn(String string, Throwable thrwbl) { //// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public boolean isWarnEnabled(Marker marker) { return false; // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void warn(Marker marker, String string) { //// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void warn(Marker marker, String string, Object o) { //// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void warn(Marker marker, String string, Object o, Object o1) { //// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void warn(Marker marker, String string, Object... os) { //// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void warn(Marker marker, String string, Throwable thrwbl) { //// throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public boolean isErrorEnabled() { return false; // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void error(String string) { System.out.println("CUSTOM LOG ERROR: ===> " + string); } @Override public void error(String string, Object o) { System.out.println("CUSTOM LOG ERROR: ===> " + string + " | " + o); } @Override public void error(String string, Object o, Object o1) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void error(String string, Object... os) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void error(String string, Throwable thrwbl) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public boolean isErrorEnabled(Marker marker) { return false; // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void error(Marker marker, String string) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void error(Marker marker, String string, Object o) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void error(Marker marker, String string, Object o, Object o1) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void error(Marker marker, String string, Object... os) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } @Override public void error(Marker marker, String string, Throwable thrwbl) { // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
aeb5e30889a46bbbe5aff5ef917590fc9eb44050
e093ca580f54d8e2edba68a73821ed37a1ca0bce
/src/main/java/vista/vistaConfiguracion/VentanaAcerca.java
2e9107448d99b1deda3df939e96621e2ebe3aa5e
[]
no_license
jucsp/PetAlive
7bad2a4358cd041baa555921d1570fdcdbe49ace
388d74827eb968c5f50f3ef60ccc36887300bc4c
refs/heads/master
2022-06-18T23:01:50.768304
2018-08-09T18:34:46
2018-08-09T18:34:46
133,447,791
0
0
null
null
null
null
UTF-8
Java
false
false
732
java
package vista.vistaConfiguracion; import java.awt.BorderLayout; import javax.swing.JFrame; /** * * @author Juan Carlos */ public class VentanaAcerca extends JFrame{ private PanelAcerca pnlAcerca; public VentanaAcerca(){ this.iniciarComponentes(); } private void iniciarComponentes(){ this.pnlAcerca = new PanelAcerca(); this.add(this.pnlAcerca, BorderLayout.CENTER); this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); this.setTitle("Acerda de..."); this.setLocation(50,50); this.setVisible(true); this.setResizable(false); pack(); } }
6f15a2ef0811b8217956250e8eb6a53944757303
18ae7f67a749a5cfed36163b750f0caf1f514dcf
/src/main/java/com/onshape/api/requests/AppElementsCreateElementRequestLocation.java
9d6175cbdf31b29d07ebc69ae6cb8b76273591d1
[ "MIT" ]
permissive
Change2improve/java-client
d936d35d20d8dbb192d2470f096d06babd034b65
5da89caf8c678342376b67eafd6a0fba6289a41a
refs/heads/master
2020-04-11T05:50:54.304309
2018-11-01T14:31:47
2018-11-01T14:31:47
161,561,752
0
0
null
null
null
null
UTF-8
Java
false
false
7,758
java
// The MIT License (MIT) // // Copyright (c) 2018 - Present Onshape Inc. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // package com.onshape.api.requests; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; import com.onshape.api.Onshape; import java.lang.Number; import java.lang.Override; import java.lang.String; /** * Object used in calls to createElement API endpoint. * &copy; 2018 Onshape Inc. */ @JsonIgnoreProperties( ignoreUnknown = true ) public final class AppElementsCreateElementRequestLocation { /** * For internal use. */ @JsonProperty("groupId") public String groupId; /** * Id of an element to place the new element near. */ @JsonProperty("elementId") public String elementId; /** * An indicator for the relative placement of the new element. If elementId is specified, a negative number indicates insertion prior to the element and a non-negative number indicates insertion following the element. If no elementId is specified, a negative value indicates insertion at the end of the group or element list and a non-negative number indicates insertion at the start of the group or elmenet list. */ @JsonProperty("position") public Number position; AppElementsCreateElementRequestLocation(String groupId, String elementId, Number position) { this.groupId = groupId; this.elementId = elementId; this.position = position; } /** * Get For internal use. * * @return For internal use. * */ public final String getGroupId() { return this.groupId; } /** * Get Id of an element to place the new element near. * * @return Id of an element to place the new element near. * */ public final String getElementId() { return this.elementId; } /** * Get An indicator for the relative placement of the new element. If elementId is specified, a negative number indicates insertion prior to the element and a non-negative number indicates insertion following the element. If no elementId is specified, a negative value indicates insertion at the end of the group or element list and a non-negative number indicates insertion at the start of the group or elmenet list. * * @return An indicator for the relative placement of the new element. If elementId is specified, a negative number indicates insertion prior to the element and a non-negative number indicates insertion following the element. If no elementId is specified, a negative value indicates insertion at the end of the group or element list and a non-negative number indicates insertion at the start of the group or elmenet list. * */ public final Number getPosition() { return this.position; } public static final Builder builder() { Builder builder = new Builder(); return builder; } @Override public String toString() { return Onshape.toString(this); } public static final class Builder { /** * For internal use. */ private String groupId; /** * Id of an element to place the new element near. */ private String elementId; /** * An indicator for the relative placement of the new element. If elementId is specified, a negative number indicates insertion prior to the element and a non-negative number indicates insertion following the element. If no elementId is specified, a negative value indicates insertion at the end of the group or element list and a non-negative number indicates insertion at the start of the group or elmenet list. */ private Number position; Builder() { } /** * Get For internal use. * * @return For internal use. * */ public final String groupId() { return this.groupId; } /** * Set For internal use. * * @param value For internal use. * * @return the Builder object. */ public final Builder groupId(String value) { this.groupId = value; return this; } /** * Get Id of an element to place the new element near. * * @return Id of an element to place the new element near. * */ public final String elementId() { return this.elementId; } /** * Set Id of an element to place the new element near. * * @param value Id of an element to place the new element near. * * @return the Builder object. */ public final Builder elementId(String value) { this.elementId = value; return this; } /** * Get An indicator for the relative placement of the new element. If elementId is specified, a negative number indicates insertion prior to the element and a non-negative number indicates insertion following the element. If no elementId is specified, a negative value indicates insertion at the end of the group or element list and a non-negative number indicates insertion at the start of the group or elmenet list. * * @return An indicator for the relative placement of the new element. If elementId is specified, a negative number indicates insertion prior to the element and a non-negative number indicates insertion following the element. If no elementId is specified, a negative value indicates insertion at the end of the group or element list and a non-negative number indicates insertion at the start of the group or elmenet list. * */ public final Number position() { return this.position; } /** * Set An indicator for the relative placement of the new element. If elementId is specified, a negative number indicates insertion prior to the element and a non-negative number indicates insertion following the element. If no elementId is specified, a negative value indicates insertion at the end of the group or element list and a non-negative number indicates insertion at the start of the group or elmenet list. * * @param value An indicator for the relative placement of the new element. If elementId is specified, a negative number indicates insertion prior to the element and a non-negative number indicates insertion following the element. If no elementId is specified, a negative value indicates insertion at the end of the group or element list and a non-negative number indicates insertion at the start of the group or elmenet list. * * @return the Builder object. */ public final Builder position(Number value) { this.position = value; return this; } public final AppElementsCreateElementRequestLocation build() { return new com.onshape.api.requests.AppElementsCreateElementRequestLocation(groupId,elementId,position); } } }
2d81d210ce15fd820e596957fcc99a3d57ca17a9
e70256a6e2d2b9be8620dc8749e78882b00b2faa
/src/main/java/com/itgarden/controller/UserPrivateController.java
aa983e6f158715f510494602c699e61f93f909ee
[]
no_license
sobanjawaid26/billingsystem
74307807e3c3f37169e7ce80589113fdc804e0fb
5497af0accc9c54bfd8e156cd7e431ab96bd354d
refs/heads/main
2023-01-15T10:41:16.870539
2020-11-23T18:31:30
2020-11-23T18:31:30
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,012
java
package com.itgarden.controller; import com.itgarden.common.staticdata.UserType; import com.itgarden.dto.*; import com.itgarden.messages.ResponseMessage; import com.itgarden.service.bo.CustomerService; import com.itgarden.service.bo.EmployeeService; import com.itgarden.service.bo.RegistrationService; import com.itgarden.service.bo.VendorService; import com.itgarden.validator.UserValidator; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.validation.annotation.Validated; import org.springframework.web.bind.annotation.*; import javax.validation.Valid; @RestController @RequestMapping("api/private/users") @Validated public class UserPrivateController { private final CustomerService customerService; private final EmployeeService employeeService; private final VendorService vendorService; private final RegistrationService registrationService; private final UserValidator userValidator; @Autowired public UserPrivateController(CustomerService customerService, EmployeeService employeeService, VendorService vendorService, RegistrationService registrationService, UserValidator userValidator) { this.customerService = customerService; this.employeeService = employeeService; this.vendorService = vendorService; this.registrationService = registrationService; this.userValidator = userValidator; } @PostMapping("/employees") // http://localhost:9091/api/public/users/employees public ResponseEntity<ResponseMessage<?>> saveEmployee(@Valid @RequestBody EmployeeInfo requestBody) throws Exception { requestBody.setType(UserType.EMPLOYEE.name()); userValidator.validate(requestBody); ResponseMessage responseMessage = registrationService.doRegistration(requestBody); return new ResponseEntity<ResponseMessage<?>>(responseMessage, HttpStatus.CREATED); } @PostMapping("/customers") // http://localhost:9091/api/public/users/customers public ResponseEntity<ResponseMessage<?>> saveCustomer(@Valid @RequestBody CustomerInfo requestBody) throws Exception { requestBody.setType(UserType.CUSTOMER.name()); userValidator.validate(requestBody); ResponseMessage responseMessage = registrationService.doRegistration(requestBody); return new ResponseEntity<ResponseMessage<?>>(responseMessage, HttpStatus.CREATED); } @PostMapping("/vendors") public ResponseEntity<ResponseMessage<?>> saveVendor(@Valid @RequestBody VendorInfo requestBody) throws Exception { requestBody.setType(UserType.VENDOR.name()); userValidator.validate(requestBody); ResponseMessage responseMessage = registrationService.doRegistration(requestBody); return new ResponseEntity<ResponseMessage<?>>(responseMessage, HttpStatus.CREATED); } @GetMapping("/customers/{id}") public ResponseEntity<ResponseMessage<?>> viewCustomer(@PathVariable String id) throws Exception { ResponseMessage responseMessage = customerService.findResourceById(id); return new ResponseEntity<ResponseMessage<?>>(responseMessage, HttpStatus.OK); } @GetMapping("/employees/{id}") public ResponseEntity<ResponseMessage<?>> viewEmployee(@PathVariable String id) throws Exception { ResponseMessage responseMessage = employeeService.findResourceById(id); return new ResponseEntity<ResponseMessage<?>>(responseMessage, HttpStatus.OK); } @GetMapping("/vendors/{id}") public ResponseEntity<ResponseMessage<?>> viewVendor(@PathVariable String id) throws Exception { ResponseMessage responseMessage = vendorService.findResourceById(id); return new ResponseEntity<ResponseMessage<?>>(responseMessage, HttpStatus.OK); } }
bf61ed0bb21f7c7a36ad56b296cceb4e8f239478
dbd2ed3f4381b9a15ff9d9597e97e0f5d120eeff
/ystart-upms/ystart-upms-biz/src/main/java/tech/yiren/ystart/admin/mapper/SysMenuMapper.java
6864ae8baf54381ab03e879e75608a657019e70c
[]
no_license
tt-52101/ystart
80ba6d680192c28b62e9142aa8f4e50c1e22c002
33e9adba2d4d02c07a948593730a64969a8f9ad6
refs/heads/master
2023-06-28T20:56:25.702462
2021-08-04T01:35:54
2021-08-04T01:35:54
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,476
java
/* * * Copyright (c) 2018-2025, ystart 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 pig4cloud.com developer nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * Author: ystart * */ package tech.yiren.ystart.admin.mapper; import tech.yiren.ystart.admin.api.entity.SysMenu; import tech.yiren.ystart.common.data.datascope.YstartBaseMapper; import org.apache.ibatis.annotations.Mapper; import java.util.List; /** * <p> * 菜单权限表 Mapper 接口 * </p> * * @author ystart * @since 2017-10-29 */ @Mapper public interface SysMenuMapper extends YstartBaseMapper<SysMenu> { /** * 通过角色编号查询菜单 * @param roleId 角色ID * @return */ List<SysMenu> listMenusByRoleId(Integer roleId); /** * 通过角色ID查询权限 * @param roleIds Ids * @return */ List<String> listPermissionsByRoleIds(String roleIds); }
479eeb03a557c8f8d1d0582ed2663e3b3bcf683d
c552ecad5c7fd629538a11fa5bcde45daeeb16a4
/app/src/test/java/com/hilay/actionbar/ExampleUnitTest.java
9a903a3b0adf362bc775284f8f2160d96affc02b
[]
no_license
Nickleby9/ActionbarNew
f3cdfec26b9ff5693ba69544069f40a675b8c3c0
6f57e170a67585d71c6d00a0854e56615cd3efce
refs/heads/master
2021-06-17T13:56:45.042325
2017-05-03T19:30:22
2017-05-03T19:30:22
null
0
0
null
null
null
null
UTF-8
Java
false
false
397
java
package com.hilay.actionbar; import org.junit.Test; import static org.junit.Assert.*; /** * Example local unit test, which will execute on the development machine (host). * * @see <a href="http://d.android.com/tools/testing">Testing documentation</a> */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
4339e576cc38cfeccf7b3cbd2341314922fffbfe
911c4c70ba12f863ee906d2435af19ca652ddde8
/hyb-ct-usercenter/src/main/java/com/mszx/hyb/entity/VirtualRecord.java
0d80740e5ac5dbe49b53815a8cf1f1ffce968007
[]
no_license
ahuiwanglei/hyb-ct-service
bb98d9dccf6302bc20053b3dd08e54d6dc663fa3
993eaf3409e0fa9a3c814a5dbceba6e6d070bdce
refs/heads/main
2023-04-23T06:11:39.840344
2021-05-04T04:09:31
2021-05-04T04:09:31
363,552,996
0
0
null
null
null
null
UTF-8
Java
false
false
3,509
java
package com.mszx.hyb.entity; import java.math.BigDecimal; import java.util.Date; public class VirtualRecord { private String pkmembervirtualrecord; private String pkregister; private Date startdate; private BigDecimal amount; private Integer type; private String remark; private String createuser; private Date createtime; private String sourcepk; private String pkmuser; private String totalCount; //累计惠缘币 private String virtualBalance; //剩余惠缘币 private Integer status = 1; public VirtualRecord() { } public VirtualRecord(String pkmembervirtualrecord, String pkregister, BigDecimal amount, Integer type, String remark, String sourcepk, String pkmuser) { this.pkmembervirtualrecord = pkmembervirtualrecord; this.pkregister = pkregister; this.amount = amount; this.type = type; this.remark = remark; this.sourcepk = sourcepk; this.pkmuser = pkmuser; } public Integer getStatus() { return status; } public void setStatus(Integer status) { this.status = status; } public String getTotalCount() { return totalCount; } public void setTotalCount(String totalCount) { this.totalCount = totalCount; } public String getVirtualBalance() { return virtualBalance; } public void setVirtualBalance(String virtualBalance) { this.virtualBalance = virtualBalance; } public String getPkmuser() { return pkmuser; } public void setPkmuser(String pkmuser) { this.pkmuser = pkmuser; } public String getSourcepk() { return sourcepk; } public void setSourcepk(String sourcepk) { this.sourcepk = sourcepk; } public String getPkmembervirtualrecord() { return pkmembervirtualrecord; } public void setPkmembervirtualrecord(String pkmembervirtualrecord) { this.pkmembervirtualrecord = pkmembervirtualrecord; } public String getPkregister() { return pkregister; } public void setPkregister(String pkregister) { this.pkregister = pkregister; } public Date getStartdate() { return startdate; } public void setStartdate(Date startdate) { this.startdate = startdate; } public BigDecimal getAmount() { return amount; } public void setAmount(BigDecimal amount) { this.amount = amount; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getCreateuser() { return createuser; } public void setCreateuser(String createuser) { this.createuser = createuser; } public Date getCreatetime() { return createtime; } public void setCreatetime(Date createtime) { this.createtime = createtime; } @Override public String toString() { return "VirtualRecord [pkmembervirtualrecord=" + pkmembervirtualrecord + ", pkregister=" + pkregister + ", startdate=" + startdate + ", amount=" + amount + ", type=" + type + ", remark=" + remark + ", createuser=" + createuser + ", createtime=" + createtime + "]"; } }
235d9890a05e37e4a70132b81e3534f67a5e53c8
04c569129b6f89aeeeb21cf3dad90a144148a968
/src/main/java/com/ashkan/ie/domain/UserAuthority.java
f09ab8861add3a2a88bb938963ee4de0743d1552
[]
no_license
nimaaj93/ei-project
d51358ed49b0bb171a8e2593b367b67caa760be7
d5dc9e6c3b6976a45f4142260379a31d4155647d
refs/heads/master
2023-01-06T02:50:37.643406
2019-06-21T14:14:17
2019-06-21T14:14:17
190,589,104
0
0
null
2023-01-04T00:38:43
2019-06-06T13:46:58
CSS
UTF-8
Java
false
false
903
java
package com.ashkan.ie.domain; import com.ashkan.ie.enumeration.UserType; import javax.persistence.*; /** * Created by K550 VX on 6/6/2019. */ @Entity @Table(name = "ie_user_authority") public class UserAuthority extends BaseEntity { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Enumerated(EnumType.STRING) private UserType authorityVal; @OneToOne private User user; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public UserType getAuthorityVal() { return authorityVal; } public void setAuthorityVal(UserType authorityVal) { this.authorityVal = authorityVal; } }
06ed9b72c44a04f33714eab3b07694455b9713e0
1c0c8f70a04b1a24faf08f198afe380edcee3a1e
/app/src/main/java/com/google/api/client/http/MultipartContent.java
07378fa27f580f2d338e843befea35def5111627
[ "Apache-2.0" ]
permissive
alonerocky/PicasaPlus
77b8adcac723049ca85218aacd0514273a7b304f
e8a4cf7f3e747655b6037f442cfff4da96bc2720
refs/heads/master
2021-01-21T05:05:41.962453
2014-12-14T14:41:11
2014-12-14T14:41:11
null
0
0
null
null
null
null
UTF-8
Java
false
false
3,807
java
package com.google.api.client.http; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import org.apache.http.util.ByteArrayBuffer; /** * Multi-part related content. * * @since 2.2 * @author Yaniv Inbar */ public final class MultipartContent implements HttpContent { // TODO: test it! // TODO: instead of getBytes() use getBytes("UTF-8")? private static final byte[] CR_LF = "\r\n".getBytes(); private static final byte[] HEADER = "Media multipart posting".getBytes(); private static final byte[] CONTENT_TYPE = "Content-Type: ".getBytes(); private static final byte[] CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding: binary".getBytes(); private static final byte[] TWO_DASHES = "--".getBytes(); private static final byte[] END_OF_PART = "END_OF_PART".getBytes(); private final byte[] metadataContentTypeBytes; private final byte[] mediaTypeBytes; private final HttpContent metadata; private final HttpContent content; private final long length; public MultipartContent(HttpContent metadata, HttpContent content) { byte[] metadataContentTypeBytes = metadata.getType().getBytes(); byte[] mediaTypeBytes = content.getType().getBytes(); long metadataLength = content.getLength(); this.length = metadataLength + content.getLength() + mediaTypeBytes.length + metadataContentTypeBytes.length + HEADER.length + 2 * CONTENT_TYPE.length + CONTENT_TRANSFER_ENCODING.length + 3 * END_OF_PART.length + 10 * CR_LF.length + 4 * TWO_DASHES.length; this.metadata = metadata; this.content = content; this.metadataContentTypeBytes = metadataContentTypeBytes; this.mediaTypeBytes = mediaTypeBytes; } public void forRequest(HttpRequest request) { request.headers.mimeVersion = "1.0"; request.content = this; } public void writeTo(OutputStream out) throws IOException { out.write(HEADER); out.write(CR_LF); out.write(TWO_DASHES); out.write(END_OF_PART); out.write(CR_LF); out.write(CONTENT_TYPE); out.write(metadataContentTypeBytes); out.write(CR_LF); out.write(CR_LF); metadata.writeTo(out); out.write(CR_LF); out.write(TWO_DASHES); out.write(END_OF_PART); out.write(CR_LF); out.write(CONTENT_TYPE); out.write(mediaTypeBytes); out.write(CR_LF); out.write(CONTENT_TRANSFER_ENCODING); out.write(CR_LF); out.write(CR_LF); content.writeTo(out); out.write(CR_LF); out.write(TWO_DASHES); out.write(END_OF_PART); out.write(TWO_DASHES); out.flush(); } public byte[] getContent() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); out.write(HEADER); out.write(CR_LF); out.write(TWO_DASHES); out.write(END_OF_PART); out.write(CR_LF); out.write(CONTENT_TYPE); out.write(metadataContentTypeBytes); out.write(CR_LF); out.write(CR_LF); metadata.writeTo(out); out.write(CR_LF); out.write(TWO_DASHES); out.write(END_OF_PART); out.write(CR_LF); out.write(CONTENT_TYPE); out.write(mediaTypeBytes); out.write(CR_LF); out.write(CONTENT_TRANSFER_ENCODING); out.write(CR_LF); out.write(CR_LF); // content.writeTo(out); out.write(CR_LF); out.write(TWO_DASHES); out.write(END_OF_PART); out.write(TWO_DASHES); out.flush(); return out.toByteArray(); } public String getEncoding() { return null; } public long getLength() { return this.length; } public String getType() { return "multipart/related; boundary=\"END_OF_PART\""; } }
1c92f8ed22862a3d3fcfb8bcf9e837474974b73f
bc6bfd92b640e19fb91ec1739be4b9ec84355c02
/Day1012/src/CheatSheet.java
f2696d4f65037389f59bdb23466f4c8cc33493cd
[]
no_license
St4rFi5h/JAVA
0ed02b194fbfa66678f40e828dff8f4a6b901e1c
09f18111a20c8dab435ad2ece13bbdf206dd114c
refs/heads/master
2023-01-05T20:08:43.946431
2020-11-12T07:14:24
2020-11-12T07:14:24
297,852,823
0
0
null
null
null
null
UHC
Java
false
false
5,463
java
import java.util.Scanner; //스캐너 사용.1 import Project01.Pro10; import java.util.Random; // 랜덤 사용 import java.io.*; //버퍼리로더 준비 public class Cheatsheet { public static void main(String[] args) { ////////////////////스캔, 랜덤 , 버퍼리로더 //////////////////// Scanner scan = new Scanner (System.in); // 스캐너 사용.2 int c = scan.nextInt(); // c 값 키보드 입력받기 Random random = new Random(); // 랜덤사용 int a = random.nextInt(100); // 100까지의 랜섬정수 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); //버퍼리로더 사용 (System.in)= 키보드랑연결 //버퍼리로더는 문자로받아서 인트형으로 변환 String str1 = br.readLine(); int num1 = Integer.parseInt(str1); ////////////////////연산자//////////////////// if (a>b && a>c) // && 그리고 if (a>b || a>c) // ||또는 if (a>b != a>c) // != 안닌 else if(b == 2) // 값을 비교 else if(b = 2) // 값을 지정 오른쪽에서 왼쪽 대입 System.out.println("내용"); //출력 ////////////////////배열 //////////////////// int [] A = {5,9,3}; //배열값 임의로 지정 int [] B = new int [10]; //배열 공간만 지정 0부터 9까지만사용하는것 *1부터 10까지가 아님* String[] itstring = new String[3]; // 스트링 공간 지정 int c = 1; int c = scan.nextInt(); // c 값 키보드 입력받기 ///잘못된 배열선언/// int []myScores; char []myChars; int [5] love ; //x 배열만들때 사이즈는 참조변수 옆에 안붙는다 Dog myDogs1[]; //클래스형 배열 Dog myDog2[7]; //x ////////////////////for 문 //////////////////// for(;;) { // 무한 포문 } for(int i = 0 ; i<5; i++) //포문 기본모양 System.out.println(test[0]); System.out.println(test[0]); ////////////////////배열을 통한 최솟값 최댓값//////////////////// for(int i=0; i<a.length;i++) { if(max<a[i]) { //max < a 이면 최댓값은 a max = a[i]; } if(min>a[i]) { //min > a 이면 최솟값은 a min = a[i]; ////////////////////최댓값 최솟값 삼항연산자 //////////////////// int max = b[0] > b[1] ? (max = b[0]) : (max = b[1]) ; max = max > b[2] ? max : (max = b[2]) ; int min = b[0] > b[1] ? (min = b[1]) : (min = b[0]) ; min = min < b[2] ? min : b[2]; // 최댓값 최솟값 삼항연산자 //////////////////// 배열 합을구하는 for 문 //////////////////// for(int i=0; i<a.length;i++) { sum+=a[i]; //모든합을 구하는 for 문 } ////////////////////배열의 피라미드 형식//////////////////// int[] [] a = new int [3][]; a[0] = new int [3]; a[1] = new int [2]; a[2] = new int [3]; ㅁ // 이런식의 피라미드 모양가능 ㅁㅁ ㅁㅁㅁ ////////////////////class 배열//////////////////// Grade[] grade = new Grade[]; // 만으로 클래스 배열이 생성이안되서 grade[i] = new Grade[]; // 포문안에 를써쭤야한다 이걸써주는 시점이 클래스 배열이 만들어진다 // (생산자 불러오기) // 풀어쓰면 grade[0] = new Grade[]; grade[1] = new Grade[]; grade[2] = new Grade[]; // 이렇게 쓰게된다 void run() { input(); output(); } // 이런식으로 짜야한다 포문안에 input() 쓰는건별로 ////////////////////메소드//////////////////// void input() { } //뉴 클래스 선언 Classname Best = new Classname(); best.input(); ////////////////////while || 응용//////////////////// while(btrue || ff) { // 둘다 만족할떄 빠저나온다 || 붙여서 계속 나올수있다 } ////////////////////상하연산자//////////////////// int res = a > 5 ? 1 : -1 ; //a 가 5보다크면 1 을담고 아니면 - 1 을 담아라 (a > b) ? "a는 b보다 크다" : (a < b) ? "b는 a보다 크다" : "a와 b는 같다." ; (조건식) ? 참 : (조건식) ? 참 : 거짓 ; } } ////////////////////무명클래스//////////////////// interface Show{ public void show(); public void count(); ////이게있을거면 } class <임의이름> implements Show{ public void show();{ } public void count() { } //이런 빈거라도 하나 더필요하다 } ////그후 public static void main(String[]args) {//메인안에서 Show s = new Show() { public void show() { System.out.println("무명클래스 show 실행"); ////즉석으로 실행 을 결정가능 } s.show(); } } } } ////////////////////toString//////////////////// public String toString(){ return"설명하는 설명문입니다"; }
0da41134cc2981c666a98c5476ea08ec9c424fa0
d052793718f235220b53cc57d2049710f3ea7b83
/SiLomba/app/src/main/java/com/example/fandyaditya/silomba/PengaturanTim/RequestCalon/RequestCalonObjek.java
82d077125280a629cba977c5f24f42b578424b34
[]
no_license
irfanhanif/SI-Lomba
962c3cf9767088886a5e080340005853832575e6
2fb0895dc4320a8236b4e332817ddbf78af4eb26
refs/heads/master
2021-01-19T20:02:36.395724
2017-05-25T22:11:02
2017-05-25T22:11:02
88,476,567
1
0
null
null
null
null
UTF-8
Java
false
false
451
java
package com.example.fandyaditya.silomba.PengaturanTim.RequestCalon; /** * Created by Fandy Aditya on 4/24/2017. */ public class RequestCalonObjek { private String idUser; private String nama; public RequestCalonObjek(String idUser, String nama) { this.idUser = idUser; this.nama = nama; } public String getIdUser() { return idUser; } public String getNama() { return nama; } }
e6ee9615633eb66c01013276b78a2ff94b2a72ff
7db7413ea6dac6325b0c4dc0cda6536983d7a915
/OriginalGame/src/finalproject/framework/gameplay/Game.java
d64922c521e8f011abedda475320fcf3ed1e1831
[]
no_license
brandonsbarber/House-Divided
93f62760bf169bfa49becbf94868faf1edec3058
b061b7b6bf2f864aa62fd08b5b11d58bf098257b
refs/heads/master
2021-05-04T11:04:22.580328
2013-03-07T01:12:29
2013-03-07T01:12:29
8,442,181
0
0
null
null
null
null
UTF-8
Java
false
false
23,862
java
/* * Brandon Barber * Gallatin - 2 * 5/23/12 * Game.java * Class that contains all information for gameplay */ package finalproject.framework.gameplay; import finalproject.framework.entity.Building; import finalproject.framework.entity.Entity; import finalproject.framework.entity.EntityType; import finalproject.framework.entity.Unit; import finalproject.gui.Coordinate; import finalproject.gui.Display; import finalproject.gui.Map; import java.util.ArrayList; import java.util.LinkedList; import java.util.Queue; import java.util.TreeMap; import java.util.TreeSet; public class Game { private TreeSet<Unit> playerUnits; private TreeSet<Unit> enemyUnits; private Player player; private int resourceTick; private Queue<Unit> spawn; private long startTime; private long currentSecond; private long money; public static final int RESOURCE_TIME = 5; private TreeSet<Building> coals; private TreeSet<Building> buildings; private TreeSet<Building> enemyBuildings; public static final int MONEY_AMOUNT = 50; public static final int STARTING_AMOUNT = 1500; private Building infSpawn,cavSpawn,artSpawn; private Entity selected; public TreeMap<Integer, ArrayList<Integer>> invalids = new TreeMap<Integer, ArrayList<Integer>>(); private Map map; private boolean starting = true; private Queue<Command> commands; private int cp,maxCP; public static TreeMap<Integer,ArrayList<Integer>> occupied = new TreeMap<Integer,ArrayList<Integer>>(); /** * Constructs a game * @param player player being used * @param m map with terrain */ public Game(Player player, Map m) { commands = new LinkedList<Command>(); playerUnits = new TreeSet<Unit>(); enemyUnits = new TreeSet<Unit>(); coals = new TreeSet<Building>(); this.player = player; startTime = System.currentTimeMillis(); currentSecond = 0; resourceTick = 0; money = STARTING_AMOUNT; commands = new LinkedList<Command>(); spawn = new LinkedList<Unit>(); buildings = new TreeSet<Building>(); enemyBuildings = new TreeSet<Building>(); map = m; for(int x = 0; x < m.getDimension(); x++) { for(int y = 0; y < m.getDimension(); y++) { if(m.getTile(new Coordinate(x,y)) == Map.WATER) { if(!occupied.containsKey(x)) occupied.put(x, new ArrayList<Integer>()); occupied.get(x).add(y); } } } } /** * Updates all units */ public void update() { ArrayList<Entity> dead = new ArrayList<Entity>(); for(Unit u : playerUnits) { if(u.getHealth() <= 0) dead.add(u); } for(Building b : buildings) { if(b.getHealth() <= 0) dead.add(b); } for(Building b : coals) { if(b.getHealth() <= 0) dead.add(b); } for(Entity e : dead) { if(e instanceof Unit) { Unit u = (Unit)e; playerUnits.remove(u); cp -= u.getCP(); } else { Building b = (Building)e; buildings.remove(b); if(b == infSpawn) { boolean found = false; for(Building bl : buildings) { if(bl.getType() == EntityType.CONSCRIPT) { infSpawn = bl; found = true; break; } } if(!found) infSpawn = null; } else if(b == cavSpawn) { boolean found = false; for(Building bl : buildings) { if(bl.getType() == EntityType.STABLES) { cavSpawn = bl; found = true; break; } } if(!found) infSpawn = null; } else if(b == artSpawn) { boolean found = false; for(Building bl : buildings) { if(bl.getType() == EntityType.BLACKSMITH) { artSpawn = bl; found = true; break; } } if(!found) infSpawn = null; } coals.remove(b); for(int x1 = b.getX()/Display.SQUARE_SIZE; x1 < b.getX()/Display.SQUARE_SIZE+b.getWidth()/Display.SQUARE_SIZE; x1 ++ ) { for(int y1 = b.getY()/Display.SQUARE_SIZE; y1 < b.getY()/Display.SQUARE_SIZE+b.getHeight()/Display.SQUARE_SIZE; y1 ++ ) { occupied.get(x1).remove(new Integer(y1)) ; if(occupied.get(x1).isEmpty()) occupied.remove(x1); } } maxCP-=b.getCP(); } } dead.clear(); for(Unit u : enemyUnits) { if(u.getHealth() <= 0) dead.add(u); } for(Building b : enemyBuildings) { if(b.getHealth() <= 0) dead.add(b); } for(Entity e : dead) { if(e instanceof Unit) { Unit u = (Unit)e; enemyUnits.remove(u); } else { Building b = (Building)e; enemyBuildings.remove(b); for(int x1 = b.getX()/Display.SQUARE_SIZE; x1 < b.getX()/Display.SQUARE_SIZE+b.getWidth()/Display.SQUARE_SIZE; x1 ++ ) { for(int y1 = b.getY()/Display.SQUARE_SIZE; y1 < b.getY()/Display.SQUARE_SIZE+b.getHeight()/Display.SQUARE_SIZE; y1 ++ ) { occupied.get(x1).remove(new Integer(y1)) ; if(occupied.get(x1).isEmpty()) occupied.remove(x1); } } } } for(Unit u : playerUnits) { if(u.getHealth() > 0) u.move(currentSecond); } for(Unit u : enemyUnits) { if(u.getHealth() > 0) u.move(currentSecond); } if(hasTimeMoved()) { if(resourceTick == 0) { money += coals.size()*MONEY_AMOUNT; } if(!spawn.isEmpty()) { if(spawn.peek().getSpawnTime() > 0) { spawn.peek().decreaseTime(); } else { Unit u = spawn.remove(); String[] args = {player.toString(),""+u.getX(),""+u.getY()}; sendCommand(new Command(CommandType.SPAWN,u, args)); } } } } /** * Gets the time in seconds * @return time in seconds */ public long getTime() { return (System.currentTimeMillis() - startTime)/1000; } /** * Determines if time has moved in seconds * @return whether time has moved */ public boolean hasTimeMoved() { long currentTime = (System.currentTimeMillis() - startTime)/1000; if(currentTime == currentSecond) { return false; } else { resourceTick++; if(resourceTick == RESOURCE_TIME) { resourceTick = 0; } currentSecond = currentTime; return true; } } /** * Gets the player of the game * @return the player */ public Player getPlayer() { return player; } /** * Gets money held by the player * @return money the player has */ public long getMoney() { return money; } /** * Deducts the given amount of money * @param cost cost of the item */ public void deduct(int cost) { money -= cost; } /** * Returns the number of troops owned by the player * @return number of troops */ public int getNumTroops() { return playerUnits.size(); } /** * Recruits a unit of the given entityType * @param entityType type of unit to be used */ public void recruit(EntityType entityType) { if(entityType.ordinal() <= EntityType.HINF.ordinal()) { spawn.add(new Unit(entityType,infSpawn)); } else if(entityType.ordinal() <= EntityType.HCAV.ordinal()) { spawn.add(new Unit(entityType,cavSpawn)); } else if(entityType.ordinal() <= EntityType.HART.ordinal()) { spawn.add(new Unit(entityType,artSpawn)); } deduct(new Unit(entityType).getPrice()); cp+=(new Unit(entityType)).getCP(); } /** * Gets where infantry spawns * @return where infantry spawns */ public Building getInfSpawn() { return infSpawn; } /** * Gets where artillery spawns * @return where artillery spawns */ public Building getArtSpawn() { return artSpawn; } /** * Gets where cavalry spawns * @return where cavalry spawns */ public Building getCavSpawn() { return cavSpawn; } /** * Prepares command to be sent (adds it to sending queue) * @param c command to be sent */ public void sendCommand(Command c) { commands.add(c); } /** * Retrieves the oldest command to be sent * @return command to be sent */ public Command getCommand() { return commands.remove(); } /** * Returns if there is a command to send * @return if there is a command to send */ public boolean hasCommand() { return commands.size() != 0; } /** * Gets all player owned buildings * @return player-owned buildings */ public TreeSet<Building> getBuildings() { TreeSet<Building> temp = new TreeSet<Building>(); temp.addAll(buildings); temp.addAll(coals); return temp; } /** * Gets all enemy owned buildings * @return enemy-owned buildings */ public TreeSet<Building> getEnemyBuildings() { return enemyBuildings; } /** * Gets all units held by the player * @return units held by the player */ public TreeSet<Unit> getPlayerUnits() { return playerUnits; } /** * Gets all enemy units * @return enemy units */ public TreeSet<Unit> getEnemyUnits() { return enemyUnits; } /** * Gets what type of unit is being spawn * @return type of unit being spawned */ public EntityType getSpawnUnitType() { if(spawn.size() == 0) return null; return spawn.peek().getType(); } /** * Gets the selected entity * @return selected entity */ public Entity getSelected() { return selected; } /** * Gets if the user currently has something selected * @return if the user currently has something selected */ public boolean hasSelected() { return selected != null; } /** * Attempts to select a unit based on x and y position * @param x x-position * @param y y-position */ public void select(int x, int y) { for(Entity unit: playerUnits) { if(unit.getX() <= x && unit.getX()+unit.getWidth() >= x && unit.getY() <= y && unit.getY()+unit.getHeight() >= y) { selected = unit; return; } } for(Entity building : buildings) { if(building.getX() <= x && building.getX()+building.getWidth() >= x && building.getY() <= y && building.getY()+building.getHeight() >= y) { selected = building; return; } } for(Entity building : coals) { if(building.getX() <= x && building.getX()+building.getWidth() >= x && building.getY() <= y && building.getY()+building.getHeight() >= y) { selected = building; return; } } selected = null; } /** * Sets the destination of a selected unit. Sends a command. * @param x new x * @param y new y */ public void setDestination(int x, int y) { if(hasSelected() && selected instanceof Unit) { for(Entity unit: enemyUnits) { if(unit.getX() <= x && unit.getX()+unit.getWidth() >= x && unit.getY() <= y && unit.getY()+unit.getHeight() >= y) { String[] args = {player.toString(),unit.toString()}; Command c = new Command(CommandType.ATTACK,(Unit)selected,args); commands.add(c); return; } } for(Entity building : enemyBuildings) { if(building.getX() <= x && building.getX()+building.getWidth() >= x && building.getY() <= y && building.getY()+building.getHeight() >= y) { String[] args = {player.toString(),building.toString()}; Command c = new Command(CommandType.ATTACK,(Unit)selected,args); commands.add(c); return; } } String[] args = {player.toString(), ""+x,""+y}; Command command = new Command(CommandType.MOVE,(Unit)selected,args); commands.add(command); } } /** * Places a building (if valid) at the given location. Sends a command. * @param t type of building * @param x x-position * @param y y-position * @return whether building will continue or not */ public boolean placeBuilding(EntityType t, int x, int y) { Building b = new Building(t, -1,-1); TreeMap<Integer,ArrayList<Integer>> spawnD; if(getPlayer() == Player.UNION) spawnD = map.getSpawn1(); else spawnD = map.getSpawn2(); for(int x1 = x/Display.SQUARE_SIZE; x1 < x/Display.SQUARE_SIZE+b.getWidth()/Display.SQUARE_SIZE; x1 ++ ) { for(int y1 = y/Display.SQUARE_SIZE; y1 < y/Display.SQUARE_SIZE+b.getHeight()/Display.SQUARE_SIZE; y1 ++ ) { if(occupied.containsKey(x1) && occupied.get(x1).contains(new Integer(y1)) || !spawnD.containsKey(new Integer(x1)) || !spawnD.get(x1).contains(new Integer(y1))) { return true; } } } b.setPosition((x/Display.SQUARE_SIZE)*Display.SQUARE_SIZE,(y/Display.SQUARE_SIZE)*Display.SQUARE_SIZE); for(int x1 = x/Display.SQUARE_SIZE; x1 < x/Display.SQUARE_SIZE+b.getWidth()/Display.SQUARE_SIZE; x1 ++ ) { for(int y1 = y/Display.SQUARE_SIZE; y1 < y/Display.SQUARE_SIZE+b.getHeight()/Display.SQUARE_SIZE; y1 ++ ) { if(!occupied.containsKey(x1)) occupied.put(x1, new ArrayList<Integer>()); occupied.get(x1).add(y1); } } String[] args = {player.toString(),""+x,""+y}; Command c = new Command(CommandType.BUILD, b, args); commands.add(c); return false; } /** * Gets all squares occupied by water or buildings * @return occupied locations */ public TreeMap<Integer,ArrayList<Integer>> getOccupied() { return occupied; } /** * Determines if cursor is over enemy unit * @param x x-position * @param y y-position * @return if cursor is over enemy unit */ public boolean overEnemyUnit(int x, int y) { for(Entity unit: enemyUnits) { if(unit.getX() <= x && unit.getX()+unit.getWidth() >= x && unit.getY() <= y && unit.getY()+unit.getHeight() >= y) { return true; } } for(Entity building : enemyBuildings) { if(building.getX() <= x && building.getX()+building.getWidth() >= x && building.getY() <= y && building.getY()+building.getHeight() >= y) { return true; } } return false; } /** * Determines if cursor is over player unit * @param x x-position * @param y y-position * @return if cursor is over player unit */ public boolean overPlayerUnit(int x, int y) { for(Entity unit: playerUnits) { if(unit.getX() <= x && unit.getX()+unit.getWidth() >= x && unit.getY() <= y && unit.getY()+unit.getHeight() >= y) { return true; } } return false; } /** * Processes a command based on what it contains * @param c command to process */ public void giveCommand(Command c) { if(c.getLabel() == CommandType.SPAWN) { if(c.getPlayer() == player) { playerUnits.add((Unit)c.getEntity()); } else { enemyUnits.add((Unit)c.getEntity()); } } else if(c.getLabel() == CommandType.MOVE) { if(c.getPlayer() == player) { for(Unit u:playerUnits) { if(u.compareTo((Unit)c.getEntity()) == 0) { u.setDestination(Integer.parseInt(c.getArgs()[1]), Integer.parseInt(c.getArgs()[2])); } } } else { for(Unit u:enemyUnits) { if(u.compareTo((Unit)c.getEntity()) == 0) { u.setDestination(Integer.parseInt(c.getArgs()[1]), Integer.parseInt(c.getArgs()[2])); } } } } else if(c.getLabel() == CommandType.BUILD) { Building build = (Building)c.getEntity(); if(c.getPlayer() == player) { deduct(build.getPrice()); maxCP+=build.getCP(); if(build.getType() == EntityType.COAL) { coals.add(build); } else { buildings.add(build); if(build.getType() == EntityType.CONSCRIPT && infSpawn == null) { infSpawn = build; } else if(build.getType() == EntityType.STABLES && cavSpawn == null) { cavSpawn = build; } else if(build.getType() == EntityType.BLACKSMITH && artSpawn == null) { artSpawn = build; } } } else { enemyBuildings.add(build); } } else if(c.getLabel() == CommandType.ATTACK) { Unit unit = (Unit)c.getEntity(); String line = c.getArgs()[1]; EntityType enemyT = EntityType.valueOf(line.substring(0,line.indexOf("_"))); int eCount = Integer.parseInt(line.substring(line.indexOf("_")+1)); if(c.getPlayer() == player) { for(Unit u : playerUnits) { if(u.compareTo(unit) == 0) { if(EntityType.isUnit(enemyT)) { Unit enemy = new Unit(enemyT, eCount); for(Unit e : enemyUnits) { if(e.compareTo(enemy) == 0) { u.setTarget(e); } } } else { Building enemy = new Building(enemyT, eCount); for(Building e : enemyBuildings) { if(e.compareTo(enemy) == 0) { u.setTarget(e); } } } } } } else { for(Unit u : enemyUnits) { if(u.compareTo(unit) == 0) { if(EntityType.isUnit(enemyT)) { Unit enemy = new Unit(enemyT, eCount); for(Unit e : playerUnits) { if(e.compareTo(enemy) == 0) { u.setTarget(e); } } } else { Building enemy = new Building(enemyT, eCount); for(Building e : buildings) { if(e.compareTo(enemy) == 0) { u.setTarget(e); } } for(Building e : coals) { if(e.compareTo(enemy) == 0) { u.setTarget(e); } } } } } } } starting = starting && (getBuildings().isEmpty() || getEnemyBuildings().isEmpty()); } /** * Returns if the game is just beginning (one side at least has not placed buildings) * @return if the game is just beginning */ public boolean isStarting() { return starting; } /** * Maximum amount of CP possible * @return max amount of CP */ public int getMaxCP() { return maxCP; } /** * Gets the current amount of command points used up * @return command points */ public int getCP() { return cp; } }
c53558b523bd4a66e544e6dacf25b14fd2b6ba9f
28b2fad502fbfa5eda3f29c5ec7b6d1c819a65d6
/src/main/java/pe/com/syscenterlife/control/global/PersonaControl.java
4ab542e76ff3cfc3dc912044399031dd2dd05d57
[]
no_license
akzonpunk/SYsVentasj
4bdf0fd371696f9faae996d17e35baaba281557b
670a27d4ff64a97b5678bc32207615bbfb437440
refs/heads/master
2020-04-06T22:24:15.963727
2018-11-19T23:38:45
2018-11-19T23:38:45
157,835,032
0
0
null
null
null
null
UTF-8
Java
false
false
6,769
java
/* * 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 pe.com.syscenterlife.control.global; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.TimeZone; import java.util.logging.Logger; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.view.RedirectView; import pe.com.syscenterlife.modelo.GloPersonas; import pe.com.syscenterlife.servicio.global.PersonaServicioI; /** * * @author LAB_SOFTWARE-DTI */ @Controller public class PersonaControl { @Autowired private MessageSource messageSource; @Autowired PersonaServicioI personaServicioI; Logger logger = Logger.getLogger(PersonaControl.class.getName()); @RequestMapping(value = {"/perMain" }, method = RequestMethod.GET) public ModelAndView inicio(Locale locale, Map<String,Object> model){ String welcome=messageSource.getMessage("welcome.message", new Object[]{"David Mamani"}, locale); List<GloPersonas> lista=personaServicioI.listarEntidad(); model.put("ListaPersona", lista); model.put("message", welcome); model.put("startMeeting", "09:10"); return new ModelAndView("global/persona/mainPersona"); } @RequestMapping(value = {"/pru1" }, method = RequestMethod.GET) public ModelAndView inicioUno(){ return new ModelAndView("global/Prueba2"); } @RequestMapping(value = {"/pru2" }, method = RequestMethod.GET) public ModelAndView inicioDos(){ return new ModelAndView("global/Prueba3"); } @RequestMapping(value = {"/pers" }, method = RequestMethod.GET) public ModelAndView mainPersona(){ return new ModelAndView("global/persona/mainPersona"); } @RequestMapping(value = {"/report" }, method = RequestMethod.GET) public ModelAndView mainPersonaReport(){ return new ModelAndView("global/persona/reporte/reportePersona"); } @RequestMapping(value = {"/elim" }, method = RequestMethod.GET) public ModelAndView eliminarPersona(HttpServletRequest r){ int idEntidad=Integer.parseInt(r.getParameter("id")); personaServicioI.eliminarEntidad(idEntidad); return new ModelAndView(new RedirectView("/perMain")); } @RequestMapping(value = {"/buscar"}, method = RequestMethod.POST) public ModelAndView buscarEntidad(Locale locale, Map<String,Object> model, HttpServletRequest r){ String welcome=messageSource.getMessage("welcome.message", new Object[]{"David Mamani"}, locale); String dato=r.getParameter("dato"); List<GloPersonas> lista=personaServicioI.listarEntidadDato(dato); model.put("ListaPersona", lista); model.put("message", welcome); model.put("startMeeting", "09:10"); return new ModelAndView("global/persona/mainPersona"); } @RequestMapping(value = "/formPersona", method = RequestMethod.GET) public ModelAndView irFormulario(@ModelAttribute("modeloPersona")GloPersonas persona, BindingResult result, Model model){ Map<String,String> genero = new LinkedHashMap<String,String>(); genero.put("F", "Femenino"); genero.put("M", "Masculino"); Map<String,String> idioma = new LinkedHashMap<String,String>(); idioma.put("en", "Ingles"); idioma.put("es", "Español"); model.addAttribute("urlAccion", "guardarPersona"); model.addAttribute("ListGenero", genero); model.addAttribute("ListIdioma", idioma); return new ModelAndView("global/persona/formPersona"); } @RequestMapping(value = "/guardarPersona", method = RequestMethod.POST) public ModelAndView guardarEntidad(@ModelAttribute("modeloPersona")GloPersonas persona, BindingResult result, HttpServletRequest r){ persona.setIdPersona(personaServicioI.idPersonaGenerator().getId()); logger.info("Imprimir ID: "+persona.getIdPersona()); try { personaServicioI.guardarEntidad(persona); return new ModelAndView(new RedirectView("/perMain")); } catch (Exception e) { logger.info("Error Guardar: "+e.getMessage()); return new ModelAndView(new RedirectView("/formPersona")); } } @RequestMapping(value = "/formModifPersona", method = RequestMethod.GET) public ModelAndView irModificarPersona(HttpServletRequest r ){ int id=Integer.parseInt(r.getParameter("id")); GloPersonas entidad=null; entidad=personaServicioI.buscarEntidadId(id); return new ModelAndView("global/persona/formPersona","modeloPersona",entidad); } @RequestMapping(value = "/formModif2Persona", method = RequestMethod.GET) public String irModificar2Persona(HttpServletRequest r, Model model ){ int id=Integer.parseInt(r.getParameter("id")); GloPersonas persona=null; persona=personaServicioI.buscarEntidadId(id); logger.info("Error Fecha Real "+persona.getFechaNacimiento()); Map<String,String> genero = new LinkedHashMap<String,String>(); genero.put("F", "Femenino"); genero.put("M", "Masculino"); Map<String,String> idioma = new LinkedHashMap<String,String>(); idioma.put("en", "Ingles"); idioma.put("es", "Español"); model.addAttribute("modeloPersona", persona); model.addAttribute("ListGenero", genero); model.addAttribute("ListIdioma", idioma); model.addAttribute("urlAccion", "actualizarPersona"); return "global/persona/formPersona"; } @RequestMapping(value = "actualizarPersona", method = RequestMethod.POST) public ModelAndView actualizarPersona(@ModelAttribute("modeloPersona") GloPersonas entidad, BindingResult result, HttpServletRequest r ){ try { personaServicioI.modificarEntidad(entidad); return new ModelAndView(new RedirectView(r.getContextPath()+"/perMain")); } catch (Exception e) { logger.info("Error al modificar: "+e.getMessage()); return new ModelAndView(new RedirectView(r.getContextPath()+"/formModif2Persona?id="+entidad.getIdPersona())); } } }
13734a172c30ef7ef2ef66b4757cdb33353ecd3b
f686d1092c103ac456fb4a8c4edc62826ff2a0bb
/src/test/java/br/com/becommerce/inventory/manager/api/inventoryitem/controller/InventoryItemControllerAcceptanceTest.java
e8a617dafbb05fd62badee3d924a02ada48b4f2c
[]
no_license
rmleme/inventory-manager-api
c482f44f7f84f91e29630fb29f15729d5ec7c554
40a1372e56d740691fbb8b0e36a8d50ef5802b5e
refs/heads/master
2020-04-11T02:54:39.010647
2018-12-12T09:14:40
2018-12-12T09:14:40
161,461,029
0
0
null
null
null
null
UTF-8
Java
false
false
5,797
java
package br.com.becommerce.inventory.manager.api.inventoryitem.controller; import static br.com.becommerce.inventory.manager.api.inventoryitem.model.Constants.AVAILABLE; import static br.com.becommerce.inventory.manager.api.inventoryitem.model.Constants.DESCRIPTION; import static br.com.becommerce.inventory.manager.api.inventoryitem.model.Constants.RESERVED_QUANTITY; import static br.com.becommerce.inventory.manager.api.inventoryitem.model.Constants.SHOE_ID; import static br.com.becommerce.inventory.manager.api.inventoryitem.model.Constants.TOTAL_QUANTITY; import static br.com.becommerce.inventory.manager.api.inventoryitem.model.Constants.URI; import static org.junit.Assert.assertEquals; import java.net.URI; import java.util.List; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest.WebEnvironment; import org.springframework.boot.test.util.TestPropertyValues; import org.springframework.boot.test.web.client.TestRestTemplate; import org.springframework.boot.web.server.LocalServerPort; import org.springframework.context.ApplicationContextInitializer; import org.springframework.context.ConfigurableApplicationContext; import org.springframework.http.HttpEntity; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringRunner; import org.testcontainers.containers.MySQLContainer; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import br.com.becommerce.inventory.manager.api.Application; import br.com.becommerce.inventory.manager.api.inventoryitem.model.InventoryItem; @RunWith(SpringRunner.class) @SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.RANDOM_PORT) @ContextConfiguration(initializers = { InventoryItemControllerAcceptanceTest.Initializer.class }) public class InventoryItemControllerAcceptanceTest { @ClassRule public static MySQLContainer mysql = new MySQLContainer(); private InventoryItem inventoryItem; private HttpHeaders headers; private String serverUrl; @Autowired private ObjectMapper objectMapper; @Autowired private TestRestTemplate restTemplate; @LocalServerPort private int serverPort; @Before public void setUp() throws Exception { inventoryItem = new InventoryItem(); inventoryItem.setShoeId(SHOE_ID); inventoryItem.setDescription(DESCRIPTION); inventoryItem.setTotalQuantity(TOTAL_QUANTITY); inventoryItem.setReservedQuantity(RESERVED_QUANTITY); inventoryItem.setAvailable(AVAILABLE); headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_JSON); serverUrl = "http://localhost:" + serverPort + URI; } @Test public void testCrud() throws Exception { // Create createInventoryItem(); // Retrieve ResponseEntity<String> resultGet = restTemplate.getForEntity(new URI(serverUrl), String.class); List<InventoryItem> inventoryItems = objectMapper.readValue(resultGet.getBody(), new TypeReference<List<InventoryItem>>() { }); assertEquals(HttpStatus.OK.value(), resultGet.getStatusCodeValue()); assertEquals(1, inventoryItems.size()); // Update inventoryItems.get(0).setDescription("anotherDescription"); HttpEntity<InventoryItem> request = new HttpEntity<>(inventoryItems.get(0), headers); ResponseEntity<InventoryItem> resultPut = restTemplate.exchange(serverUrl + "/{id}", HttpMethod.PUT, request, InventoryItem.class, inventoryItems.get(0).getId()); assertEquals(HttpStatus.OK.value(), resultPut.getStatusCodeValue()); assertEquals(inventoryItems.get(0).getDescription(), resultPut.getBody().getDescription()); // Delete ResponseEntity<String> resultDelete = restTemplate.exchange(serverUrl + "/{id}", HttpMethod.DELETE, null, String.class, inventoryItems.get(0).getId()); assertEquals(HttpStatus.NO_CONTENT.value(), resultDelete.getStatusCodeValue()); } @Test public void testRetrieveAllFilteredByShoeId() throws Exception { createInventoryItem(); createInventoryItem(); inventoryItem.setShoeId(SHOE_ID + 1); createInventoryItem(); ResponseEntity<String> resultGet = restTemplate.getForEntity(new URI(serverUrl + "?shoeId=" + SHOE_ID), String.class); List<InventoryItem> inventoryItems = objectMapper.readValue(resultGet.getBody(), new TypeReference<List<InventoryItem>>() { }); assertEquals(HttpStatus.OK.value(), resultGet.getStatusCodeValue()); assertEquals(2, inventoryItems.size()); assertEquals(SHOE_ID, inventoryItems.get(0).getShoeId()); assertEquals(SHOE_ID, inventoryItems.get(1).getShoeId()); } private void createInventoryItem() throws Exception { HttpEntity<InventoryItem> request = new HttpEntity<>(inventoryItem, headers); ResponseEntity<String> resultPost = restTemplate.postForEntity(new URI(serverUrl), request, String.class); assertEquals(HttpStatus.CREATED.value(), resultPost.getStatusCodeValue()); } static class Initializer implements ApplicationContextInitializer<ConfigurableApplicationContext> { public void initialize(ConfigurableApplicationContext configurableApplicationContext) { TestPropertyValues .of("spring.datasource.url=" + mysql.getJdbcUrl(), "spring.datasource.username=" + mysql.getUsername(), "spring.datasource.password=" + mysql.getPassword()) .applyTo(configurableApplicationContext.getEnvironment()); } } }
b23775c961ed52d8dbda5ee7f487a2f603a88cb5
7b0c09d9514443b4927ebf70bbfa0f587788274e
/src/theAntsPowerOf6/model/AntBrain.java
eb85decaf0132e3c9819de3d9d3e03a9785564fe
[]
no_license
delmo/TheAntGame
4af5b24da346a87f85ad220e3df2c75d4d447e93
19767793f8bdca69c6dd98d92685b6ee20c0710f
refs/heads/master
2021-01-22T13:12:17.249195
2013-04-18T12:33:55
2013-04-18T12:33:55
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,885
java
package theAntsPowerOf6.model; import java.io.BufferedReader; import java.io.FileReader; import java.util.ArrayList; import java.util.Arrays; /** * This class is used to hold information about an ant brain. * @author Tristan * @version 0.02 */ public class AntBrain { private String name; public String getName() { return name; } private Action[] states; /** * Constructor which takes String name of an ant brain and String filename. * @param name, instruction * @param file, AntBrain file name */ public AntBrain(String name, String file){ BufferedReader reader = null; ArrayList<Action> actions = new ArrayList<Action>(); this.name = name; try{ reader = new BufferedReader(new FileReader(file)); String line = null; while((line = reader.readLine()) != null){ line = line.split(";")[0]; // remove the comment after ; if(line.length() > 0){ actions.add(new Action(line)); }else{ actions.add(null); } } }catch(Exception e){ //edit this line, check runtime error for reading file System.out.println("File not accessible: " + e.getMessage()); }finally{ try{ if(reader != null){ reader.close(); } }catch(Exception c){ System.out.println("Cannot close the file: " + c.getMessage()); } } //put all actions in states[] int size = actions.size(); states = new Action[size]; for(int i=0; i<size; i++){ states[i] = actions.get(i); } } /** * @return size of states[] */ public int getStateSize(){ return states.length; } /** * @return all remaining states */ public Action[] getStates(){ return this.states; } /** * @return current instruction name; */ public Action getInstruction(int state){ if((state >= this.states.length) || (state < 0)){ return null; }else{ return this.states[state]; } } /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + Arrays.hashCode(states); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (!(obj instanceof AntBrain)) return false; AntBrain other = (AntBrain) obj; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; if (!Arrays.equals(states, other.states)) return false; return true; } /* * Print finite state machine of an ant brain. * (non-Javadoc) * @see java.lang.Object#toString() */ public String toString(){ String print = ""; for(Action action: this.states){ print += action.toString() + "\n"; } return print; } }
48684c8d8f811bd32bc3d06c280555f914eeaf70
09e20b1b01e29daf3aa5ce3bbf19d86dbdf21d97
/test/_6KYU/BuyCarTest.java
3dbc8020b389caba97a4fa5285cf678de0dee4ec
[]
no_license
EkremC/Codewars
893bb65111b40533ddac12e799a69d20c5b43290
3d7c6823f77b7cc80c835aa635e878d06913a5be
refs/heads/master
2021-03-19T11:12:24.724620
2018-06-30T16:26:20
2018-06-30T16:26:20
98,125,978
0
0
null
null
null
null
UTF-8
Java
false
false
482
java
package _6KYU; import _6KYU.BuyCar; import org.junit.Test; import static org.junit.Assert.*; /** * Created by ekremcandemir on 10/07/2017. */ public class BuyCarTest { @Test public void test1() { int[] r = new int[] { 6, 766 }; assertArrayEquals(r, BuyCar.nbMonths(2000, 8000, 1000, 1.5)); } @Test public void test2() { int[] r = new int[] { 0, 4000 }; assertArrayEquals(r, BuyCar.nbMonths(12000, 8000, 1000, 1.5)); } }
331f40bd53ffedabb5573215ca2e85bb52b84cf7
9cfd3232c9d02e9a75c70653195c07dc26183987
/app/src/main/java/org/solovyev/android/calculator/DisplayState.java
2a2297f73adbbd14c492c635be74a8ea044b50c4
[]
no_license
suresh-mahawar/android-calculatorpp
a00fc4c64f32db713c5c2283c0afc6814f531250
13f12d5d140903d7d708eac967c81a5a49a3a06a
refs/heads/master
2022-01-27T15:29:01.552326
2016-02-25T16:45:28
2016-02-25T16:45:28
null
0
0
null
null
null
null
UTF-8
Java
false
false
4,369
java
/* * Copyright 2013 serso aka se.solovyev * * 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. * * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ * Contact details * * Email: [email protected] * Site: http://se.solovyev.org */ package org.solovyev.android.calculator; import android.os.Parcel; import android.os.Parcelable; import android.text.TextUtils; import android.view.ContextMenu; import jscl.math.Generic; import org.json.JSONException; import org.json.JSONObject; import org.solovyev.android.calculator.jscl.JsclOperation; import javax.annotation.Nonnull; import javax.annotation.Nullable; public class DisplayState implements Parcelable, ContextMenu.ContextMenuInfo { public static final Creator<DisplayState> CREATOR = new Creator<DisplayState>() { @Override public DisplayState createFromParcel(Parcel in) { return new DisplayState(in); } @Override public DisplayState[] newArray(int size) { return new DisplayState[size]; } }; private static final String JSON_TEXT = "t"; @Nonnull public final String text; public final boolean valid; public final long sequence; @Nonnull private transient JsclOperation operation = JsclOperation.numeric; @Nullable private transient Generic result; private DisplayState(@Nonnull String text, boolean valid, long sequence) { this.text = text; this.valid = valid; this.sequence = sequence; } DisplayState(@Nonnull JSONObject json) { this(json.optString(JSON_TEXT), true, Calculator.NO_SEQUENCE); } private DisplayState(Parcel in) { text = in.readString(); valid = in.readByte() != 0; sequence = Calculator.NO_SEQUENCE; } @Nonnull public static DisplayState empty() { return new DisplayState("", true, Calculator.NO_SEQUENCE); } @Nonnull public static DisplayState create(@Nonnull JSONObject json) { return new DisplayState(json); } @Nonnull public static DisplayState createError(@Nonnull JsclOperation operation, @Nonnull String errorMessage, long sequence) { final DisplayState state = new DisplayState(errorMessage, false, sequence); state.operation = operation; return state; } @Nonnull public static DisplayState createValid(@Nonnull JsclOperation operation, @Nullable Generic result, @Nonnull String stringResult, long sequence) { final DisplayState state = new DisplayState(stringResult, true, sequence); state.result = result; state.operation = operation; return state; } @Nullable public Generic getResult() { return this.result; } @Nonnull public JsclOperation getOperation() { return this.operation; } public boolean same(@Nonnull DisplayState that) { return TextUtils.equals(text, that.text) && operation == that.operation; } @Nonnull public JSONObject toJson() throws JSONException { final JSONObject json = new JSONObject(); json.put(JSON_TEXT, text); return json; } @Override public String toString() { return "DisplayState{" + "valid=" + valid + ", sequence=" + sequence + ", operation=" + operation + '}'; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(text); dest.writeByte((byte) (valid ? 1 : 0)); } }
87dd173332be55928590c5b4d5a82dd3d3e70a16
51a553448c0fb8b5231b5d7e030392eaf156db32
/TestMerge.java
6a778cdaf2a2e8e03e14a3621e637de347b7548a
[]
no_license
zday294/cps210-lab2
96bf527d016872d78e47aab8b3dfa32877375bd9
371beaa08fc897c38847b87a40a64a0cd97ca40f
refs/heads/master
2020-07-31T02:56:02.948574
2019-09-23T22:03:36
2019-09-23T22:03:36
210,460,072
0
0
null
null
null
null
UTF-8
Java
false
false
1,331
java
public class TestMerge { public static void printArray(Integer [] array, int len) { for (int pos=0; pos < len; ++pos) { System.out.print(" " + array[pos]); } System.out.println(); } public static void main(String[] args) { Integer [] vals = { 20, 17, 14, 11, 8, 5, 2, 1, 4, 7, 10, 13, 16, 19, 0, 3, 6, 9, 12, 15, 18}; Integer [] hold = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; ArrayIter<Integer> valsBegin = new ArrayIter<Integer>(vals); ArrayIter<Integer> tempStorage = new ArrayIter<Integer>(hold); int N; // test length 1 N = 1; System.out.println("Test case length=1"); Mergesort.sort(valsBegin, new ArrayIter<Integer>(vals,N), tempStorage, (a,b)-> (a < b)); printArray(vals, N); // test length 2 N = 2; System.out.println("Test case length=2"); Mergesort.sort(valsBegin, new ArrayIter<Integer>(vals,N), tempStorage, (a,b)-> (a < b)); printArray(vals, N); // test length 3 N = 3; System.out.println("Test case length=3"); Mergesort.sort(valsBegin, new ArrayIter<Integer>(vals,N), tempStorage, (a,b)-> (a < b)); printAr ray(vals, N); // test length 4 N = 21; System.out.println("Test case length=21"); Mergesort.sort(valsBegin, new ArrayIter<Integer>(vals,N), tempStorage, (a,b)-> (a < b)); printArray(vals, N); } }
b24157de0ab2d8194bb249bbf49fa74c6055c861
4300155955dddfd70ffc2445e3c0a550751d71e0
/prueba/app/src/main/java/com/jespalomo/prueba/MainActivity.java
e5359dfd8cada41f77507c442d60eb12866886cd
[]
no_license
jespalomo/AndroidStudioProjects
4d520b94fa143b7f7857b94ffeafc94b767cf230
fb5636395828d818a879ac8c443751834ee32232
refs/heads/main
2023-07-15T15:04:02.252119
2021-09-06T16:14:19
2021-09-06T16:14:19
389,710,766
0
0
null
null
null
null
UTF-8
Java
false
false
9,213
java
package com.jespalomo.prueba; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.text.Html; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.TextView; import android.widget.Toast; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonArrayRequest; import com.android.volley.toolbox.Volley; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.List; public class MainActivity extends AppCompatActivity{ List<Aeropuerto> aeropuertos1=new ArrayList<>(); List<Aeropuerto> aeropuertos2=new ArrayList<>(); private String input1="", input2=""; AutoCompleteTextView c1,c2; Pais pais1 = new Pais(); Pais pais2 = new Pais(); RequestQueue requestQueue; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); String[] countries = getResources().getStringArray(R.array.countries); c1 = (AutoCompleteTextView)findViewById(R.id.pais); ArrayAdapter<String> adapter1 = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, countries); c1.setAdapter(adapter1); c2 = (AutoCompleteTextView)findViewById(R.id.city2); ArrayAdapter<String> adapter2 = new ArrayAdapter<>(this, android.R.layout.simple_dropdown_item_1line, countries); c2.setAdapter(adapter2); c1.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { confirma1(); confirmaAeropuerto1(aeropuertos1); } }); c2.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { confirma2(); confirmaAeropuerto2(aeropuertos2); } }); } public boolean onCreateOptionsMenu(Menu menu){ getMenuInflater().inflate(R.menu.menu, menu); return true; } public boolean onOptionsItemSelected(MenuItem item){ int id= item.getItemId(); if(id == R.id.home){ Intent next = new Intent(this, Seleccion.class); startActivity(next); return true; }else if(id == R.id.clinicas){ Intent next = new Intent(this, CompruebaUbicacion.class); startActivity(next); return true; }else if(id == R.id.planearviaje){ Intent next = new Intent(this, MainActivity.class); startActivity(next); return true; }else if(id == R.id.about){ Intent next = new Intent(this, SobreMi.class); startActivity(next); return true; }return super.onOptionsItemSelected(item); } public void confirma1(){ input1 = c1.getText().toString(); if(!input1.isEmpty()){ consulta("http://192.168.0.43/dev/consultabien.php?nombre="+input1+"",pais1); }else { Toast.makeText(getApplicationContext(),"Introduce pais de origen",Toast.LENGTH_SHORT).show(); } } public void confirma2(){ input2 = c2.getText().toString(); if(!input2.isEmpty()){ consulta("http://192.168.0.43/dev/consultabien.php?nombre="+input2+"", pais2); //Toast.makeText(getApplicationContext(),"Pais de destino: "+ input2,Toast.LENGTH_SHORT).show(); }else { Toast.makeText(getApplicationContext(),"Introduce pais de destino",Toast.LENGTH_SHORT).show(); } } public void confirmaAeropuerto1(List<Aeropuerto> aeropuertos){ input1 = c1.getText().toString(); if(!input1.isEmpty()) { consultaAeropuertos("http://192.168.0.43/dev/consultaaeropuertos.php?pais=" +input1+ "", aeropuertos, pais1); } } public void confirmaAeropuerto2(List<Aeropuerto> aeropuertos){ input2 = c2.getText().toString(); if(!input2.isEmpty()){ consultaAeropuertos("http://192.168.0.43/dev/consultaaeropuertos.php?pais="+input2+ "", aeropuertos, pais2); } } public void confirmaAeropuerto(){ confirmaAeropuerto1(aeropuertos1); confirmaAeropuerto2(aeropuertos2); } //Metodo para descargar datos de la bdd y transferir los datos a la actividad de detalles public void botonSpecs(View view){ if(!input1.isEmpty() && !input2.isEmpty() ){ Intent next = new Intent(this, ListaVuelos.class); next.putExtra("Pais1", pais1); next.putExtra("Pais2", pais2); next.putExtra("Aeropuertos1", (Serializable) aeropuertos1); next.putExtra("Aeropuertos2", (Serializable) aeropuertos2); startActivity(next); }else if(input1.isEmpty()){ Toast.makeText(getApplicationContext(),"Confirma pais de origen",Toast.LENGTH_SHORT).show(); }else{ Toast.makeText(getApplicationContext(),"Confirma pais de destino",Toast.LENGTH_SHORT).show(); } } //Metodo para hacer la consulta a la base de datos de mySQL private void consulta(String URL, Pais p){ JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(URL, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { JSONObject jsonObject = null; for (int i = 0; i < response.length(); i++) { try { jsonObject = response.getJSONObject(i); p.setId(jsonObject.getInt("id")); p.setNombre(codificar(jsonObject.getString("nombre"))); p.setRestricciones(codificar(jsonObject.getString("restricciones"))); p.setLatVertical(jsonObject.getDouble("latVertical")); p.setLatHorizontal(jsonObject.getDouble("latHorizontal")); p.setAlerta(jsonObject.getInt("alerta")); Toast.makeText(getApplicationContext(),"Pais: "+ p.getNombre(),Toast.LENGTH_SHORT).show(); } catch (JSONException e) { Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show(); } } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show(); } } ); requestQueue = Volley.newRequestQueue(this); requestQueue.add(jsonArrayRequest); } private void consultaAeropuertos(String URL, List<Aeropuerto> aeropuertos, Pais p){ JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(URL, new Response.Listener<JSONArray>() { @Override public void onResponse(JSONArray response) { JSONObject jsonObject = null; for (int i = 0; i < response.length(); i++) { try { jsonObject = response.getJSONObject(i); aeropuertos.add(new Aeropuerto(jsonObject.getInt("id"),codificar(jsonObject.getString("nombre")), jsonObject.getDouble("latVertical"), jsonObject.getDouble("latHorizontal"), jsonObject.getString("codigo"), jsonObject.getInt("coeficiente"), jsonObject.getInt("idPais"), p)); Toast.makeText(getApplicationContext(),aeropuertos.get(i).getCodigo(),Toast.LENGTH_SHORT).show(); } catch (JSONException e) { Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_SHORT).show(); } } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show(); } } ); requestQueue = Volley.newRequestQueue(this); requestQueue.add(jsonArrayRequest); } private String codificar(String cadena){ String str = ""; try { str = new String(cadena.getBytes("ISO-8859-1"), "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return Html.fromHtml(str).toString(); } }
f1f79463f4bbcb425cfbd11b95cd87810a59ce56
07aae7efba93ce0ef907d544486def383fd88e29
/src/com/lijiaxing/A/RMB.java
ae2af2a9836dac9fc04f83864be6da922d7f4aa4
[]
no_license
1142862444/RMB
c1046fe748a2a2542d627395c483c6f28c80cad6
e305f8df14489d334d37892bbe6311809d09513a
refs/heads/master
2020-04-04T19:23:02.529753
2018-11-05T11:01:59
2018-11-05T11:01:59
156,203,712
0
0
null
null
null
null
UTF-8
Java
false
false
3,341
java
package com.lijiaxing.A; import java.math.BigDecimal; import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class RMB { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); while (true) { System.out.print("请输入需要转换的数字:"); String i = sc.nextLine(); System.out.println(digitUppercase(i)); } } /** * 处理的最大数字达千万亿位 精确到分 * * @return */ public static String digitUppercase(String num) throws Exception { String fraction[] = {"角", "分"}; String digit[] = {"零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"}; String unit1[] = {"", "拾", "佰", "仟"};//把钱数分成段,每四个一段,实际上得到的是一个二维数组 String unit2[] = {"元", "万", "亿", "万亿"}; //把钱数分成段,每四个一段,实际上得到的是一个二维数组 BigDecimal bigDecimal = new BigDecimal(num); bigDecimal = bigDecimal.multiply(new BigDecimal(100)); // Double bigDecimal = new Double(name*100); 存在精度问题 eg:145296.8 String strVal = String.valueOf(bigDecimal.toBigInteger()); String head = strVal.substring(0, strVal.length() - 2); //整数部分 String end = strVal.substring(strVal.length() - 2); //小数部分 String endMoney = ""; String headMoney = ""; if ("00".equals(end)) { endMoney = "整"; } else { if (!end.substring(0, 1).equals("0")) { endMoney += digit[Integer.valueOf(end.substring(0, 1))] + "角"; } else if (end.substring(0, 1).equals("0") && !end.substring(1, 2).equals("0")) { endMoney += "零"; } if (!end.substring(1, 2).equals("0")) { endMoney += digit[Integer.valueOf(end.substring(1, 2))] + "分"; } } char[] chars = head.toCharArray(); Map<String, Boolean> map = new HashMap<String, Boolean>();//段位置是否已出现zero boolean zeroKeepFlag = false;//0连续出现标志 int vidxtemp = 0; for (int i = 0; i < chars.length; i++) { int idx = (chars.length - 1 - i) % 4;//段内位置 unit1 int vidx = (chars.length - 1 - i) / 4;//段位置 unit2 String s = digit[Integer.valueOf(String.valueOf(chars[i]))]; if (!"零".equals(s)) { headMoney += s + unit1[idx] + unit2[vidx]; zeroKeepFlag = false; } else if (i == chars.length - 1 || map.get("zero" + vidx) != null) { headMoney += ""; } else { headMoney += s; zeroKeepFlag = true; map.put("zero" + vidx, true);//该段位已经出现0; } if (vidxtemp != vidx || i == chars.length - 1) { headMoney = headMoney.replaceAll(unit2[vidx], ""); headMoney += unit2[vidx]; } if (zeroKeepFlag && (chars.length - 1 - i) % 4 == 0) { headMoney = headMoney.replaceAll("零", ""); } } return headMoney + endMoney; } }
b55693a658512fa1a8e5a4cd7fee679cf5ef3eff
9781550f55e49f31705c6885252d1e09cca86d13
/src/java/Exchange/proyecto/persistencia/dao/Encriptacioaes.java
2624b106000021df89299e74349221f87ad0d5db
[]
no_license
camano/exchange
3e0040f57304a1fc3ea1152570e4d2b5e9967001
df1a65555f22a4b587b116528cac2e91b068ade7
refs/heads/master
2021-07-12T04:06:53.445155
2020-10-17T17:43:05
2020-10-17T17:43:05
206,692,968
0
0
null
null
null
null
UTF-8
Java
false
false
2,639
java
/* * 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 Exchange.proyecto.persistencia.dao; import java.io.UnsupportedEncodingException; import java.security.InvalidKeyException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Base64; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.spec.SecretKeySpec; /** * * @author 57313 */ public class Encriptacioaes { private SecretKeySpec crearClave(String clave) throws UnsupportedEncodingException, NoSuchAlgorithmException { byte[] claveEncriptacion = clave.getBytes("UTF-8"); MessageDigest sha = MessageDigest.getInstance("SHA-1"); claveEncriptacion = sha.digest(claveEncriptacion); claveEncriptacion = Arrays.copyOf(claveEncriptacion, 16); SecretKeySpec secretKey = new SecretKeySpec(claveEncriptacion, "AES"); return secretKey; } public String encriptar(String datos, String claveSecreta) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { SecretKeySpec secretKey = this.crearClave(claveSecreta); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] datosEncriptar = datos.getBytes("UTF-8"); byte[] bytesEncriptados = cipher.doFinal(datosEncriptar); String encriptado = Base64.getEncoder().encodeToString(bytesEncriptados); return encriptado; } public String desencriptar(String datosEncriptados, String claveSecreta) throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException { SecretKeySpec secretKey = this.crearClave(claveSecreta); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING"); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] bytesEncriptados = Base64.getDecoder().decode(datosEncriptados); byte[] datosDesencriptados = cipher.doFinal(bytesEncriptados); String datos = new String(datosDesencriptados); return datos; } }
edf684714ecbb7a527df78665e8f8749c9501f92
16d064dbfe80542d9332a99d436b88d60a36cd8c
/app/src/main/java/com/hippoandfriends/helpdiabetes/slider/WeekLabeler.java
e6c18af1d27877e82f6430aeec1adb865321687b
[]
no_license
JohanDegraeve/helpdiabetes-android
e2e5bee9dcc0ab5a7f65a2137b9cdbcbff31d327
a75ac2267e214d066cc79e09919d9d3158a6bf92
refs/heads/master
2021-01-10T16:37:12.549909
2017-06-18T12:53:29
2017-06-18T12:53:29
44,637,522
0
1
null
2017-06-16T20:12:55
2015-10-20T22:03:46
Java
UTF-8
Java
false
false
3,047
java
// Please read info.txt for license and legal information package com.hippoandfriends.helpdiabetes.slider; import java.util.Calendar; import android.content.Context; import android.graphics.Typeface; import android.util.TypedValue; import android.view.Gravity; /** * A customized Labeler that displays weeks using a CustomTimeTextView */ public class WeekLabeler extends Labeler { private final String mFormatString; public WeekLabeler(String formatString) { super(120, 60); mFormatString = formatString; } @Override public TimeObject add(long time, int val) { return timeObjectfromCalendar(Util.addWeeks(time, val)); } /** * We implement this as custom code rather than a method in Util because there * is no format string that shows the week of the year as an integer, so we just * format the week directly rather than extracting it from a Calendar object. */ @Override protected TimeObject timeObjectfromCalendar(Calendar c) { int week = c.get(Calendar.WEEK_OF_YEAR); int day_of_week = c.get(Calendar.DAY_OF_WEEK)-1; // set calendar to first millisecond of the week c.add(Calendar.DAY_OF_MONTH,-day_of_week); c.set(Calendar.HOUR_OF_DAY,0);c.set(Calendar.MINUTE,0);c.set(Calendar.SECOND,0); c.set(Calendar.MILLISECOND, 0); long startTime = c.getTimeInMillis(); // set calendar to last millisecond of the week c.add(Calendar.DAY_OF_WEEK, 6); c.set(Calendar.HOUR_OF_DAY,23);c.set(Calendar.MINUTE,59);c.set(Calendar.SECOND,59); c.set(Calendar.MILLISECOND, 999); long endTime = c.getTimeInMillis(); return new TimeObject(String.format(mFormatString,week), startTime, endTime); } /** * create our customized TimeTextView and return it */ public TimeView createView(Context context, boolean isCenterView) { return new CustomTimeTextView(context, isCenterView, 25); } /** * Here we define our Custom TimeTextView which will display the fonts in its very own way. */ private static class CustomTimeTextView extends TimeTextView { public CustomTimeTextView(Context context, boolean isCenterView, int textSize) { super(context, isCenterView, textSize); } /** * Here we set up the text characteristics for the TextView, i.e. red colour, * serif font and semi-transparent white background for the centerView... and shadow!!! */ @Override protected void setupView(boolean isCenterView, int textSize) { setGravity(Gravity.CENTER); setTextColor(0xFF883333); setTextSize(TypedValue.COMPLEX_UNIT_DIP, textSize); setTypeface(Typeface.SERIF); if (isCenterView) { setTypeface(Typeface.create(Typeface.SERIF, Typeface.BOLD)); setBackgroundColor(0x55FFFFFF); setShadowLayer(2.5f, 3, 3, 0xFF999999); } } } }
9f728ccde82f7c925ce25aaea15923b3d241db6d
d28cba43683811fc632ffc73f9af38e5c5c03a43
/site-templates-search-portlet/docroot/WEB-INF/src/com/websites/dashboard/model/impl/WebSitesDashboardImpl.java
506900e457bc2e4db30a8a59791c52799da6f8bf
[]
no_license
liferaynarena/webEx
ae133cec571ec9b3866cdbe66af3470d311ea13b
5f889c7f93b3294a5c17036207931ba5403cbf19
refs/heads/master
2021-01-01T05:46:05.341077
2016-05-22T14:35:19
2016-05-22T14:38:14
59,417,129
0
0
null
null
null
null
UTF-8
Java
false
false
1,355
java
/** * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved. * * The contents of this file are subject to the terms of the Liferay Enterprise * Subscription License ("License"). You may not use this file except in * compliance with the License. You can obtain a copy of the License by * contacting Liferay, Inc. See the License for the specific language governing * permissions and limitations under the License, including but not limited to * distribution rights of the Software. * * * */ package com.websites.dashboard.model.impl; /** * The extended model implementation for the WebSitesDashboard service. Represents a row in the &quot;websitesdashboard&quot; database table, with each column mapped to a property of this class. * * <p> * Helper methods and all application logic should be put in this class. Whenever methods are added, rerun ServiceBuilder to copy their definitions into the {@link com.websites.dashboard.model.WebSitesDashboard} interface. * </p> * * @author liferay */ public class WebSitesDashboardImpl extends WebSitesDashboardBaseImpl { /* * NOTE FOR DEVELOPERS: * * Never reference this class directly. All methods that expect a web sites dashboard model instance should use the {@link com.websites.dashboard.model.WebSitesDashboard} interface instead. */ public WebSitesDashboardImpl() { } }
[ "liferay@liferay-PC" ]
liferay@liferay-PC
515e0a7c8c316230f0a922d6f13f503cff38c78e
752365da5c4d938e563d336235e630da98378d54
/src/main/java/com/trendyol/shoppingcard/service/CartService.java
7d91abf97970e3dfd365d286f9a8452400f0f2d3
[]
no_license
beyzaekici/shoppingcart
1b9c96db475fa59de11fe1fd307c885757e93cc9
eb7a4fc325dcafc47719a67b67116085fdf80626
refs/heads/master
2022-12-10T19:18:18.631071
2020-09-13T11:05:03
2020-09-13T11:05:03
null
0
0
null
null
null
null
UTF-8
Java
false
false
2,090
java
package com.trendyol.shoppingcard.service; import com.trendyol.shoppingcard.exception.ExceptionFactory; import com.trendyol.shoppingcard.model.Cart; import com.trendyol.shoppingcard.repository.BaseRepository; import com.trendyol.shoppingcard.repository.CartCustomRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Isolation; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import java.util.List; @Service @Transactional(readOnly = true, isolation = Isolation.DEFAULT, propagation = Propagation.REQUIRED) public class CartService { private CartCustomRepository cartCustomRepository; private BaseRepository baseRepository; @Autowired public CartService(CartCustomRepository cartCustomRepository, BaseRepository baseRepository) { this.cartCustomRepository = cartCustomRepository; this.baseRepository = baseRepository; } @Transactional public Cart save(Cart cart) { if (StringUtils.isEmpty(cart.getTitle())) { ExceptionFactory.throwException("Title is required.", HttpStatus.BAD_REQUEST); } return baseRepository.saveOrUpdate(cart); } public Cart get(String cartId) { if (StringUtils.isEmpty(cartId)) { ExceptionFactory.throwException("CartId is required", HttpStatus.BAD_REQUEST); } Cart cart = baseRepository.get(cartId, Cart.class); if (cart == null) { ExceptionFactory.throwException("Cart not found.", HttpStatus.NOT_FOUND); } return cart; } public List<String> listCategoriesOfCart(String cartId) { if (StringUtils.isEmpty(cartId)) { ExceptionFactory.throwException("CartId is required", HttpStatus.BAD_REQUEST); } return cartCustomRepository.listCategoriesOfCart(cartId); } }
a616eca5823af610e66b9fd417ed5ef01370cf4a
2c2f6082fc3af49f66cee39f4863abc7a17f7879
/app/src/androidTest/java/androiddive/timothy/dive/ApplicationTest.java
4b060d19a7ec2690bfb98a08e863c3641ee1f7a8
[]
no_license
tim-hoff/Dive
3f7e4fa88914b4c1ca1e34e8a060dcbd37bee94d
ea82aaf93d20e3d16186b6f99f682bb807314086
refs/heads/master
2016-09-06T05:09:17.553707
2014-11-10T17:35:25
2014-11-10T17:35:25
null
0
0
null
null
null
null
UTF-8
Java
false
false
355
java
package androiddive.timothy.dive; import android.app.Application; import android.test.ApplicationTestCase; /** * <a href="http://d.android.com/tools/testing/testing_android.html">Testing Fundamentals</a> */ public class ApplicationTest extends ApplicationTestCase<Application> { public ApplicationTest() { super(Application.class); } }
fa82e447a810d28414549acc5f41fb47869b17a8
cc716354af2bdee913dca383af6950cdd0ec3717
/src/net/byteplex/ByteplexCore/commands/MenuCommand.java
8859d48b56053e4a90d393a7ea423d9fb714d70b
[]
no_license
ckhawks/ByteplexCore
b4d7b72ada84d7125e9ce57fc853bf525d6b8356
353d7c3e0fa107aed3a11d4765d5289b11b19345
refs/heads/master
2021-04-03T08:24:59.192472
2018-03-26T15:05:42
2018-03-26T15:05:42
124,406,164
0
0
null
null
null
null
UTF-8
Java
false
false
2,598
java
package net.byteplex.ByteplexCore.commands; import net.byteplex.ByteplexCore.ByteplexCore; import net.byteplex.ByteplexCore.util.ChatFormat; import net.byteplex.ByteplexCore.util.ChatLevel; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.Material; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; import org.bukkit.event.Listener; import org.bukkit.event.inventory.InventoryClickEvent; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; public class MenuCommand extends BaseCommand implements Listener { Inventory myInventory; public MenuCommand(String name) { super(name); Bukkit.getServer().getPluginManager().registerEvents(this, ByteplexCore.getPlugin(ByteplexCore.class)); initInventory(); } @Override public boolean execute(CommandSender sender, String label, String[] args) { if (sender instanceof Player) { Player player = (Player) sender; player.openInventory(myInventory); } return true; } // custom inventory for custom inventory interaction menu prototype public void initInventory() { myInventory = Bukkit.createInventory(null, 9, "Interaction Menu"); myInventory.setItem(0, new ItemStack(Material.DIRT, 1)); myInventory.setItem(8, new ItemStack(Material.COOKIE, 1)); } // event listener for custom inventory interaction menu prototype @EventHandler public void onInventoryClick(InventoryClickEvent event) { Player player = (Player) event.getWhoClicked(); ItemStack clicked = event.getCurrentItem(); Inventory inventory = event.getInventory(); if (inventory.getName().equals(myInventory.getName())) { if (clicked.getType() == Material.COOKIE) { event.setCancelled(true); player.closeInventory(); player.getInventory().addItem(new ItemStack(Material.COOKIE, 1)); player.sendMessage(ChatFormat.formatExclaim(ChatLevel.INFO, ChatColor.YELLOW + "You get a cookie!")); } else if (clicked.getType() == Material.DIRT) { event.setCancelled(true); player.closeInventory(); player.getInventory().addItem(new ItemStack(Material.DIAMOND, 1)); player.sendMessage(ChatFormat.formatExclaim(ChatLevel.INFO, ChatColor.BLUE + "You found the secret button, " + ChatColor.RED + player.getName() + ChatColor.BLUE + "!")); } } } }
58b69019ca4a818d11a32f8a9571bbdf80880f16
c827bfebbde82906e6b14a3f77d8f17830ea35da
/Development3.0/TeevraServer/extensions/generic/message/commons/src/main/java/com/headstrong/fusion/services/message/commons/adapter/mapper/config/SwitchCaseStatement.java
655f8f10a475a3806b134637be05411664847131
[]
no_license
GiovanniPucariello/TeevraCore
13ccf7995c116267de5c403b962f1dc524ac1af7
9d755cc9ca91fb3ebc5b227d9de6bcf98a02c7b7
refs/heads/master
2021-05-29T18:12:29.174279
2013-04-22T07:44:28
2013-04-22T07:44:28
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,714
java
/* * The information in this document is subject to change without notice and * does not represent a commitment by Headstrong Corporation. The software * and/or databases described in this document are furnished under a license * agreement and may be used or copied only in accordance with the terms of * the agreement. * * Copyright © 2008 Headstrong Corporation * All rights reserved. * * $Id: SwitchCaseStatement.java * $Revision: * $Author: ssoni * $DateTime: Jun 11, 2009 */ package com.headstrong.fusion.services.message.commons.adapter.mapper.config; import java.util.List; import java.util.Map; import com.headstrong.fusion.commons.expression.evaluator.Expression; /** * Conditional Euronext Adapter Statement. */ public class SwitchCaseStatement implements Statement { /** * Expressions to be evaluated. */ private Expression expression; /** * A Map of expression values v/s the mapping to be assigned. */ private Map<String, List<Statement>> cases; /** * Switch Type. defaults to Default. */ private SwitchType type = SwitchType.Default; /** * @return the expression */ public Expression getExpression() { return expression; } /** * @param expression * the expression to set */ public void setExpression(Expression expression) { this.expression = expression; } /** * @return the type */ public SwitchType getType() { return type; } /** * @param type * the type to set */ public void setType(SwitchType type) { this.type = type; } public Map<String, List<Statement>> getCases() { return cases; } public void setCases(Map<String, List<Statement>> cases) { this.cases = cases; } }
e5fffb1811d5265c65a908eb637f49145ee0617c
23d4d25ae5fef08e8c4d0fc07d179b650c04320d
/src/_08_duotai/Test2.java
c1c7db21c647c32a0a0400d2539efa96458b282f
[]
no_license
LiuMei1/jave-Study
1d08b7824001ddf629341da137ee048a5532d9d0
772aa6b0ef9ec793301fa83bad1993b2b0f19c29
refs/heads/master
2020-12-31T00:09:55.455723
2017-04-07T15:55:58
2017-04-07T15:55:58
86,560,177
2
0
null
null
null
null
GB18030
Java
false
false
655
java
package _08_duotai; public class Test2 { /* * 基础班学生:学习、睡觉 * 高级版学生:学习、睡觉 * * 可以将这两类事物进行抽取。 */ public static void main(String[] args) { // BaseStudent bs = new BaseStudent() ; // bs.sleep(); // bs.study(); // AdvStudent as = new AdvStudent() ; // as.sleep(); // as.study(); DoStudent ds = new DoStudent() ; ds.doSome(new AdvStudent() ); ds.doSome(new BaseStudent() ); // MainBoard mb = new MainBoard() ; mb.run(); mb.usePCI(null); mb.usePCI(new NetCard()); //接口型引用指向自己的子类对象 } }
[ "LiuMei@CN-20161017GBEX" ]
LiuMei@CN-20161017GBEX
4498fc494cc702a2f5feea17e89657a71be9f7fa
ca928c6a038a4ca3cbe30a1e9b39df7fd11827b4
/user-service/src/main/java/com/cg/app/service/UserService.java
920f51a667eec0950dd2d82392fe080dc01afe2f
[]
no_license
123Ammar/Microservice-demo
c0cb589c9b556173c9065c735fd7388e05a47662
55e7c3b1eff38b53760409f77c7c77b8fad7ad0a
refs/heads/master
2021-08-22T20:12:35.216409
2018-09-26T05:28:18
2018-09-26T05:28:18
136,433,265
0
1
null
null
null
null
UTF-8
Java
false
false
88
java
package com.cg.app.service; public interface UserService{ String getProductList(); }
b8a1901888cffbe43d8542414021ce62b0e6eb5d
4cd6362aac7256a83a1f438058db6a5df2f03326
/Side-by-Side-Deployment/Camera/src/aug/bueno/Configuration.java
c251fdd5745b5f930983066f50862c3fae882207
[ "Apache-2.0" ]
permissive
Augusto11CB/JVM-Custom-ClassLoader
57e6e53d765751ef4f83be5230a93a92eeacd9bb
4fa76805509ea300cbed952ca482521189574d89
refs/heads/master
2023-07-12T01:28:01.489688
2020-07-10T23:35:27
2020-07-10T23:35:27
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,054
java
package aug.bueno; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.FileSystems; import java.nio.file.Files; import java.nio.file.Path; public class Configuration { public static Configuration loadConfiguration(String fileName) throws IOException { Path path = FileSystems.getDefault().getPath(fileName); String contents = new String(Files.readAllBytes(path), StandardCharsets.UTF_8); ObjectMapper mapper = new ObjectMapper(); Configuration config = mapper.readValue(contents, Configuration.class); return config; } private String factoryType; private String location; public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } public String getFactoryType() { return factoryType; } public void setFactoryType(String factoryType) { this.factoryType = factoryType; } }
b5abd4019a2e8dd4962680d6b28677ba31991985
d8b5352145006cb984b3ba093a89648fcc8dd654
/SOS_dp.java
27289cd5fc2d00d4e21c738a37f1a1467e235988
[]
no_license
amanCoder110599/Competitive-Programming
64afd0055bc278d8a7ec4ef5aac9c0962badc9d7
440a63a35a90496b310f1c2d81664d10af940b7e
refs/heads/master
2021-10-30T15:09:50.786319
2021-10-02T14:24:27
2021-10-02T14:24:27
211,046,244
0
1
null
2020-04-27T19:37:42
2019-09-26T09:02:48
Java
UTF-8
Java
false
false
305
java
long[] dp = new long[1 << n]; for(i = 0; i < (1 << n); ++i) dp[i] = A[i]; for(i = 0; i < n; ++i){ for(int mask = 0; mask < (1 << n); ++mask){ if((mask & (1<<i)) > 0) dp[mask] += dp[mask^(1<<i)]; //reverse the transitions if submasks are required instead of supermasks } }
95e0ed57cabc6efbd9c62db1e67c1d637d7ce6dd
6b129f6f66ff04570a54d01a69c2708728c79d73
/restygwt/src/main/java/org/fusesource/restygwt/client/REST.java
7564d201d9ecb4d648a2183e964116d4eb9fac42
[ "Apache-2.0" ]
permissive
platformlayer/resty-gwt
1095ea499ceee88f9c8616a2946696d85aa81be6
b9b1d4c60125883fd094bca96f92f80530d00fc0
refs/heads/master
2021-01-15T20:38:00.702355
2012-09-20T09:06:08
2012-09-20T09:06:08
null
0
0
null
null
null
null
UTF-8
Java
false
false
1,390
java
/** * Copyright (C) 2009-2011 the original author or authors. * See the notice.md file distributed with this work for additional * information regarding copyright ownership. * * 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 org.fusesource.restygwt.client; import org.fusesource.restygwt.client.callback.CallbackAware; /** * @author <a href="mailto:[email protected]">Bogdan Mustiata</<a> * @param <T> * @param <R> */ public class REST<T, R> { private MethodCallback<R> callback; public REST(MethodCallback<R> callback) { this.callback = callback; } public static <T, R> REST<T, R> withCallback(MethodCallback<R> callback) { return new REST<T, R>(callback); } public final <T extends DirectRestService> T call(T service) { ((CallbackAware)service).setCallback(callback); return service; } }
956dc04c3bda773a131dd6c91eadf5cdd94d6df1
41029dc7c76c617ac2ca0600aedef284acf71d58
/src/main/java/com/mj/example/repository/UserRepository.java
ed6d14061ed4b27a9bf731ace4940d94c60842fe
[]
no_license
mrujoshi/SpringBoot_example
07cd414cc468308a82441f220197321a0d600902
3547d62634c99463657d5fc4de9972c068c7915f
refs/heads/master
2022-04-28T03:14:25.034055
2022-04-14T06:55:51
2022-04-14T06:55:51
167,000,582
0
0
null
null
null
null
UTF-8
Java
false
false
233
java
package com.mj.example.repository; import org.springframework.data.repository.PagingAndSortingRepository; import com.mj.example.model.AppUser; public interface UserRepository extends PagingAndSortingRepository<AppUser,Long> { }
c7a2d705fa6396fc19c456d50d3d07abf52d906a
c56cbc159b39a1c4a1c53322ee1379137587531d
/src/com/BasicJava/SingleDimensionalArray.java
60a649a770bc3208e64c3085e84643296802d9d5
[]
no_license
Madhu-3167/MadhuBade
4afdec23cffb6797b639561ec5a007d9ff8ebcde
9155781e79a91071f2403a967e44742c20f9b993
refs/heads/master
2020-07-02T18:23:26.917648
2019-08-10T12:26:21
2019-08-10T12:26:21
201,620,689
0
0
null
null
null
null
UTF-8
Java
false
false
834
java
package com.BasicJava; public class SingleDimensionalArray { public static void main(String[] args) { // An array is used to store multiple values // An array Size is always fixed / constant / static // An array can store only similar dataType value // An array cannot have more values than the size declared // An array index always starts with 0 // dataType arrayName[] = new dataType[size] double array1[] = new double[4]; array1[0] = 10.1; array1[1] = 20.2; array1[2] = 30.3; array1[3] = 40.4; /*System.out.println(array1[0]); System.out.println(array1[1]); System.out.println(array1[2]);*/ // System.out.println(array1[3]); //for(int i=0;i<3;i++) for(int i=0;i<array1.length;i++) // length method finds the size of the array { System.out.println(array1[i]); } } }
5c3af3f6a91c7847eeaf48c087f9048ad854a38c
43507f48c54536f511707883ff4e30e0e3de8a1e
/lab5/src/gui/NewCircleDialog.java
753a1e2ed63355e39bb1d0d730198f0ced63fc99
[]
no_license
CG2016/Avdoshko_1
253d374403692286489fa2fc21c5f4b5502fef3a
a59527f80331d4d5da59debd20c2c78b5562fbe5
refs/heads/master
2021-01-17T14:09:55.850556
2016-05-23T11:50:21
2016-05-23T11:50:21
52,275,524
0
1
null
null
null
null
UTF-8
Java
false
false
2,064
java
package gui; import rasterizer.line.LineRasterizer; import rasterizer.line.RasterizeMethod; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.WindowEvent; /** * Created by Evgeny on 24.04.2016. */ public class NewCircleDialog extends JDialog { private Point center; private int radius; public Point getCenter() { return center; } public int getRadius() { return radius; } public NewCircleDialog(Frame owner, boolean modal) { super(owner, modal); JPanel panel = new JPanel(); JPanel panelPointCenter = new JPanel(); JPanel panelRadius = new JPanel(); panel.setSize(this.getWidth(), this.getHeight()); panel.setLayout(new GridLayout(0, 1)); panelPointCenter.setLayout(new GridLayout(0, 3)); panelRadius.setLayout(new GridLayout(0, 2)); JTextField centerPointX = new JTextField(); JTextField centerPointY = new JTextField(); JTextField radiusField = new JTextField(); JButton submit = new JButton("Submit"); submit.addActionListener(new StubActionListener(this) { @Override public void actionPerformed(ActionEvent e) { try { center = new Point(Integer.parseInt(centerPointX.getText()), Integer.parseInt(centerPointY.getText())); radius = Integer.parseInt(radiusField.getText()); dialog.dispatchEvent(new WindowEvent(dialog, WindowEvent.WINDOW_CLOSING)); } catch(Exception ex) { } } }); panelPointCenter.add(new Label("Center point:")); panelPointCenter.add(centerPointX); panelPointCenter.add(centerPointY); panelRadius.add(new Label("Radius:")); panelRadius.add(radiusField); panel.add(panelPointCenter); panel.add(panelRadius); panel.add(submit); add(panel); } }
1539a96890d176d52d94674e64f789dea0ae0654
6c63a413029a1b135f4f7d57a7181634d7957a2b
/src/main/java/com/rabobank/services/impl/StatementProcessorServiceImpl.java
e6c3e59473fd0d5c7b6823228dd3b6223325d75d
[]
no_license
ionicappworld/updatedProjectTuesday
8b26df7f643b87cafc09d2103ef5a507d9aa1e08
e3ec74d52cadec26d537ff7a8ac08e3e67c323fc
refs/heads/master
2020-05-14T07:50:50.497567
2019-04-17T05:57:03
2019-04-17T05:57:03
181,713,359
0
0
null
null
null
null
UTF-8
Java
false
false
1,571
java
package com.rabobank.services.impl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.multipart.MultipartFile; import com.rabobank.controller.StatementController; import com.rabobank.domain.CustomerStatements; import com.rabobank.domain.Records; import com.rabobank.factory.StatementFactory; import com.rabobank.repository.CustomerStatementsRepository; import com.rabobank.services.ValidationService; import com.rabobank.services.StatementProcessorService; @Service public class StatementProcessorServiceImpl implements StatementProcessorService { private static final Logger logger = LoggerFactory.getLogger(StatementController.class); @Autowired StatementFactory statementFactory; @Autowired ValidationService validationService; @Autowired CustomerStatementsRepository customerStatementsRepository; @Override public void process(MultipartFile file) { try { Records statements = (Records) statementFactory.getFileReader(file).readStatement(file); statements.getRecords().parallelStream().forEach(record -> { validationService.validateEndBalance(record); validationService.validateDuplicate(record); CustomerStatements statments = new CustomerStatements(); BeanUtils.copyProperties(record, statments); customerStatementsRepository.save(statments); }); } catch (Exception e) { logger.error(e.getMessage()); } } }
51e32b80a1d0ec538b00424f34e90aa2f715644f
ed2a35e7bafaf1eccd1e84641d1e8b6e0ec49ad6
/src/main/java/org/pfaa/chemica/model/ConditionProperties.java
54cef05ed6c5963dbc7962c18e6e4af79d5e8c01
[ "Artistic-2.0" ]
permissive
mymagadsl/PerFabricaAdAstra
7a27632c7b2d9d93ccac62a7a33b8b2446f71a5a
1a3126ca1233a6fe2dc6040d85f79de6d743eb62
refs/heads/master
2020-12-31T02:50:15.573003
2015-09-26T14:13:09
2015-09-26T14:13:09
48,414,350
0
0
null
2015-12-22T06:21:20
2015-12-22T06:21:20
null
UTF-8
Java
false
false
1,586
java
package org.pfaa.chemica.model; import java.awt.Color; public class ConditionProperties { public final State state; public final Color color; public final double density; public final Hazard hazard; public final double viscosity; public final int luminosity; public final boolean opaque; // FIXME: can't we just use the color alpha for this? public ConditionProperties(StateProperties properties, Condition condition) { this(properties.getPhase(), properties.getColor(condition.temperature), properties.getDensity(condition), properties.getHazard(), properties.getViscosity(condition.temperature), properties.getLuminosity(condition.temperature), properties.getOpaque()); } public ConditionProperties(State phase, Color color, double density, Hazard hazard, double viscosity, int luminosity, boolean opaque) { super(); this.state = phase; this.color = color; this.hazard = hazard; this.density = density; this.viscosity = viscosity; this.luminosity = luminosity; this.opaque = opaque; } public ConditionProperties(State phase, Color color, double density, Hazard hazard) { this(phase, color, density, hazard, phase == State.SOLID ? Double.POSITIVE_INFINITY : Double.NaN, 0, false); } private ConditionProperties(ConditionProperties props, Color overrideColor) { this(props.state, overrideColor, props.density, props.hazard, props.viscosity, props.luminosity, props.opaque); } public ConditionProperties recolor(Color overrideColor) { return new ConditionProperties(this, overrideColor); } }
b5e5be9047e97e559efd9f142eccd95c217965b8
2773ab13817b0cb2ae2191a25a1e106a7e8bab93
/BitcoinSpinner/src/com/miracleas/bitcoin_spinner/SettingsActivity.java
3304e4556b49b8fcf2d17a108926d9096824d99e
[]
no_license
jackba/bitcoinspinner
99bae3e519484d7da5efc04bef31a9103f8e3415
1fc2f8a217daf93972a5982d9135d4949e8e08f8
refs/heads/master
2020-06-05T11:55:29.302700
2013-12-16T10:39:51
2013-12-16T10:39:51
35,721,302
0
0
null
null
null
null
UTF-8
Java
false
false
15,495
java
package com.miracleas.bitcoin_spinner; import java.util.Locale; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Configuration; import android.graphics.Bitmap; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.preference.EditTextPreference; import android.preference.ListPreference; import android.preference.Preference; import android.preference.Preference.OnPreferenceChangeListener; import android.preference.Preference.OnPreferenceClickListener; import android.preference.PreferenceActivity; import android.text.ClipboardManager; import android.view.View; import android.view.View.OnClickListener; import android.widget.RadioButton; import android.widget.Toast; import com.bccapi.bitlib.crypto.KeyExporter; import com.bccapi.bitlib.crypto.PrivateKeyRing; import com.bccapi.bitlib.crypto.PublicKey; import com.bccapi.bitlib.model.Address; import com.bccapi.bitlib.model.NetworkParameters; import com.bccapi.bitlib.util.Base58; import com.bccapi.ng.api.Balance; public class SettingsActivity extends PreferenceActivity { private SharedPreferences preferences; private SharedPreferences.Editor editor; private static final int REQUEST_CODE_SCAN = 0; private Context mContext; private Preference backupWalletPref; private Preference restoreWalletPref; private Preference exportPrivateKeyPref; private Preference clearPinPref; private Preference setPinPref; private EditTextPreference transactionHistorySizePref; private ListPreference useLocalePref; private ListPreference usedCurrencyPref; private ProgressDialog restoreDialog; /** * @see android.app.Activity#onCreate(Bundle) */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (!SpinnerContext.isInitialized()) { SpinnerContext.initialize(this, getWindowManager().getDefaultDisplay()); } preferences = getSharedPreferences(Consts.PREFS_NAME, Activity.MODE_PRIVATE); editor = preferences.edit(); mContext = this; addPreferencesFromResource(R.xml.preferences); useLocalePref = (ListPreference) findPreference("useLocale"); useLocalePref.setTitle(R.string.prefs_choose_default_locale); useLocalePref.setOnPreferenceChangeListener(useLocalChangeListener); usedCurrencyPref = (ListPreference) findPreference("usedCurrency"); String localCurrency = preferences.getString(Consts.LOCAL_CURRENCY, Consts.DEFAULT_CURRENCY); usedCurrencyPref.setValue(localCurrency); usedCurrencyPref.setTitle(R.string.prefs_currency); usedCurrencyPref.setOnPreferenceChangeListener(usedCurrency); transactionHistorySizePref = (EditTextPreference) findPreference("transactionHistorySize"); int transactionSize = preferences.getInt(Consts.TRANSACTION_HISTORY_SIZE, Consts.DEFAULT_TRANSACTION_HISTORY_SIZE); transactionHistorySizePref.setText(String.valueOf(transactionSize)); transactionHistorySizePref.setOnPreferenceChangeListener(TransactionHistorySizeChangeListener); backupWalletPref = (Preference) findPreference("backupSeed"); backupWalletPref.setOnPreferenceClickListener(backupWalletClickListener); restoreWalletPref = (Preference) findPreference("restoreSeed"); restoreWalletPref.setOnPreferenceClickListener(restoreWalletClickListener); exportPrivateKeyPref = (Preference) findPreference("exportPrivateKey"); exportPrivateKeyPref.setOnPreferenceClickListener(exportPrivateKeyClickListener); setPinPref = (Preference) findPreference("setPin"); setPinPref.setOnPreferenceClickListener(setPinClickListener); clearPinPref = (Preference) findPreference("clearPin"); clearPinPref.setOnPreferenceClickListener(clearPinClickListener); } @Override public void onResume() { super.onResume(); if (!preferences.getString(Consts.LOCALE, "").matches("")) { Locale locale = new Locale(preferences.getString(Consts.LOCALE, "en")); Locale.setDefault(locale); Configuration config = new Configuration(); config.locale = locale; getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics()); } } private final OnPreferenceChangeListener useLocalChangeListener = new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { editor.putString(Consts.LOCALE, (String) newValue); editor.commit(); return true; } }; private final OnPreferenceChangeListener usedCurrency = new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { editor.putString(Consts.LOCAL_CURRENCY, (String) newValue); editor.commit(); return true; } }; private final OnPreferenceChangeListener TransactionHistorySizeChangeListener = new OnPreferenceChangeListener() { @Override public boolean onPreferenceChange(Preference preference, Object newValue) { try { int newSize = Integer.parseInt((String) newValue); if (newSize < 1) { newSize = Consts.DEFAULT_TRANSACTION_HISTORY_SIZE; } editor.putInt(Consts.TRANSACTION_HISTORY_SIZE, newSize); editor.commit(); } catch (NumberFormatException e) { Toast.makeText(mContext, R.string.invalid_value, Toast.LENGTH_SHORT).show(); } return true; } }; private final OnPreferenceClickListener backupWalletClickListener = new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { Utils.runPinProtectedFunction(mContext, new Runnable() { @Override public void run() { backupWallet(); } }); return true; } }; private void backupWallet() { AlertDialog.Builder builder = new AlertDialog.Builder(mContext); builder.setMessage(R.string.backup_dialog_text).setCancelable(false) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); NetworkParameters net = SpinnerContext.getInstance().getNetwork(); final BackupInfo info = new BackupInfo(Utils.readSeed(SpinnerContext.getInstance().getApplicationContext(), net), net); info.getBackupUrl(); Bitmap qrCode = Utils.getLargeQRCodeBitmap(info.getBackupUrl()); Utils.showQrCode(mContext, R.string.bitcoinspinner_backup, qrCode, info.getBackupUrl()); } }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // do nothing } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } private final OnPreferenceClickListener restoreWalletClickListener = new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { Balance balance = SpinnerContext.getInstance().getAsyncApi().getCachedBalance(); if (balance != null && balance.unspent + balance.pendingChange > 0) { AlertDialog.Builder builder = new AlertDialog.Builder(mContext); builder.setMessage(R.string.restore_dialog_coins).setCancelable(false) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); ShowRestoreWalletAlert(); } }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } else { ShowRestoreWalletAlert(); } return true; } }; private void ShowRestoreWalletAlert() { final Activity myself = this; final Dialog dialog = new Dialog(mContext); dialog.setTitle(R.string.restore_method); dialog.setContentView(R.layout.dialog_restore_method); dialog.findViewById(R.id.btn_ok).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { RadioButton rbQrCode = (RadioButton) dialog.findViewById(R.id.rb_qr_code); if (rbQrCode.isChecked()) { Utils.startScannerActivity(myself, REQUEST_CODE_SCAN); } else { ClipboardManager clipboard = (ClipboardManager) mContext.getSystemService(Context.CLIPBOARD_SERVICE); String backupCode = ""; if (clipboard.hasText()) { backupCode = clipboard.getText().toString().trim(); } doRestore(backupCode); } dialog.dismiss(); } }); dialog.findViewById(R.id.btn_cancel).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { dialog.dismiss(); } }); dialog.show(); } private final OnPreferenceClickListener exportPrivateKeyClickListener = new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { Utils.runPinProtectedFunction(mContext, new Runnable() { @Override public void run() { exportPrivateKey(); } }); return true; } }; private void exportPrivateKey() { AlertDialog.Builder builder = new AlertDialog.Builder(mContext); builder.setMessage(R.string.export_private_key_dialog_text).setCancelable(false) .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); NetworkParameters network = SpinnerContext.getInstance().getNetwork(); PrivateKeyRing keyRing = SpinnerContext.getInstance().getPrivateKeyRing(); // Get the single bitcoin address that BitcoinSpinner uses Address address = SpinnerContext.getInstance().getAsyncApi().getPrimaryBitcoinAddress(); // Locate the corresponding public key PublicKey publicKey = keyRing.findPublicKeyByAddress(address); // Get the key exporter from the public key reference KeyExporter exporter = keyRing.findKeyExporterByPublicKey(publicKey); // Export the private key String exportedPrivateKey = exporter.getBase58EncodedPrivateKey(network); // Turn it into a QR code Bitmap qrCode = Utils.getLargeQRCodeBitmap(exportedPrivateKey); // Show Utils.showQrCode(mContext, R.string.private_key, qrCode, exportedPrivateKey); } }).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } private final OnPreferenceClickListener setPinClickListener = new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { Utils.runPinProtectedFunction(mContext, new Runnable() { @Override public void run() { setPin(); } }); return true; } }; private void setPin() { Dialog d = new PinDialog(mContext, false, new PinDialog.OnPinEntered() { private String newPin = null; @Override public void pinEntered(PinDialog dialog, String pin) { if (newPin == null) { newPin = pin; dialog.setTitle(R.string.pin_confirm_pin); } else if (newPin.equals(pin)) { SpinnerContext.getInstance().setPin(pin); Toast.makeText(mContext, R.string.pin_set, Toast.LENGTH_LONG).show(); dialog.dismiss(); } else { Toast.makeText(mContext, R.string.pin_codes_dont_match, Toast.LENGTH_LONG).show(); dialog.dismiss(); } } }); d.setTitle(R.string.pin_enter_new_pin); d.show(); } private final OnPreferenceClickListener clearPinClickListener = new OnPreferenceClickListener() { public boolean onPreferenceClick(Preference preference) { Utils.runPinProtectedFunction(mContext, new Runnable() { @Override public void run() { SpinnerContext.getInstance().setPin(""); Toast.makeText(mContext, R.string.pin_cleared, Toast.LENGTH_LONG).show(); } }); return true; } }; @Override public void onActivityResult(final int requestCode, final int resultCode, final Intent intent) { if (requestCode != REQUEST_CODE_SCAN || resultCode != RESULT_OK || !("QR_CODE".equals(intent.getStringExtra("SCAN_RESULT_FORMAT")))) { return; } String contents = intent.getStringExtra("SCAN_RESULT"); doRestore(contents); } private void doRestore(String backupCode) { BackupInfo info = BackupInfo.fromString(backupCode); if (info == null || !info.getNetwork().equals(SpinnerContext.getInstance().getNetwork())) { Utils.showAlert(this, R.string.restore_invalid_qr_code); return; } restoreDialog = ProgressDialog.show(this, getString(R.string.restore_dialog_title), getString(R.string.please_wait), true); new AsyncInit().execute(info); } private class AsyncInit extends AsyncTask<BackupInfo, Integer, Long> { @Override protected Long doInBackground(BackupInfo... params) { BackupInfo info = params[0]; SpinnerContext.getInstance().recoverWallet(info.getSeed()); return null; } protected void onPostExecute(Long result) { restoreDialog.dismiss(); Utils.showAlert(mContext, R.string.restore_complete_dialog_text); } } public static class BackupInfo { private byte[] _seed; private NetworkParameters _network; public static BackupInfo fromString(String string) { try { Uri temp = Uri.parse(string); final Uri uri = Uri.parse("bsb://" + temp.getSchemeSpecificPart()); int netId = Integer.parseInt(uri.getQueryParameter("net")); NetworkParameters network; if (netId == 0) { network = NetworkParameters.productionNetwork; } else if (netId == 1) { network = NetworkParameters.testNetwork; } else { return null; } String host = uri.getHost(); byte[] seed = Base58.decode(host); if (seed != null) { return new BackupInfo(seed, network); } } catch (Exception e) { e.printStackTrace(); } return null; } public BackupInfo(byte[] seed, NetworkParameters network) { _seed = seed; _network = network; } public byte[] getSeed() { return _seed; } public NetworkParameters getNetwork() { return _network; } String getBackupUrl() { StringBuilder sb = new StringBuilder(); sb.append("bsb:"); sb.append(Base58.encode(_seed)); sb.append("?net="); sb.append(_network.isProdnet() ? 0 : 1); return sb.toString(); } } }
[ "[email protected]@1b99fd55-653d-3305-1646-2baddee6abf9" ]
[email protected]@1b99fd55-653d-3305-1646-2baddee6abf9
654fc8bd6ee8da873453eb682ba5bf85e78a71dd
19d9bc6e589c03ecc9288fb93c7e25c9cb2d706b
/src/by/htp/hw/unit8/task01/MyThread.java
90cf742a6fa2f0dabbb6101e5e0a1fe59c8f1b04
[]
no_license
Pickle9/JD
075ceed01aa5ed2ca5b27c76d4ff496fe34443f0
18793bf379a1a81a1d7e91c347671fcb43501bf0
refs/heads/master
2021-05-09T16:06:43.530935
2018-03-17T21:24:57
2018-03-17T21:24:57
119,108,735
0
0
null
null
null
null
UTF-8
Java
false
false
755
java
package by.htp.hw.unit8.task01; public class MyThread implements Runnable { private int id; public MyThread(int id) { this.id = id; } @Override public void run() { for (int x = 0; x < 5; x++) { Matrix matrix = Matrix.getInstance(); synchronized (Matrix.getInstance()) { if (matrix.getMatrix()[x][x] == 0) { matrix.getMatrix()[x][x] = id; System.out.println(String.format("id: %o - [%o][%o]", id, x, x)); } } try { Thread.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } } } }
1fb4c21d3fcb487e41cc29ddab18af103d73b963
582a0eb683da4f2bdd8e09c6f0741d17e425e3b5
/app/src/main/java/edu/slcc/jamesfullmer/csisclasses/dummy/DummyContent.java
fac349898b3498a301d4185a5d62726c01df964c
[]
no_license
jefullmer/CSISClasses
e01f09231b85b9014067faa20522280c1622ee91
8e3e6f14a7d02d8ade0990547890f93a9f854078
refs/heads/master
2021-01-20T15:53:59.531193
2017-05-09T23:04:29
2017-05-09T23:04:29
90,799,559
0
0
null
null
null
null
UTF-8
Java
false
false
22,684
java
package edu.slcc.jamesfullmer.csisclasses.dummy; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Helper class for providing sample content for user interfaces created by * Android template wizards. * <p> * TODO: Replace all uses of this class before publishing your app. */ public class DummyContent { /** * An array of sample (dummy) items. */ public static final List<DummyItem> ITEMS = new ArrayList<DummyItem>(); /** * A map of sample (dummy) items, by ID. */ public static final Map<String, DummyItem> ITEM_MAP = new HashMap<String, DummyItem>(); static { addItem(new DummyItem("1", "CSIS 1010 - BEGINNING KEYBOARDING", "CSIS 1010 - BEGINNING KEYBOARDING:\n\n", "During the semester, students will: demonstrate proficiency using the computer; learn the keyboard by touch keying at least 25+ net words a minute on 3-minute timed writings; demonstrate correct keyboarding techniques and be evaluated; operate the alphabetic keys, number row keys, and symbol keys of the main keyboard; operate the ten-key numeric keypad; complete special drills and activities.")); addItem(new DummyItem("2", "CSIS 1013 - HOW TO OPERATE A COMPUTER FOR BEGINNING USERS", "CSIS 1013 - HOW TO OPERATE A COMPUTER FOR BEGINNING USERS\n\n", "This course is designed for students who have little or no experience with a computer. Upon completion of the course, students will be able to login to the computer, open various programs, understand some basic computer terminology, use an internet search engine, save a file in different locations, and login to the mypage and Canvas systems of SLCC. ")); addItem(new DummyItem("3", "CSIS 1015 - WORD PROCESSING APPLICATIONS", "CSIS 1015 - WORD PROCESSING APPLICATIONS\n\n", "Students will learn basic fundamentals of word processing. Students will learn to create and attach their documents to a e-portfolio. ")); addItem(new DummyItem("4", "CSIS 1017 - PRESENTATION APPLICATIONS", "CSIS 1017 - PRESENTATION APPLICATIONS\n\n", "Upon completion of this course, students will know the basic fundamentals of Microsoft PowerPoint 2010. Students will learn how to create, format, and display presentations using PowerPoint.")); addItem(new DummyItem("5", "CSIS 1019 - SPREADSHEET APPLICATIONS", "CSIS 1019 - SPREADSHEET APPLICATIONS\n\n", "In this course, students will use various features and use of current spreadsheet software. Students will learn the syntax, use and application of spreadsheet features/tools through tutorial lessons and application exercise problems. ")); addItem(new DummyItem("6", "CSIS 1020 - COMPUTER ESSENTIALS", "CSIS 1020 - COMPUTER ESSENTIALS\n\n", "A hands-on introduction to problem solving using Computer Tools. Basic hardware and Office software products topics are discussed.")); addItem(new DummyItem("7", "CSIS 1030 - FOUNDATIONS OF COMPUTER SCIENCE", "CSIS 1030 - FOUNDATIONS OF COMPUTER SCIENCE\n\n", "Understand the world of computing that surrounds you: technology’s impact on society, hardware, SOHO networking, threats, Google as a verb, ethics/policy, file management, standards, disaster recovery & remote computing. ")); addItem(new DummyItem("8", "CSIS 1032 - INTRODUCTION TO LINUX", "CSIS 1032 - INTRODUCTION TO LINUX\n\n", "This course covers fundamental Linux skills such as file management and manipulation, text processing, command line use, package management, filesystems, hardward, basic shell scripting and more. Students completing this course will have a solid understanding of basic Linux skills.")); addItem(new DummyItem("9", "CSIS 1050 - FUNDAMENTALS OF DATABASE DESIGN AND PROCESSING", "CSIS 1050 - FUNDAMENTALS OF DATABASE DESIGN AND PROCESSING\n\n", "Course provides introduction & broad overview of concepts & basic skills in current database technologies to prepare students for further studies in database programming, application development & administration/management of database systems. ")); addItem(new DummyItem("10", "CSIS 1070 - LIVING IN A DIGITAL WORLD (ID)", "CSIS 1070 - LIVING IN A DIGITAL WORLD (ID)\n\n", "This course explores 21st Century business tools needed to prepare learners using web based software with the latest digital media and technology in a real world context to share and communicate knowledge creating a social network.")); addItem(new DummyItem("11", "CSIS 1080 - XML AND DECLARATIVE PROGRAMMING", "CSIS 1080 - XML AND DECLARATIVE PROGRAMMING\n\n", "This course describes how XML is used as both a text based markup language and metalanguages for describing and transmitting data (especially over a network). Other lisp-like metalanguages are also studied for comparison.")); addItem(new DummyItem("12", "CSIS 1121 - COMPTIA", "CSIS 1121 - COMPTIA\n\n", "Presents necessary competencies for an IT professional, including configuring, troubleshooting, and performing preventative maintenance of PC hardware and operating systems. Students will take the CompTIA A+ Essentials exam. ")); addItem(new DummyItem("13", "CSIS 1122 - LINUX SYSTEM ADMINISTRATION I", "CSIS 1122 - LINUX SYSTEM ADMINISTRATION I\n\n", "This course covers fundamental Linux skills such as file management and manipulation, text processing, command line use, package management, file systems, hardware, and many more. The course also prepares students to take the Linux Professional Institute LPIC-101 exam. ")); addItem(new DummyItem("14", "CSIS 1124 - INTRODUCTION TO MICROSOFT WINDOWS DESKTOP", "CSIS 1124 - INTRODUCTION TO MICROSOFT WINDOWS DESKTOP\n\n", "This course provides students with the an overview of the Microsoft desktop operating system. It explores installation, features, and troubleshoooting. ")); addItem(new DummyItem("15", "CSIS 1129 - COMPTIA", "CSIS 1129 - COMPTIA\n\n", "Presents necessary competencies for an IT professional, including configuring, troubleshooting, & performing preventative maintenance of PC hardware & operating systems.")); addItem(new DummyItem("16", "CSIS 1132 - LINUX SYSTEM ADMIN I", "CSIS 1132 - LINUX SYSTEM ADMIN I\n\n", "Students completing this course will have an in-depth knowledge of installation, configuration and maintenance of Linux Systems. Topics include Security, user and group administration, networking, FACLs, LVM, task automation, troubleshooting, and more. This course helps prepare students to take Red Hat RHCSA or LPIC 1 exams. ")); addItem(new DummyItem("17", "CSIS 1200 - INTRODUCTION TO NETWORKING", "CSIS 1200 - INTRODUCTION TO NETWORKING\n\n", "This course covers how common network protocols are used within a network. Students will learn how to use Wireshark to capture and analyze network traffic such as: ARP, IP, TCP, UDP, ICMP, DNS, DHCP, HTTP, RIP and EIGRP. Subnetting, VLSM, and CIDR are also covered. ")); addItem(new DummyItem("18", "CSIS 1250 - NETWORK ROUTING AND SWITCHING I", "CSIS 1250 - NETWORK ROUTING AND SWITCHING I\n\n", "This course provides students with the fundamental Cisco CCENT level skills necessary to administer routers and switches. Students will use Ciscos Packet Tracer software to create dynamic networking environments. Topics include static and dynamic routing, switch configuration, Implementing NAT and DHCP, network troubleshooting and more. ")); addItem(new DummyItem("19", "CSIS 1251 - NETWORK ROUTING AND SWITCHING II", "CSIS 1251 - NETWORK ROUTING AND SWITCHING II\n\n", "This course provides students with advances skills in Cisco CCNA level networking. Topics covered include: VLSM and IPv6 addressing; extending switched networks with VLANs; configuring, verifying and troubleshooting VLANs; the VTP, RSTP, OSPF and EIGRP protocols.")); addItem(new DummyItem("20", "CSIS 1340 - INTRODUCTION TO PROGRAMMING", "CSIS 1340 - INTRODUCTION TO PROGRAMMING\n\n", "A first course in programming. This course introduces the fundamental concepts of programming using an object-oriented language such as Java. No prior programming experience is necessary for successful course completion. Topics include: syntax, control structures, arrays and algorithms. ")); addItem(new DummyItem("21", "CSIS 1350 - APPS AND APPLETS: AN INTRODUCTION TO PROGRAMMING", "CSIS 1350 - APPS AND APPLETS: AN INTRODUCTION TO PROGRAMMING\n\n", "A first course in computer programming with an emphasis on interactive and graphical components. No prior programming experience is required for this course. Students will create a wide variety of interactive, interesting programs from business applications to game playing. Some software will be developed and simulated as apps in a mobile environment. ")); addItem(new DummyItem("22", "CSIS 1400 - FUNDAMENTALS OF PROGRAMMING", "CSIS 1400 - FUNDAMENTALS OF PROGRAMMING\n\n", "Object oriented design using UML: problem statement and glossary, use case diagram and scenarios, activity diagram, role/object mapping, and class diagrams. Introduction to Java: data types, control structures, methods and classes, arrays and introduction to the Java API. ")); addItem(new DummyItem("23", "CSIS 1410 - OBJECT-ORIENTED PROGRAMMING", "CSIS 1410 - OBJECT-ORIENTED PROGRAMMING\n\n", "Essentials of object oriented programming in Java: creating classes, data validation, generics, packages, exception handling, unit testing, inheritance, , polymorphism, file handling, basic Swing, and a subset of the Java API are covered. ")); addItem(new DummyItem("24", "CSIS 1430 - INTERNET & XHTML FUNDAMENTALS (ID)", "CSIS 1430 - INTERNET & XHTML FUNDAMENTALS (ID)\n\n", "Students should have basic computer skills. Students will learn to use the Internet & create Websites. Topics include basic Internet applications & HTML, XHTML, CSS, XML, JavaScript & layout techniques. The Internets social & legal impacts will also be studied. ")); addItem(new DummyItem("25", "CSIS 1440 - OBJECT ORIENTED ANALYSIS AND DESIGN", "CSIS 1440 - OBJECT ORIENTED ANALYSIS AND DESIGN\n\n", "Provides practical experience designing the construction of object-oriented software. Topics include finding classes, identifying attributes and methods, UML, CRC cards, use-case scenarios. Software tools will be used. ")); addItem(new DummyItem("26", "CSIS 1520 - OPERATING SYSTEMS", "CSIS 1520 - OPERATING SYSTEMS\n\n", "This course introduces the fundamental concepts of operating systems. Command-based & graphical OSs are examined. Concepts include: History of OS, Mac OS X, Linux, Windows, and Network OS.")); addItem(new DummyItem("27", "CSIS 1550 - SQL PROGRAMMING", "CSIS 1550 - SQL PROGRAMMING\n\n", "The course provides students with a comprehensive understanding and hands-on experience in SQL, a database computer language designed for the retrieval and management of data in relational database management systems (RDBMS).")); addItem(new DummyItem("28", "CSIS 1600 - C++ PROGRAMMING", "CSIS 1600 - C++ PROGRAMMING\n\n", "Introductory programming course designed to develop a solid foundation in structured programming by developing computer programs to solve scientific and technical problems. Includes a brief introduction to object oriented programming.")); addItem(new DummyItem("29", "CSIS 1850 - OBJECT-ORIENTED PROGRAMMING FOR VISUAL ART", "CSIS 1850 - OBJECT-ORIENTED PROGRAMMING FOR VISUAL ART\n\n", "A course designed to teach the basics of computer programming skills for visual art production. Emphasis will be placed on the design and implementation of complex projects between art and programming applications.")); addItem(new DummyItem("30", "CSIS 2000 - CO-OP EDUCATION", "CSIS 2000 - CO-OP EDUCATION\n\n", "A supervised work experience in a business, industrial, or government environment related to a computer sciences and information systems major. Credit is awarded for successful completion of specific learning objectives. ")); addItem(new DummyItem("31", "CSIS 2010 - BUSINESS COMPUTER PROFICIENCY", "CSIS 2010 - BUSINESS COMPUTER PROFICIENCY\n\n", "Course covers various features and functions of spreadsheet and database software for business applications. Class consists of lectures and demonstrations of how specific software tools can be used and correct formula and function syntax. Students will develop knowledge and skills using spreadsheet and database software as business problem solving tools. ")); addItem(new DummyItem("32", "CSIS 2040 - ADVANCED SPREADSHEET APPLICATIONS", "CSIS 2040 - ADVANCED SPREADSHEET APPLICATIONS\n\n", "The course provides significant problem solving experiences in a wide range of business-focused spreadsheet application problems using spreadsheet software.")); addItem(new DummyItem("33", "CSIS 2050 - ADVANCED DATABASE APPLICATIONS", "CSIS 2050 - ADVANCED DATABASE APPLICATIONS\n\n", "The course provides significant problem solving experiences in a wide range of business-focused database application problems using database software.")); addItem(new DummyItem("34", "CSIS 2060 - DECISION SUPPORT SYSTEMS", "CSIS 2060 - DECISION SUPPORT SYSTEMS\n\n", "This course provides students with learning activities to apply database and spreadsheet software effectively and efficiently to solve real-world business decision support system (DSS) problems.")); addItem(new DummyItem("35", "CSIS 2110 - MANAGING MICROSOFT WINDOWS SERVER: NETWORK INFRASTRUCTURE", "CSIS 2110 - MANAGING MICROSOFT WINDOWS SERVER: NETWORK INFRASTRUCTURE\n\n", "This course covers topics that a student would need to prepare for the Windows Server Network Infrastructure exam. ")); addItem(new DummyItem("36", "CSIS 2120 - MICROSOFT SERVER ACTIVE DIRECTORY ADMINISTRATION", "CSIS 2120 - MICROSOFT SERVER ACTIVE DIRECTORY ADMINISTRATION\n\n", "This course covers topics that a student would need to prepare for the Windows Server Active Directory exam. ")); addItem(new DummyItem("37", "CSIS 2130 - MICROSOFT SERVER ADMINISTRATION", "CSIS 2130 - MICROSOFT SERVER ADMINISTRATION\n\n", "This course covers topics that a student would need to prepare for the Windows Server Administrator exam. ")); addItem(new DummyItem("38", "CSIS 2132 - LINUX SYSTEM ADMIN II", "CSIS 2132 - LINUX SYSTEM ADMIN II\n\n", "Students completing this course will have an in-depth knowledge of installation, configuration and maintenance of Linux Systems. Topics include Security, user and group administration, networking, FACLs, LVM, task automation, troubleshooting, and more. This course helps prepare students to take Red Hat RHCSA or LPIC 1 exams. ")); addItem(new DummyItem("39", "CSIS 2310 - WIRELESS NETWORKING", "CSIS 2310 - WIRELESS NETWORKING\n\n", "This course pepares students to configure wireless networks from layers 1-4 of the OSI model. It includes wireless security, encryption, RF fundamentals, antenna design, Wi-Fi and more. Students setup WLANs and secure them. It uses the CWNA curriculum. ")); addItem(new DummyItem("40", "CSIS 2320 - COMPUTER AND NETWORK SECURITY", "CSIS 2320 - COMPUTER AND NETWORK SECURITY\n\n", "This course covers network security and maps to the CompTIA Security+ exam.")); addItem(new DummyItem("41", "CSIS 2330 - PENETRATION TESTING", "CSIS 2330 - PENETRATION TESTING\n\n", "Students learn how to secure computer networks from attacks by learning the tools and tactics employed by hackers to penetrate networks and compromise hosts computers. Topics include Using the Linux distribution Backtrack for pen-testing, network security and ethical hacking. ")); addItem(new DummyItem("42", "CSIS 2340 - CISCO SECURITY", "CSIS 2340 - CISCO SECURITY\n\n", "This course covers the materials that a student would need to prepare for the Cisco CCNA Security Exam 210-260. Cisco Certified Network Associate Security (CCNA Security) validates associate-level knowledge and skills required to secure Cisco networks.")); addItem(new DummyItem("43", "CSIS 2350 - CERTIFIED HACKING FORENSIC INVESTIGATOR", "CSIS 2350 - CERTIFIED HACKING FORENSIC INVESTIGATOR\n\n", "This course prepares students to pass the Certified Hacking Forensic Investigator (CHFI) exam. This course helps students understand the legal and ethical aspects of information security and assurance. Students will study procedures for collecting and handling computer related evidence in criminal investigations. ")); addItem(new DummyItem("44", "CSIS 2360 - CERTIFIED ETHICAL HACKER", "CSIS 2360 - CERTIFIED ETHICAL HACKER\n\n", "This course prepares students to pass the Certified Ethical Hacker (CEH) exam. Students will study and practice hacking techniques and master hacking technologies. Students will use advanced hacking tools and techniques used by hackers to defeat security defenses. ")); addItem(new DummyItem("45", "CSIS 2410 - ADVANCED PROGRAMMING", "CSIS 2410 - ADVANCED PROGRAMMING\n\n", "Students will develop substantial projects with the rigor required to succed in CSIS-2420, four year colleges, or in the work place. Students will design, and publish applications that consist of graphical front-ends and database back-ends. They will be introduced to best practices such as recognizing and applying design patterns as well as to a new object oriented language.")); addItem(new DummyItem("46", "CSIS 2420 - ALGORITHMS & DATA STRUCTURES", "CSIS 2420 - ALGORITHMS & DATA STRUCTURES\n\n", "Topics include data structures (stacks, queues, linked lists, heaps, hash tables, trees, graphs); Java Collections framework; algorithmic analysis (Big O, profiling); and common algorithms (recursion, searching, sorting, traversals).")); addItem(new DummyItem("47", "CSIS 2430 - DISCRETE STRUCTURES", "CSIS 2430 - DISCRETE STRUCTURES\n\n", "An introduction to discrete mathematics and algebraic structures as applied to computer science. Proposition and logic, finite sets, relations, functions, graph theory, analysis of algorithms and state machines are taught.")); addItem(new DummyItem("48", "CSIS 2440 - WEB PROGRAMMING", "CSIS 2440 - WEB PROGRAMMING\n\n", "This course teaches how to program web pages based on the three-teir model. Both client side and server side languages as well as tools such as XHTML, JavaScript, PHP, and My*SQL are taught.")); addItem(new DummyItem("49", "CSIS 2450 - SOFTWARE ENGINEERING", "CSIS 2450 - SOFTWARE ENGINEERING\n\n", "Presents concepts, methodology and best-practices necessary to develop large scale software projects. Includes reqts., analysis, design, implementation and testing. Emphasizes current “real world” industry best-practices and tools.")); addItem(new DummyItem("50", "CSIS 2470 - ADVANCED JAVASCRIPT AND JSP", "CSIS 2470 - ADVANCED JAVASCRIPT AND JSP\n\n", "This course is a continuation of CSIS 2440. It will teach advanced JavaScript techniques and JSP for use in the THREE TIER MODEL. Advanced skills will be taught to allow the student to build complex web sites suitable for E-Commerce. ")); addItem(new DummyItem("51", "CSIS 2530 - INTERMEDIATE PROGRAMMING IN C#", "CSIS 2530 - INTERMEDIATE PROGRAMMING IN C#\n\n", "This intermediate programming course focuses on C# and the .NET platform. Syntax, data structures, file i/o, .NET library, XML, class structure, GUI design, and web/database projects will be discussed.")); addItem(new DummyItem("52", "CSIS 2570 - ADVANCED JAVA PROGRAMMING", "CSIS 2570 - ADVANCED JAVA PROGRAMMING\n\n", "Students will learn skills to design, code, and publish applications using advanced concepts in the Java Programming Language. Topics may include; SQL Database Access, Networks Communications, Multithreading, Parallel Programming, Servlets, Multimedia, Java Beans, Socket Programming and Advanced GUI interfaces using Menus, Toobars, and Dialogs.")); addItem(new DummyItem("53", "CSIS 2630 - ANDROID APPLICATION DEVELOPMENT", "CSIS 2630 - ANDROID APPLICATION DEVELOPMENT\n\n", "Students will learn the skills required to design, code, and publish applications for mobile devices running the Android operating system. Topics include IDEs and emulators, Java as it relates to Android, XML layouts and resource files, SQLite, and the Android Market. During the semester, students will code and publish a complete mobile application.")); addItem(new DummyItem("54", "CSIS 2640 - MOBILE IOS APPLICATION DEVELOPMENT", "CSIS 2640 - MOBILE IOS APPLICATION DEVELOPMENT\n\n", "Students will learn the skills to design, code, and publish applications for mobile devices running Apple’s iOS operating system. Current devices include the iPhone and iPad. Topics include Apple’s IDE and iOS simulator, the Objective C programming language, memory management, wireless communication, and the iTunes market. ")); addItem(new DummyItem("55", "CSIS 2700 - PROJECTS FOR INDUSTRY", "CSIS 2700 - PROJECTS FOR INDUSTRY\n\n", "Students will implement skills learned in previous CSIS design and programming classes and gain real world experience through service learning. Each class will work together as a team to design and program and computer system that meets the needs of an approved client from the community. ")); addItem(new DummyItem("56", "CSIS 2810 - COMPUTER ARCHITECTURE", "CSIS 2810 - COMPUTER ARCHITECTURE\n\n", "Computer architecture explores the language of the computer, computer arithmetic, assessing & understanding performance, datapath and control, pipelining, memory hierarchies, and interfacing processors and peripherals. The course emphasizes how these topics influence the physical and functional relationships between computer hardware and software.")); addItem(new DummyItem("57", "CSIS 2900 - CURRENT TOPICS IN COMPUTER SCIENCES AND INFORMATION SYSTEMS", "CSIS 2900 - CURRENT TOPICS IN COMPUTER SCIENCES AND INFORMATION SYSTEMS\n\n", "This course covers current topics in computer science that meet student needs and industry demands.")); } private static void addItem(DummyItem item) { ITEMS.add(item); ITEM_MAP.put(item.id, item); } /** * A dummy item representing a piece of content. */ public static class DummyItem { public final String id; public final String content; public final String details; public DummyItem(String id, String content, String title, String details) { this.id = id; this.content = content; this.details = title + details; } @Override public String toString() { return content; } } }
dbfc03c53154ead68269a902b66d0375a4fcb5f2
a040c6c30ec23435f5ba5bb6f5ed52c6dcb3db7f
/BBSSDKTHEME1/src/com/mob/bbssdk/theme1/view/Theme1MainView.java
88aeb9dbcbbe664484310dc8480983a2356257fa
[ "Apache-2.0" ]
permissive
Inspirelife96/BBSSDK-for-Android
6934732910fab3e85c73032f0fc18c24c695c0bc
383d9386141e48d6ef12be02b715ca361f6f32f7
refs/heads/master
2021-06-29T04:46:05.213856
2017-09-22T07:42:15
2017-09-22T07:42:15
null
0
0
null
null
null
null
UTF-8
Java
false
false
20,886
java
package com.mob.bbssdk.theme1.view; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.Bitmap; import android.graphics.Color; import android.os.Handler; import android.os.Message; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import com.mob.bbssdk.API; import com.mob.bbssdk.APICallback; import com.mob.bbssdk.BBSSDK; import com.mob.bbssdk.api.ForumAPI; import com.mob.bbssdk.api.UserAPI; import com.mob.bbssdk.gui.BBSViewBuilder; import com.mob.bbssdk.gui.ForumThreadHistoryManager; import com.mob.bbssdk.gui.GUIManager; import com.mob.bbssdk.gui.builder.ListViewItemBuilder; import com.mob.bbssdk.gui.helper.ErrorCodeHelper; import com.mob.bbssdk.gui.other.BannerLayout; import com.mob.bbssdk.gui.pages.PageWeb; import com.mob.bbssdk.gui.pages.forum.PageForumThreadDetail; import com.mob.bbssdk.gui.pages.forum.PageSearch; import com.mob.bbssdk.gui.utils.ImageDownloader; import com.mob.bbssdk.gui.utils.ScreenUtils; import com.mob.bbssdk.gui.utils.SendForumThreadManager; import com.mob.bbssdk.gui.views.ForumThreadListView; import com.mob.bbssdk.gui.views.GlideImageView; import com.mob.bbssdk.gui.views.MainView; import com.mob.bbssdk.gui.views.MainViewInterface; import com.mob.bbssdk.gui.views.pullrequestview.BBSPullToRequestView; import com.mob.bbssdk.model.Banner; import com.mob.bbssdk.model.ForumForum; import com.mob.bbssdk.model.ForumThread; import com.mob.bbssdk.model.User; import com.mob.bbssdk.model.UserOperations; import com.mob.bbssdk.theme1.BBSTheme1ViewBuilder; import com.mob.bbssdk.theme1.page.Theme1PageForumSetting; import com.mob.bbssdk.theme1.page.Theme1PageForumThread; import com.mob.tools.FakeActivity; import com.mob.tools.utils.ResHelper; import com.mob.tools.utils.UIHandler; import java.util.ArrayList; import java.util.HashMap; import java.util.List; public class Theme1MainView extends FrameLayout implements MainViewInterface { protected ForumThreadListView forumThreadListViewWithBanner; protected GlideImageView imageViewAvatar; protected ImageView imageViewSearch; protected ImageView imageViewWritePost; protected View viewTitle; protected View viewBackground; protected TextView textViewTitle; protected View viewMessageMark; private GUIManager.LoginListener loginListener; private ArrayList<ForumForum> forumForum; private BroadcastReceiver sendThreadReceiver; private View viewHeaderContent; protected ViewGroup viewHeaderFunc1; protected ViewGroup viewHeaderFunc2; protected ViewGroup viewHeaderFunc3; protected ViewGroup viewHeaderFunc4; protected ImageView imageViewHeaderFunc1; protected ImageView imageViewHeaderFunc2; protected ImageView imageViewHeaderFunc3; protected ImageView imageViewHeaderFunc4; protected ImageView imageViewFakeBanner; protected TextView textViewHeaderFunc1; protected TextView textViewHeaderFunc2; protected TextView textViewHeaderFunc3; protected TextView textViewHeaderFunc4; protected ViewGroup viewHeaderFuncMore; public Theme1MainView(@NonNull Context context) { super(context); init(context); } public Theme1MainView(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(context); } public Theme1MainView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); } protected void updateTab() { BBSSDK.getApi(ForumAPI.class).getForumList(0, false, new APICallback<ArrayList<ForumForum>>() { @Override public void onSuccess(API api, int action, final ArrayList<ForumForum> result) { forumForum = result; updateTabFunc(); } @Override public void onError(API api, int action, int errorCode, Throwable details) { ErrorCodeHelper.toastError(getContext(), errorCode, details); } }); } protected void updateNewMessageMark() { //only update the mark when user have logged in. if (!GUIManager.isLogin()) { return; } UserAPI api = BBSSDK.getApi(UserAPI.class); api.getUserOperations(null, false, new APICallback<UserOperations>() { @Override public void onSuccess(API api, int action, UserOperations result) { if (result != null) { if (result.notices > 0) { viewMessageMark.setVisibility(VISIBLE); } else { viewMessageMark.setVisibility(INVISIBLE); } } } @Override public void onError(API api, int action, int errorCode, Throwable details) { ErrorCodeHelper.toastError(getContext(), errorCode, details); } }); } OnClickListener headerOnClickListener = new OnClickListener() { @Override public void onClick(View v) { if (forumForum == null) { return; } ForumForum forum = null; if (v == viewHeaderFunc1) { forum = forumForum.get(0); } else if (v == viewHeaderFunc2) { forum = forumForum.get(1); } else if (v == viewHeaderFunc3) { forum = forumForum.get(2); } else if (v == viewHeaderFunc4) { forum = forumForum.get(3); } if (forum != null) { Theme1PageForumThread page = new Theme1PageForumThread(); page.initData(forum); page.show(getContext()); } } }; protected void updateTabFunc() { //view created and data got. if (viewHeaderContent != null && forumForum != null) { if (forumForum.get(0) != null) { final ForumForum forum = forumForum.get(0); ImageDownloader.loadCircleImage(forum.forumPic, imageViewHeaderFunc1); textViewHeaderFunc1.setText(forum.name); viewHeaderFunc1.setVisibility(VISIBLE); } else { viewHeaderFunc1.setVisibility(INVISIBLE); } if (forumForum.get(1) != null) { final ForumForum forum = forumForum.get(1); ImageDownloader.loadCircleImage(forum.forumPic, imageViewHeaderFunc2); textViewHeaderFunc2.setText(forum.name); viewHeaderFunc2.setVisibility(VISIBLE); } else { viewHeaderFunc2.setVisibility(INVISIBLE); } if (forumForum.get(2) != null) { final ForumForum forum = forumForum.get(2); ImageDownloader.loadCircleImage(forum.forumPic, imageViewHeaderFunc3); textViewHeaderFunc3.setText(forum.name); viewHeaderFunc3.setVisibility(VISIBLE); } else { viewHeaderFunc3.setVisibility(INVISIBLE); } if (forumForum.get(3) != null) { final ForumForum forum = forumForum.get(3); ImageDownloader.loadCircleImage(forum.forumPic, imageViewHeaderFunc4); textViewHeaderFunc4.setText(forum.name); viewHeaderFunc4.setVisibility(VISIBLE); } else { viewHeaderFunc4.setVisibility(INVISIBLE); } } } protected void init(Context context) { setBackgroundColor(Color.WHITE); loginListener = new GUIManager.LoginListener() { @Override public void OnLoggedIn() { if (forumThreadListViewWithBanner != null) { forumThreadListViewWithBanner.refreshData(); } } @Override public void OnCancel() { } }; forumThreadListViewWithBanner = new ForumThreadListView(context) { BannerLayout bannerLayout; ImageView imageViewFakeBanner; List<Banner> listBanner = new ArrayList<Banner>(); public boolean dispatchTouchEvent(MotionEvent ev) { if (checkIsTouchHeaderView(ev.getY())) { return viewHeader.dispatchTouchEvent(ev); } return super.dispatchTouchEvent(ev); } public boolean onInterceptTouchEvent(MotionEvent ev) { if (checkIsTouchHeaderView(ev.getY())) { return true; } return super.onInterceptTouchEvent(ev); } private boolean checkIsTouchHeaderView(float eventY) { if (!basePagedItemAdapter.haveContentHeader()) { return false; } if (viewHeader != null && viewHeader.isShown()) { float headerViewY = viewHeader.getY(); return eventY < viewHeader.getHeight() + headerViewY && Math.abs(headerViewY) < viewHeader.getHeight() && headerViewY <= 0 && headerViewY > -10; } return false; } @Override protected void init() { super.init(); setHaveContentHeader(true); } @Override public View getContentHeader(ViewGroup viewGroup, View viewprev) { if (viewprev != null) { return viewprev; } //Don't reuse the previous view to prevent the click no response bug during scroll back and forth. View viewheader = LayoutInflater.from(getContext()).inflate(ResHelper.getLayoutRes(getContext(), "bbs_theme1_layout_mainviewheader"), viewGroup, false); viewheader.setOnClickListener(headerOnClickListener); imageViewFakeBanner = (ImageView) viewheader.findViewById(ResHelper.getIdRes(getContext(), "imageViewFakeBanner")); bannerLayout = (BannerLayout) viewheader.findViewById(ResHelper.getIdRes(getContext(), "bannerLayout")); viewHeaderFunc1 = (ViewGroup) viewheader.findViewById(ResHelper.getIdRes(getContext(), "viewHeaderFunc1")); viewHeaderFunc2 = (ViewGroup) viewheader.findViewById(ResHelper.getIdRes(getContext(), "viewHeaderFunc2")); viewHeaderFunc3 = (ViewGroup) viewheader.findViewById(ResHelper.getIdRes(getContext(), "viewHeaderFunc3")); viewHeaderFunc4 = (ViewGroup) viewheader.findViewById(ResHelper.getIdRes(getContext(), "viewHeaderFunc4")); viewHeaderFunc1.setOnClickListener(headerOnClickListener); viewHeaderFunc2.setOnClickListener(headerOnClickListener); viewHeaderFunc3.setOnClickListener(headerOnClickListener); viewHeaderFunc4.setOnClickListener(headerOnClickListener); imageViewHeaderFunc1 = (ImageView) viewheader.findViewById(ResHelper.getIdRes(getContext(), "imageViewHeaderFunc1")); imageViewHeaderFunc2 = (ImageView) viewheader.findViewById(ResHelper.getIdRes(getContext(), "imageViewHeaderFunc2")); imageViewHeaderFunc3 = (ImageView) viewheader.findViewById(ResHelper.getIdRes(getContext(), "imageViewHeaderFunc3")); imageViewHeaderFunc4 = (ImageView) viewheader.findViewById(ResHelper.getIdRes(getContext(), "imageViewHeaderFunc4")); textViewHeaderFunc1 = (TextView) viewheader.findViewById(ResHelper.getIdRes(getContext(), "textViewHeaderFunc1")); textViewHeaderFunc2 = (TextView) viewheader.findViewById(ResHelper.getIdRes(getContext(), "textViewHeaderFunc2")); textViewHeaderFunc3 = (TextView) viewheader.findViewById(ResHelper.getIdRes(getContext(), "textViewHeaderFunc3")); textViewHeaderFunc4 = (TextView) viewheader.findViewById(ResHelper.getIdRes(getContext(), "textViewHeaderFunc4")); viewHeaderFuncMore = (ViewGroup) viewheader.findViewById(ResHelper.getIdRes(getContext(), "viewHeaderFuncMore")); viewHeaderFuncMore.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { new Theme1PageForumSetting().show(getContext()); } }); if (viewprev == null) { getBanner(); } else { updateBanner(null); } viewHeaderContent = viewheader; updateTabFunc(); return viewheader; } @Override protected View getContentView(final int position, View convertView, ViewGroup parent) { Integer layout = ResHelper.getLayoutRes(getContext(), "bbs_theme1_item_mainviewthread"); final View view = ListViewItemBuilder.getInstance().buildLayoutThreadView(getItem(position), convertView, parent, layout); final ForumThread forumthread = getItem(position); view.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (forumthread != null) { if (itemClickListener != null) { itemClickListener.onItemClick(position, forumthread); } ForumThreadHistoryManager.getInstance().addReadedThread(forumthread); setThreadReaded(view, true); } } }); TextView textViewTime = (TextView) view.findViewById(ResHelper.getIdRes(getContext(), "textViewMainViewThreadTime")); if (textViewTime != null) { textViewTime.setText(com.mob.bbssdk.gui.utils.TimeUtils.timeDiff(getContext(), forumthread.createdOn)); } return view; } @Override protected void OnRefresh() { super.OnRefresh(); getBanner(); updateTab(); updateNewMessageMark(); } protected void getBanner() { UserAPI userapi = BBSSDK.getApi(UserAPI.class); userapi.getBannerList(false, new APICallback<List<Banner>>() { @Override public void onSuccess(API api, int action, List<Banner> result) { listBanner = result; OnBannerGot(listBanner); } @Override public void onError(API api, int action, int errorCode, Throwable details) { ErrorCodeHelper.toastError(getContext(), errorCode, details); } }); } protected void OnBannerGot(List<Banner> list) { updateBanner(list); } public void updateBanner(List<Banner> l) { if (imageViewFakeBanner == null || bannerLayout == null) { return; } final List<Banner> banners; if (l == null) { banners = listBanner; } else { banners = l; } if (banners == null || banners.size() == 0) { imageViewFakeBanner.setVisibility(VISIBLE); bannerLayout.setVisibility(GONE); return; } else { imageViewFakeBanner.setVisibility(GONE); bannerLayout.setVisibility(VISIBLE); } if (bannerLayout != null && banners != null) { List<BannerLayout.Item> list = new ArrayList<BannerLayout.Item>(); for (Banner banner : banners) { BannerLayout.Item item = new BannerLayout.Item(); item.strUrl = banner.picture; item.strTitle = banner.title; list.add(item); } bannerLayout.setOnBannerItemClickListener(new BannerLayout.OnBannerItemClickListener() { @Override public void onItemClick(int position) { if (banners != null) { Banner banner = banners.get(position); if (banner != null && banner.btype != null) { if (banner.btype.equals("thread")) { PageForumThreadDetail page = BBSViewBuilder.getInstance().buildPageForumThreadDetail(); ForumThread thread = new ForumThread(); thread.tid = Long.valueOf(banner.tid); thread.fid = Long.valueOf(banner.fid); page.setForumThread(thread); page.show(getContext()); } else if (banner.btype.equals("link")) { String url = banner.link; if (url != null && (url.startsWith("http://") || url.startsWith("https://"))) { PageWeb pageWeb = BBSViewBuilder.getInstance().buildPageWeb(); pageWeb.setLink(url); pageWeb.show(getContext()); } } } } } }); bannerLayout.setViewItems(list); } } }; addView(forumThreadListViewWithBanner, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); forumThreadListViewWithBanner.startLoadData(); viewTitle = LayoutInflater.from(context).inflate(ResHelper.getLayoutRes(context, "bbs_theme1_mainview_title"), this, false); viewBackground = viewTitle.findViewById(ResHelper.getIdRes(getContext(), "viewBackground")); imageViewAvatar = (GlideImageView) viewTitle.findViewById(ResHelper.getIdRes(context, "imageViewAvatar")); imageViewSearch = (ImageView) viewTitle.findViewById(ResHelper.getIdRes(context, "imageViewSearch")); imageViewWritePost = (ImageView) viewTitle.findViewById(ResHelper.getIdRes(context, "imageViewWritePost")); textViewTitle = (TextView) viewTitle.findViewById(ResHelper.getIdRes(context, "textViewTitle")); viewMessageMark = viewTitle.findViewById(ResHelper.getIdRes(context, "viewMessageMark")); addView(viewTitle); setFitsSystemWindows(true); imageViewAvatar.setExecuteRound(); imageViewSearch.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { PageSearch search = BBSTheme1ViewBuilder.getInstance().buildPageSearch(); search.show(getContext()); } }); imageViewWritePost.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { GUIManager.getInstance().writePost(getContext(), null); } }); imageViewAvatar.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { if (GUIManager.isLogin()) { BBSViewBuilder.getInstance().buildPageUserProfile().showForResult(getContext(), new FakeActivity() { @Override public void onResult(HashMap<String, Object> data) { super.onResult(data); if (data != null) { Boolean logout = ResHelper.forceCast(data.get("logout")); if (logout != null && logout) { forumThreadListViewWithBanner.performPullingDown(true); } } } }); } else { GUIManager.showLogin(getContext(), loginListener); } } }); forumThreadListViewWithBanner.setOnScrollListener(new ForumThreadListView.OnScrollListener() { @Override public void OnScrolledTo(int y) { BBSPullToRequestView.setAlphaByScrollY(viewBackground, y, ScreenUtils.dpToPx(100)); BBSPullToRequestView.setAlphaByScrollY(textViewTitle, y, ScreenUtils.dpToPx(100)); } }); } @Override public void loadData() { forumThreadListViewWithBanner.performPullingDown(true); } @Override public void onCreate() { getContext().registerReceiver(initSendThreadReceiver(), new IntentFilter(SendForumThreadManager.BROADCAST_SEND_THREAD)); updateTitleBarRight(SendForumThreadManager.getStatus(getContext())); } @Override public void onDestroy() { if (sendThreadReceiver != null) { getContext().unregisterReceiver(sendThreadReceiver); } } @Override public void setThreadItemClickListener(ForumThreadListView.OnItemClickListener listener) { forumThreadListViewWithBanner.setOnItemClickListener(listener); } @Override public void setForumItemClickListener(MainView.ForumItemClickListener listener) { } @Override public void updateTitleUserAvatar() { if (imageViewAvatar == null) { return; } if (!GUIManager.isLogin()) { imageViewAvatar.setImageResource(ResHelper.getBitmapRes(getContext(), "bbs_theme1_account_white")); } else { Bitmap currenavatar = GUIManager.getInstance().getCurrentUserAvatar(); if (currenavatar == null) { GUIManager.getInstance().forceUpdateCurrentUserAvatar(new GUIManager.AvatarUpdatedListener() { @Override public void onUpdated(Bitmap bitmap) { if (bitmap == null) { imageViewAvatar.setImageResource(ResHelper.getBitmapRes(getContext(), "bbs_theme1_account_white")); } else { imageViewAvatar.setImageBitmap(bitmap); } } }); } else { imageViewAvatar.setImageBitmap(currenavatar); } } } private BroadcastReceiver initSendThreadReceiver() { if (sendThreadReceiver == null) { sendThreadReceiver = new BroadcastReceiver() { public void onReceive(Context context, Intent intent) { if (intent == null) { return; } int status = intent.getIntExtra("status", SendForumThreadManager.STATUS_SEND_IDLE); updateTitleBarRight(status); } }; } return sendThreadReceiver; } protected void updateTitleRightImg(MainView.WritePostStatus status) { if (status == null) { imageViewWritePost.setImageResource(ResHelper.getBitmapRes(getContext(), "bbs_theme1_title_writepost")); return; } switch (status) { case Failed: { imageViewWritePost.setImageResource(ResHelper.getBitmapRes(getContext(), "bbs_ic_writethread_failed")); } break; case Success: { imageViewWritePost.setImageResource(ResHelper.getBitmapRes(getContext(), "bbs_ic_writethread_success")); } break; case Normal: { imageViewWritePost.setImageResource(ResHelper.getBitmapRes(getContext(), "bbs_theme1_title_writepost")); } break; default: { imageViewWritePost.setImageResource(ResHelper.getBitmapRes(getContext(), "bbs_theme1_title_writepost")); } break; } } private void updateTitleBarRight(int status) { User user = BBSViewBuilder.getInstance().ensureLogin(false); if (!GUIManager.isLogin() || (user != null && user.allowPost != 1)) { updateTitleRightImg(MainView.WritePostStatus.Normal); return; } if (imageViewWritePost == null) { return; } if (status == SendForumThreadManager.STATUS_SEND_ING) { //todo // titleBar.setRightProgressBar(); } else if (status == SendForumThreadManager.STATUS_SEND_FAILED) { updateTitleRightImg(MainView.WritePostStatus.Failed); } else if (status == SendForumThreadManager.STATUS_SEND_SUCCESS) { updateTitleRightImg(MainView.WritePostStatus.Success); UIHandler.sendEmptyMessageDelayed(0, 2000, new Handler.Callback() { public boolean handleMessage(Message msg) { updateTitleRightImg(MainView.WritePostStatus.Normal); return false; } }); } else { updateTitleRightImg(MainView.WritePostStatus.Normal); } } }