text
stringlengths
10
2.72M
package uk.co.dyadica.unitymsband; import android.app.Activity; import android.content.Context; import android.os.AsyncTask; import android.widget.Toast; import com.microsoft.band.BandClient; import com.microsoft.band.BandClientManager; import com.microsoft.band.BandException; import com.microsoft.band.BandInfo; import com.microsoft.band.ConnectionState; import com.unity3d.player.UnityPlayer; /** * Created by dyadica.co.uk on 02/01/2016. * This source is subject to the dyadica.co.uk Permissive License. * Please see the http://www.dyadica.co.uk/permissive-license file for more information. * All other rights reserved. * THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY * KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A * PARTICULAR PURPOSE. */ public class MsBandManager implements IBandCommunication { // List of paired bands public BandInfo[] pairedDevices; // List of respective clients public BandClient[] clients; // List of bands public MsBand[] msBands; // Refs for the MsBandAndroidBridge.cs script private String gameObject; // region Multi-Plugin Methods /////////////////////////////// // Instance of this script private static MsBandManager bandManager; public Context context; public Activity activity; public UnityPlayer unityPlayer; /** * Constructor */ public MsBandManager() { bandManager = this; } /** * Public static access for this script * @return this script instance */ public static MsBandManager bandManager() { if(bandManager == null) { bandManager = new MsBandManager(); } return bandManager; } /////////////////////////////// /** * Method to set the context via unity * @param context */ public void setContext(Context context) { this.context = context; this.activity = (Activity) context; } /** * Method to set the player via unity * @param player */ public void setUnityPlayer(UnityPlayer player) { this.unityPlayer = player; } /** * Method to set the activity via unity * @param activity */ public void setActivity(Activity activity) { this.activity = activity; } /////////////////////////////// // endregion Multi-Plugin Methods /** * Method that acts to initialise the plugin */ public void initialisePlugin() { getPairedDevices(); if(pairedDevices == null || pairedDevices.length == 0) { System.err.println("There are no MsBands paired to this device!"); // showToast("There are no MsBands paired to this device!"); return; } } /** * Method used to get a list of band devices paired with * the mobile device. */ public void getPairedDevices() { try { pairedDevices = BandClientManager.getInstance().getPairedBands(); clients = new BandClient[pairedDevices.length]; UnityPlayer.UnitySendMessage( "MsBandManager", "ThrowDeviceListUpdateEvent", getStringDeviceList() ); } catch (Exception ex) { System.err.println("Failed to get paired devices!" + ex.getMessage()); } } // region Detail Methods // endregion Detail Methods // region Connect Bands /** * Method to allow the connection of a named band via unity and or android * @param name */ public void connectToNamedBand(String name) { int id = getDeviceIdFromName(name); if(id == -1) { String error = "1,"+ "There are no bands paired with the given name!"; System.err.println(error); UnityPlayer.UnitySendMessage( "MsBandManager", "ThrowBandErrorEvent", error ); } else { connectToPairedBand(id); } } /** * Method to get the id of a band within pairedDevices via its name. * This value will directly correspond to that of the clients list. * @param name ...String of the name of the band to find * @return int value of the bands position within pairedDevices. */ public int getDeviceIdFromName(String name) { // Check to see that there are some bands paired if(pairedDevices.length == 0) { System.err.println("There are no bands paired with the device!"); // showToast("There are no bands paired with the device!"); return -1; } // Loop through the paired devices and try to match them // against the desired name. for (int i = 0; i < pairedDevices.length; i++) { String bandName = pairedDevices[i].getName(); if(bandName.equals(name)) { // we have found the band so return return i; } } // We have not found the band so return a null value System.err.println("Failed to find band: " + name); return -1; } /** * Method to get the id of a band within pairedDevices via its mac. * This value will directly correspond to that of the clients list. * @param address ...String of the band mac to find * @return int value of the bands position within pairedDevices. */ public int getDeviceIdFromMac(String address) { // Check to see that there are some bands paired if(pairedDevices.length == 0) { System.err.println("There are no bands paired with the device!"); // showToast("There are no bands paired with the device!"); return Integer.parseInt(null); } // Loop through the paired devices and try to match them // against the desired name. for (int i = 0; i < pairedDevices.length; i++) { String bandMac = pairedDevices[i].getMacAddress(); if(bandMac.equals(address)) { // we have found the band so return return i; } } // We have not found the band so return a null value System.err.println("Failed to find band: " + address); return Integer.parseInt(null); } /** * Method to allow the connection of all bands paired to the device */ public void connectToPairedBands() { // Check to see that there are some bands paired if(pairedDevices.length == 0) { System.err.println("There are no bands paired with the device!"); // showToast("There are no bands paired with the device!"); return; } // Try and connect to each of the paired devices for (int i = 0; i < pairedDevices.length; i++) { new connectBandTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, i); } } /** * Method to allow the connection of a specific band paired to the device * given its id within the clients list. * @param id ...the id of the band to connect to. */ public void connectToPairedBand(int id) { // Check to see that there are some bands paired if(pairedDevices.length == 0) { System.err.println("There are no bands paired with the device!"); // showToast("There are no bands paired with the device!"); return; } // Try and connect to each of the paired devices new connectBandTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, id); } /** * Method to allow the disconnection of all bands paired to the device * given its id within the clients list. */ public void disconnectFromAllBands() { // Check to see that there are some bands paired if(pairedDevices.length == 0) { System.err.println("There are no bands paired with the device!"); // showToast("There are no bands paired with the device!"); return; } // Try and connect to each of the paired devices for (int i = 0; i < pairedDevices.length; i++) { new disconnectBandTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, i); } } /** * Method to allow the disconnection of a specific band paired to the device * given its id within the clients list. * @param id ...the id of the band to connect to. */ public void disconnectFromPairedBand(int id) { // Check to see that there are some bands paired if(pairedDevices.length == 0) { System.err.println("There are no bands paired with the device!"); // showToast("There are no bands paired with the device!"); return; } new disconnectBandTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,id); } /** * Method that allows for the connection of a specific band given its id within * the clients list. * @param id ...the id of the band to connect to. * @return boolean indexLevel of connection * @throws InterruptedException * @throws BandException */ private boolean getConnectedBandClient(int id) throws InterruptedException, BandException { System.out.println("Getting client for band[" + id + "]"); if(clients[id] == null) { clients[id] = BandClientManager.getInstance().create(this.context, pairedDevices[id]); } else if (ConnectionState.CONNECTED == clients[id].getConnectionState()) { return true; } return ConnectionState.CONNECTED == clients[id].connect().await(); } /** * Overridden IBandCommunication interface function that allows access * to the bandConnected event. * @param id */ @Override public void bandConnected(int id) { // msBands[id].connected = true; UnityPlayer.UnitySendMessage( "MsBandManager", "ThrowConnectedBandEvent", String.valueOf(id) ); } /** * Overridden IBandCommunication interface function that allows access * to the bandNotConnected event. * @param id */ @Override public void bandNotConnected(int id) { // msBands[id].connected = false; UnityPlayer.UnitySendMessage( "MsBandManager", "ThrowNotConnectedBandEvent", String.valueOf(id) ); } private class disconnectBandTask extends AsyncTask<Integer, Void, Integer> { @Override protected Integer doInBackground(Integer... params) { int id = params[0]; // Double-check that we have a clients list to work with if(clients == null) return id; if(msBands == null) return id; try { if (getConnectedBandClient(id)) { // Yup we are connected System.out.println("Band[" + id + "] is connected!"); // disable all sensors msBands[id].disableAllSensors(); // disconnect from the band clients[id].disconnect(); // wipe the band msBands[id] = null; // throw a not connected event bandNotConnected(id); } else { bandNotConnected(id); System.err.println("Band[" + id + "] is not connected. Please make sure bluetooth is on and the band is in range!"); return id; } } catch (BandException ex) { System.err.println("BE " + ex.getMessage()); // showToast(ex.getMessage()); return id; } catch (Exception ex) { System.err.println("E " + ex.getMessage()); // showToast(ex.getMessage()); return id; } return id; } } /** * AsyncTask that facilitates the connection of MSBands */ private class connectBandTask extends AsyncTask<Integer, Void, Integer> { @Override protected Integer doInBackground(Integer... params) { int id = params[0]; // Double-check that we have a clients list to populate if(clients == null) clients = new BandClient[pairedDevices.length]; if(msBands == null) msBands = new MsBand[pairedDevices.length]; try { if (getConnectedBandClient(id)) { // Yup we are connected System.out.println("Band[" + id + "] is connected!"); // Initialise the band msBands[id] = new MsBand(clients[id], bandManager); // Set the bands id msBands[id].bandId = id; // Enable all sensors // msBands[id].enableAllSensors(); } else { bandNotConnected(id); System.err.println("Band[" + id + "] is not connected. Please make sure bluetooth is on and the band is in range!"); return -1; } } catch (BandException ex) { System.err.println("BE " + ex.getMessage()); // showToast(ex.getMessage()); return -1; } catch (Exception ex) { System.err.println("E " + ex.getMessage()); // showToast(ex.getMessage()); return -1; } return id; } /** * Method called on completion of the connection task * @param result the id of the connected band */ @Override protected void onPostExecute(Integer result) { // If we have a -1 value then the connection has failed if(result == -1) return; // Apply the result via the following method call bandConnected(result); } } // endregion Connect Bands /** * Method to enable all the sensors on a given band * @param id the band to apply sensor enable to */ public void enableAllSensors(int id) { try { msBands[id].enableAllSensors(); } catch (Exception ex) { System.err.println("Failed to enable sensors: Band[" + id + "]!"); } } /** * Method to disable all the sensors on a given band * @param id the band to apply sensor enable to */ public void disableAllSensors(int id) { try { msBands[id].disableAllSensors(); } catch (Exception ex) { System.err.println("Failed to disable sensors: Band[" + id + "]!"); } } /** * Method to enable defined sensors on a given band * @param id the band to apply sensor enable to * @param sensors the sensors to enable */ public void enableNamedSensors(int id, String[] sensors) { try { msBands[id].enableDisableNamedSensors(sensors, true); } catch (Exception ex) { System.err.println("Failed to enable sensors: Band[" + id + "]!"); } } /** * Method to disable defined sensors on a given band * @param id the band to apply sensor disable to * @param sensors the sensors to disable */ public void disableNamedSensors(int id, String[] sensors) { try { msBands[id].enableDisableNamedSensors(sensors, false); } catch (Exception ex) { System.err.println("Failed to enable sensors: Band[" + id + "]!"); } } // region Unity Function Calls /** * Method used to get a string list of devices * @return */ public String getStringDeviceList() { String deviceList = ""; for (BandInfo info : pairedDevices) { deviceList += info.getName(); deviceList += ","; } return deviceList; } /** * Method used to get the details of a specific band identified via its id * @param id the id of the band to poll * @return comma separated string detailing both the hardware and firmware * versions. */ public String getBandDetails(int id) { if(msBands != null && msBands[id] != null) { return msBands[id].hwVersion + "," + msBands[id].fwVersion; } else { return null; } } /** * Method for creating a tile on the band * !Not implemented for this release! * @param id id of the band on which the tile is to be created */ public void createUnityTile(int id) { if(msBands != null && msBands[id] != null) { msBands[id].createTile(); } } // region Haptic Triggers /** * Method that allows for the triggering of haptic events via unity * @param id id of the band to trigger * @param vibration the name of the vibration to be triggered */ public void triggerHapticEvent(int id, String vibration) { if(msBands != null && msBands[id] != null) { msBands[id].triggerHapticEvent(vibration); } } /** * Method that allows for the triggering of haptic events via unity * @param id the band to trigger * @param value the value to be triggered */ public void triggerHapticValue(int id, String value) { if(msBands != null && msBands[id] != null) { msBands[id].triggerHapticValue(value); } } // endregion Haptic Triggers // endregion Unity Function Calls /** * Method to alow for toasts just in case :) * @param message */ public void showToast(final String message) { Toast.makeText(this.context, message, Toast.LENGTH_SHORT).show(); } }
/** */ package iso20022; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Data Type</b></em>'. * <!-- end-user-doc --> * * <!-- begin-model-doc --> * Representation of a set of values without identity. * <!-- end-model-doc --> * * * @see iso20022.Iso20022Package#getDataType() * @model abstract="true" * @generated */ public interface DataType extends TopLevelDictionaryEntry, BusinessElementType, LogicalType { } // DataType
package com.company.project.other.fgmc; import com.alibaba.fastjson.JSONObject; import com.company.project.utils.GsonUtil; import com.company.project.utils.ResourcePath; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.core.io.ClassPathResource; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.util.List; /** * Title: * Description: * Company: 北京华宇元典信息服务有限公司 * * @author zhangjing * @version 1.0 * @date 2018-11-05 14:09 */ public class Json2ListUtil { public static void main(String[] args) { Json2ListUtil.json2list(); } public static void json2list() { ClassPathResource resource1 = new ClassPathResource("files/chlTitle.txt"); ClassPathResource resource2 = new ClassPathResource("files/larTitle.txt"); try { InputStream inputStream1 = resource1.getInputStream(); InputStream inputStream2 = resource2.getInputStream(); // toFile("files/flmc_chl.txt", inputStream1); toFile("files/flmc_lar.txt", inputStream2); System.out.println("结束"); } catch (IOException e) { e.printStackTrace(); } } public static void toFile(String path, InputStream is) throws IOException { JsonBean bean = GsonUtil.fromJson(IOUtils.toString(is), JsonBean.class); List<JsonBean.DataBean> data = bean.getData(); for (JsonBean.DataBean datum : data) { String title = datum.getTitle(); if (StringUtils.isNotEmpty(title)) { FileUtils.writeStringToFile(new File(ResourcePath.getClassPath() + path), title + System.getProperty("line.separator"), "utf-8", true); } } } }
package utils; import gui.ComponentTools; import gui.comp.ProgressBar; import gui.tree.AutoTree; import java.awt.BorderLayout; import java.awt.Component; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.util.HashMap; import java.util.Map; import javax.swing.JFrame; import javax.swing.JMenuBar; import javax.swing.JOptionPane; import state.ComponentEnabler; import state.StateModel; import db.SQL; // TBD: state handler public abstract class Application implements Runnable { private String appName; private String version; private Config config; private AutoTree warnings; private SQL sql; private JMenuBar menus; private Map<Object, Component> components = new HashMap<Object, Component>(); private JFrame frame; private ProgressBar progress; private StateModel stateModel; private ComponentEnabler enabler; public Application (final String appName, final String configDir, final String version, final String[] args) { this.appName = appName; this.version = version; config = new Config(configDir + "/options.txt"); if (args != null) config.setArguments (args); warnings = new AutoTree(); warnings.setSeparator (":"); progress = new ProgressBar(); stateModel = new StateModel(); enabler = new ComponentEnabler (stateModel); } protected void add (final Component comp, final Object constraints) { if (constraints == BorderLayout.SOUTH) System.out.println ("Warning: SOUTH will be replaced with a ProgressBar!"); if (frame == null) components.put (constraints, comp); else frame.add (comp, constraints); } protected void setMenus (final JMenuBar menus) { this.menus = menus; } protected void open() { String title = appName + " (version " + version + ")"; frame = ComponentTools.open (title, components.get (BorderLayout.NORTH), components.get (BorderLayout.CENTER), progress, components.get (BorderLayout.WEST), components.get (BorderLayout.EAST)); if (menus != null) frame.setJMenuBar (menus); frame.addWindowListener (new WindowAdapter() { @Override public void windowClosing (final WindowEvent e) { close(); } }); stateModel.fireStateChanged(); } protected void close() { if (sql != null) sql.close(); } public JFrame getFrame() { return frame; } public Config getConfig() { return config; } public AutoTree getWarnings() { return warnings; } public ProgressBar getProgress() { return progress; } public void run() { try { progress.setIndeterminate (true); process(); } catch (Throwable x) { x.printStackTrace (System.err); while (x.getCause() != null) x = x.getCause(); progress.setIndeterminate (false); String trace = Utils.getExceptionText (x); JOptionPane.showMessageDialog (frame, trace, appName, JOptionPane.ERROR_MESSAGE, null); } } public void setConnection (final SQL sql) { this.sql = sql; } public SQL getConnection() { return sql; } protected void process() throws Exception { warnings.clear(); // sub-classes may or may not want to do this here } public StateModel getStateModel() { return stateModel; } public void enableWhen (final Component comp, final String... enabled) { enabler.enableWhen (comp, enabled); } public void disableWhen (final Component comp, final String... disabled) { enabler.disableWhen (comp, disabled); } public void updateState (final String state, final boolean active) { stateModel.updateState (state, active); } protected void showProperties() { ComponentTools.showProperties (frame); } }
//package com.tdr.registration.view; // //import android.content.Context; //import android.graphics.Color; //import android.view.View; // // //import com.parry.pickerview.builder.TimePickerBuilder; //import com.parry.pickerview.listener.OnTimeSelectListener; //import com.parry.pickerview.view.TimePickerView; //import com.tdr.registration.utils.TimeUtil; // //import java.text.SimpleDateFormat; //import java.util.Calendar; //import java.util.Date; //import java.util.List; // // ///** // * @author parry // * @time 2017/6/7/007 14:20 // * @des ${TODO} // */ // //public class CustomTimeDialog { // // private TimePickerView pvTime; // // // public CustomTimeDialog(Context context) { // // initPickView(context,true); // } // // /** // * @param context // * @param isShowHour 是否显示时分秒 // */ // public CustomTimeDialog(Context context,boolean isShowHour) { // // initPickView(context,isShowHour); // } // // private void initPickView(Context context, final boolean isShowHour) { // Calendar selectedDate = Calendar.getInstance(); // Calendar startDate = Calendar.getInstance(); // //startDate.set(2013,1,1); // Calendar endDate = Calendar.getInstance(); // //endDate.set(2020,1,1); // // int year = TimeUtil.getYear(); // int month = TimeUtil.getMonth()-1; // int day = TimeUtil.getDay(); // int hour = TimeUtil.getHour(); // int minute = TimeUtil.getMinute(); // int second = TimeUtil.getSecond(); // //正确设置方式 原因:注意事项有说明 // startDate.set(2000, 0, 1); //// endDate.set(year, month, day,hour,minute,second); // // pvTime = new TimePickerBuilder(context, new OnTimeSelectListener() { // @Override // public void onTimeSelect(Date date, View v) {//选中事件回调 // onItemClickListener.onCustomDialogClickListener(dateToString(date,isShowHour)); // } // }) // .setType(new boolean[]{true, true, true, isShowHour, isShowHour, isShowHour})// 默认全部显示 // .setCancelText("取消")//取消按钮文字 // .setSubmitText("确定")//确认按钮文字 // .setTitleSize(20)//标题文字大小 // .setTitleText("")//标题文字 // .setOutSideCancelable(false)//点击屏幕,点在控件外部范围时,是否取消显示 // .isCyclic(false)//是否循环滚动 // .setTitleColor(Color.LTGRAY)//标题文字颜色 // .setSubmitColor(Color.BLACK)//确定按钮文字颜色 // .setCancelColor(Color.BLACK)//取消按钮文字颜色 // .setTitleBgColor(Color.LTGRAY)//标题背景颜色 Night mode // .setBgColor(0xFFF1F1F5)//滚轮背景颜色 Night mode // .setDate(selectedDate)// 如果不设置的话,默认是系统时间*/ // .setRangDate(startDate, endDate)//起始终止年月日设定 // .setLabel("-", "-", "", ":", ":", "")//默认设置为年月日时分秒 // .isCenterLabel(true) //是否只显示中间选中项的label文字,false则每项item全部都带有label。 // .isDialog(false)//是否显示为对话框样式 // .build(); // } // // // formatType格式为yyyy-MM-dd HH:mm:ss//yyyy年MM月dd日 HH时mm分ss秒 // // data Date类型的时间 // public static String dateToString(Date data,boolean isShowHour) { // String formatType; // if(isShowHour){ // formatType = "yyyy-MM-dd HH:mm:ss"; // }else { // formatType = "yyyy-MM-dd"; // } // SimpleDateFormat simpleDateFormat = new SimpleDateFormat(formatType); // return simpleDateFormat.format(data); // } // // public void showDialog() { // if (pvTime != null && !pvTime.isShowing()) { // pvTime.show(); // } // // } // // // OnItemClickListener onItemClickListener; // // // public void setOnCustomClickListener(OnItemClickListener onItemClickListener) { // this.onItemClickListener = onItemClickListener; // } // // public interface OnItemClickListener { // void onCustomDialogClickListener(String value); // } // // //}
/** * Created by owen on 2017/6/13. */ public class StaticSingleton { /** * 使用静态内部类实现的单例模式 */ public static StaticSingleton getInstance(){return Inner.INSTANCE;} private StaticSingleton(){} private static class Inner{ final static StaticSingleton INSTANCE = new StaticSingleton(); } }
package com.wipro.stringstringbuffer; public class Ex10 { public static void main(String[] args) { // TODO Auto-generated method stub String[] s=args[0].split(","); String nstr=""; if(!s[0].equals("")) { String str=s[0]; int len=str.length(); int c=Integer.parseInt(s[1]); for(int i=1;i<=c;i++) nstr=nstr+str.substring(len-c); } System.out.println(nstr); } }
package com.apecoder.apollo.service.impl; import com.apecoder.apollo.domain.CommentArticleEntity; import com.apecoder.apollo.mapper.CommentMapper; import com.apecoder.apollo.service.CommentService; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentArticleEntity> implements CommentService { @Autowired CommentMapper articleMapper; public List<CommentArticleEntity> getCommentsByArticleId(Integer articleId, Page page) { IPage<CommentArticleEntity> iPage = articleMapper.selectPage(page, Wrappers.query(new CommentArticleEntity()).eq(CommentArticleEntity::getArticleId, articleId).orderByDesc(CommentArticleEntity::getUpdateDate) ); return iPage.getRecords(); } }
/* * Created on Mar 18, 2007 * * * Window - Preferences - Java - Code Style - Code Templates */ package com.citibank.ods.persistence.pl.dao; import com.citibank.ods.entity.pl.BaseTplProdSubFamlPrvtEntity; /** * @author leonardo.nakada * * * Preferences - Java - Code Style - Code Templates */ public interface BaseTplProdSubFamlPrvtDAO { public BaseTplProdSubFamlPrvtEntity find( BaseTplProdSubFamlPrvtEntity baseTplProductFamilyPrvtEntity_ ); public BaseTplProdSubFamlPrvtEntity findByProdCode(String prodPk); }
package com.gen.serve; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import javax.servlet.RequestDispatcher; 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 ModifyShipment */ @WebServlet("/ModifyShipment") public class ModifyShipment extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public ModifyShipment() { 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 response.getWriter().append("Served at: ").append(request.getContextPath()); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub response.setContentType("text/number/html"); PrintWriter pw = response.getWriter(); Connection conn = null; String url = "jdbc:mysql://localhost:3306/"; String dbName = "world"; String driver = "com.mysql.jdbc.Driver"; try{ String Tracking_ID= request.getParameter("TrackingID"); String Item=request.getParameter("Item"); String No_of_packages=request.getParameter("NoofPackages"); String Packaging_type=request.getParameter("Packagingtype"); String Package_Declared_Value=request.getParameter("PackageDeclaredValue"); String SCity=request.getParameter("Scity"); String DCity=request.getParameter("Dcity"); //To address String Company_or_name=request.getParameter("CompanyorName"); String Contact=request.getParameter("Contact"); String Address_line1=request.getParameter("Addressline1"); String Address_line2=request.getParameter("Addressline2"); String zipcode=request.getParameter("Zipcode"); String Email=request.getParameter("Email"); String Country=request.getParameter("Country"); //From address String from_Company_or_name=request.getParameter("from_CompanyorName"); String from_Contact=request.getParameter("from_Contact"); String from_Address_line1=request.getParameter("from_Addressline1"); String from_Address_line2=request.getParameter("from_Addressline2"); String from_zipcode=request.getParameter("from_Zipcode"); String from_Email=request.getParameter("from_Email"); String from_Country=request.getParameter("from_Country"); String radio=request.getParameter("radio"); Class.forName(driver).newInstance(); conn=DriverManager.getConnection(url+dbName, "root","1415"); String sql = "update Shipment_Creation set Item='"+ Item +"', No_of_packages='"+No_of_packages+"', Packaging_type='"+Packaging_type+"', " + "Package_Declared_Value='"+Package_Declared_Value+"', SCity='"+SCity+"', DCity='"+DCity+"', to_Company_or_name='"+Company_or_name+"'," + "to_Address_line1='"+Address_line1+"', to_Contact='"+Contact+"', to_Address_line2='"+Address_line2+"', to_zipcode='"+zipcode+"'," + "to_Email='"+Email+"', to_Country='"+Country+"', from_Company_or_name='"+from_Company_or_name+"', from_Contact='"+from_Contact+"'," + "from_Address_line1='"+from_Address_line1+"', from_Address_line2= '"+from_Address_line2+"', from_zipcode='"+from_zipcode+"'," + "from_Email='"+from_Email+"',from_Country='"+from_Country+"',radio='"+radio+"' where TrackingID='"+Tracking_ID+"'"; Statement st = conn.createStatement(); st.executeUpdate(sql); RequestDispatcher RequetsDispatcherObj1 =request.getRequestDispatcher("/agenthome2.jsp"); RequetsDispatcherObj1.forward(request, response); } catch (Exception e) { pw.println(e); } } }
package com.legaoyi.protocol.up.messagebody; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; import com.fasterxml.jackson.annotation.JsonProperty; import com.legaoyi.protocol.message.MessageBody; /** * 上传终端音视频属性 * * @author <a href="mailto:shengbo.gao@gmail.com;78772895@qq.com">gaoshengbo</a> * @version 1.0.0 * @since 2018-04-09 */ @Scope("prototype") @Component(MessageBody.MESSAGE_BODY_BEAN_PREFIX + "1005_2016" + MessageBody.MESSAGE_BODY_BEAN_SUFFIX) public class JTT1078_1005_MessageBody extends MessageBody { private static final long serialVersionUID = 1L; public static final String MESSAGE_ID = "1005"; /** 起始时间 **/ @JsonProperty("startTime") private String startTime; /** 结束时间 **/ @JsonProperty("endTime") private String endTime; /** 上车人数 **/ @JsonProperty("inCar") private int inCar; /** 下车人数 **/ @JsonProperty("offCar") private int offCar; public final String getStartTime() { return startTime; } public final void setStartTime(String startTime) { this.startTime = startTime; } public final String getEndTime() { return endTime; } public final void setEndTime(String endTime) { this.endTime = endTime; } public final int getInCar() { return inCar; } public final void setInCar(int inCar) { this.inCar = inCar; } public final int getOffCar() { return offCar; } public final void setOffCar(int offCar) { this.offCar = offCar; } }
package com.example.fileshare.model; import org.hibernate.annotations.OnDelete; import org.hibernate.annotations.OnDeleteAction; import javax.persistence.*; import java.util.Set; @Entity public class Order { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id; @ManyToOne @JoinColumn(name = "user_id") @OnDelete(action = OnDeleteAction.CASCADE) private User buyer; @ManyToOne @JoinColumn(name = "user_id") @OnDelete(action = OnDeleteAction.CASCADE) private Product product; @Column private Integer quantity; //TODO: map list of products to list of quantities private OrderState orderState = OrderState.PLACED; public Order(User buyer, Product product, Integer quantity) { this.buyer = buyer; this.product = product; this.quantity = quantity; } public User getBuyer() { return buyer; } public Product getProduct() { return product; } public Integer getQuantity() { return quantity; } public OrderState getOrderState() { return orderState; } public void setOrderState(OrderState orderState) { this.orderState = orderState; } }
package first.improve.递增的三元子序列; public class SolutionC { public boolean increasingTriplet(int[] nums) { // 设置两个变量first, second存储最小值与中间值 // 之后扫描数组 // 当有遇到数组中数num, 其有num < first时, 则first = num // 当有遇到数组中数num, 其有first < num < second时, 则second = num // 当有遇到数组中数num, 其有second < num时, 意味着三元子序列存在,返回true // 这种更新方式不会打破旧有的first与second大小关系, 只会加强 // 即如果新出现的数(third)比之前的数大, 那么他一定比现在存储的first与second也大 int fisrt = Integer.MAX_VALUE; int second = Integer.MAX_VALUE; for (int num : nums) { if (num < fisrt) { // 更新first fisrt = num; }else if (fisrt < num && num < second) { second = num; }else if (second < num) return true; } return false; } public static void main(String[] args) { // int[] testNums = {1, 2, 3, 4, 5}; // int[] testNums = {5, 4, 3, 2, 1}; int[] testNums = {2, 5, 1, 3, 4}; boolean hasIncrease = new SolutionC().increasingTriplet(testNums); System.out.println(hasIncrease); } }
package Task2; public interface Men_Clothes { public void WearMen(); }
package com.serotonin.modbus4j.serial.rtu; import com.serotonin.io.messaging.MessageRequest; import com.serotonin.io.messaging.MessageResponse; import com.serotonin.modbus4j.base.BaseMessageParser; import com.serotonin.util.queue.ByteQueue; /** * Message parser implementation for RTU encoding. Primary reference for the ordering of CRC bytes. Also * provides handling of incomplete messages. * @author mlohbihler */ public class RtuMessageParser extends BaseMessageParser { private boolean reverseCRC; public RtuMessageParser(boolean reverseCRC) { this.reverseCRC = reverseCRC; } protected MessageResponse parseResponseImpl(ByteQueue queue) throws Exception { return RtuMessageResponse.createRtuMessageResponse(queue, reverseCRC); } protected MessageRequest parseRequestImpl(ByteQueue queue) throws Exception { return RtuMessageRequest.createRtuMessageRequest(queue, reverseCRC); } }
package com.weiziplus.springboot.common.utils.token; import io.jsonwebtoken.Claims; import io.jsonwebtoken.Jwts; import io.jsonwebtoken.SignatureAlgorithm; import javax.servlet.http.HttpServletRequest; import java.util.Date; /** * JwtToken * * @author wanglongwei * @data 2019/5/7 9:50 */ public class JwtTokenUtil { /** * 发行人 */ private static final String ISSUER = "WeiziPlus"; /** * 加密方式 */ private static final SignatureAlgorithm HS512 = SignatureAlgorithm.HS512; /** * 秘钥 */ private static final String SECRET = "weiziplus"; /** * 过期时间--30天过期 */ private static final long EXPIRATION = 1000L * 60 * 60 * 24 * 30; /** * 根据用户id和用户类型创建token * * @param userId * @return * @throws Exception */ public static String createToken(Long userId, String audience) throws Exception { return Jwts.builder() .setIssuer(ISSUER) .setAudience(audience) .signWith(HS512, SECRET) .setSubject(String.valueOf(userId)) .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION)) .setIssuedAt(new Date()) .compact(); } /** * 根据token判断是否失效 * * @param token * @return * @throws Exception */ public static Boolean isExpiration(String token) throws Exception { return getTokenBody(token).getExpiration().before(new Date()); } /** * 根据token获取token中的信息 * * @param token * @return */ private static Claims getTokenBody(String token) { return Jwts.parser() .setSigningKey(SECRET) .parseClaimsJws(token) .getBody(); } /** * 根据token获取用户Audience * * @param token * @return */ public static String getUserAudienceByToken(String token) { return getTokenBody(token).getAudience(); } /** * 根据token获取用户id * * @param token * @return */ public static Long getUserIdByToken(String token) { return Long.valueOf(getTokenBody(token).getSubject()); } /** * 根据request获取用户id * * @param request * @return */ public static Long getUserIdByHttpServletRequest(HttpServletRequest request) { return getUserIdByToken(request.getHeader("token")); } }
package com.example.young.mymusicplayer.Activity; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.content.pm.PackageManager; import android.media.AudioManager; import android.media.MediaPlayer; import android.os.Bundle; import android.os.Handler; import android.os.IBinder; import android.support.annotation.Nullable; import android.support.v4.app.ActivityCompat; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import com.example.young.mymusicplayer.Service.MusicService; import com.example.young.mymusicplayer.Adapter.MusicAdapter; import com.example.young.mymusicplayer.R; import com.example.young.mymusicplayer.Bean.Song; import com.example.young.mymusicplayer.Utils.MusicUtils; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; /** * Created by Young on 2017/12/22. */ public class MusicActivity extends AppCompatActivity { private MusicService service; private Handler handler=new Handler(); private ListView myListView; private List<Song> list; private MusicService.MyBinder binder; private MusicAdapter adapter; private Button play, next, pre; private SeekBar seekBar; private TextView currenttime, totaltime; private Song song; private int currentPosition=0 ; private Intent intent; private static final int REQUEST_EXTERNAL_STORAGE = 1; private static String[] PERMISSIONS_STORAGE = { "android.permission.READ_EXTERNAL_STORAGE", "android.permission.WRITE_EXTERNAL_STORAGE"}; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.musictab); MusicActivity.verifyStoragePermissions(this); initView(); initCompent(); seekBar.setMax(0); intent=new Intent(this,MusicService.class); bindService(intent,serviceConnection,BIND_AUTO_CREATE); play.setBackgroundResource(R.drawable.btn_audio_play_normal); play.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if(currentPosition==0){ service.playMusic(list.get(0)); } if(!service.isPause()) { service.pause(); play.setBackgroundResource(R.drawable.selector_audio_btn_play); }else { service.resume(); play.setBackgroundResource(R.drawable.selector_audio_btn_pause); } } }); next.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { next(); } }); pre.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { pre(); } }); } public void pre(){ currentPosition--; if(currentPosition<0){ Toast.makeText(this,"已经是第一首了",Toast.LENGTH_LONG).show(); } else if(service.isPause()) { service.playMusic(list.get(currentPosition)); play.setBackgroundResource(R.drawable.selector_audio_btn_pause); } else{ service.playMusic(list.get(currentPosition)); } } public void next() { currentPosition++; if(currentPosition+1>list.size()){ Toast.makeText(this,"已经是最后一首了",Toast.LENGTH_LONG).show(); } else if (service.isPause()){ service.playMusic(list.get(currentPosition)); play.setBackgroundResource(R.drawable.selector_audio_btn_pause); } else { service.playMusic(list.get(currentPosition)); } } public void initView() { myListView = (ListView) findViewById(R.id.listview); list = new ArrayList<>(); list = MusicUtils.getMusicData(this); adapter = new MusicAdapter(this, list); myListView.setAdapter(adapter); myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { currentPosition = i; song=list.get(currentPosition); totaltime.setText(MusicUtils.formatTime(song.getDuration())); seekBar.setMax(song.getDuration()); service.playMusic(song); play.setBackgroundResource(R.drawable.selector_audio_btn_pause); } }); } public static void verifyStoragePermissions(AppCompatActivity appCompatActivity) { try { //检测是否有读的权限 int permission = ActivityCompat.checkSelfPermission(appCompatActivity, "android.permission.READ_EXTERNAL_STORAGE"); if (permission != PackageManager.PERMISSION_GRANTED) { // 没有读的权限,去申请读的权限,会弹出对话框 ActivityCompat.requestPermissions(appCompatActivity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE); } } catch (Exception e) { e.printStackTrace(); } } ServiceConnection serviceConnection=new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { binder=(MusicService.MyBinder)iBinder; service=binder.getService(); seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int i, boolean b) { if(b==true){//此处一定要判断是否是用户改变的进度条进度 service.seekToPosition(seekBar.getProgress()); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); handler.post(seekBartime); } @Override public void onServiceDisconnected(ComponentName componentName) { service=null; } }; private void initCompent(){ play = (Button) findViewById(R.id.play); next = (Button) findViewById(R.id.next); pre = (Button) findViewById(R.id.pre); seekBar = (SeekBar) findViewById(R.id.seekbar); currenttime = (TextView) findViewById(R.id.currenttime); totaltime = (TextView) findViewById(R.id.totaltime); } Runnable seekBartime=new Runnable() { @Override public void run() { seekBar.setProgress(service.getPlayPosition()); currenttime.setText(MusicUtils.formatTime(service.getPlayPosition())); handler.postDelayed(seekBartime,1000); } }; @Override protected void onDestroy() { super.onDestroy(); } }
package com.designurway.idlidosa.a.model; import com.google.gson.annotations.SerializedName; public class AddressModel { private String status; private String name; private String phone; private String pin_code; private String office_pin_code; @SerializedName("home_address") private String homeAddress; @SerializedName("other_address") private String otherAddress; public AddressModel(String status, String name, String phone, String pin_code, String office_pin_code, String homeAddress, String otherAddress) { this.status = status; this.name = name; this.phone = phone; this.pin_code = pin_code; this.office_pin_code = office_pin_code; this.homeAddress = homeAddress; this.otherAddress = otherAddress; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getPin_code() { return pin_code; } public void setPin_code(String pin_code) { this.pin_code = pin_code; } public String getOffice_pin_code() { return office_pin_code; } public void setOffice_pin_code(String office_pin_code) { this.office_pin_code = office_pin_code; } public String getHomeAddress() { return homeAddress; } public void setHomeAddress(String homeAddress) { this.homeAddress = homeAddress; } public String getOtherAddress() { return otherAddress; } public void setOtherAddress(String otherAddress) { this.otherAddress = otherAddress; } }
package com.flavio.android.petlegal.view; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.Toast; import com.flavio.android.petlegal.R; import com.flavio.android.petlegal.controll.ControlaTelefone; import com.flavio.android.petlegal.model.Telefone; public class TesteMVCTelefone extends AppCompatActivity { Button btnConsultar, btnInserir,btnAtualizar,btnDeletar; ControlaTelefone ct; Telefone telefone; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate ( savedInstanceState ); setContentView ( R.layout.activity_teste_mvctelefone ); btnConsultar = (Button)findViewById ( R.id.btnConsultarPetMVC ) ; btnInserir = (Button) findViewById ( R.id.btnInserirPetMVC ); btnAtualizar = (Button)findViewById ( R.id.btnAtualizarPetMVC ); btnDeletar = (Button)findViewById ( R.id.btnDeletarPetMVC ) ; ct = new ControlaTelefone ( getApplicationContext () ); telefone = new Telefone (-1,-1,1,58585858 ); btnConsultar.setOnClickListener ( new View.OnClickListener () { @Override public void onClick(View view) { if(ct.consultarTelefone ( telefone ).getNumeroTel () == telefone.getNumeroTel ()){ telefone = ct.consultarTelefone ( telefone ); sendMessage ( "Telefone consultado 58585858" ); }else sendMessage ( "Telefone 58585858 não existe" ); } } ); btnInserir.setOnClickListener ( new View.OnClickListener () { @Override public void onClick(View view) { if(ct.consultarTelefone ( telefone ).getNumeroTel () != telefone.getNumeroTel ()) { if (ct.inserirTelefone ( telefone )) { sendMessage ( "Telefone adicionado 58585858" ); } else sendMessage ( "Telefone não foi adicionado" ); }else sendMessage ( "Telefone 58585858 já existe" ); } } ); btnAtualizar.setOnClickListener ( new View.OnClickListener () { @Override public void onClick(View view) { Telefone atualizado = new Telefone(telefone.getIdTel (),-1,1,12121212); if(ct.atualizarTelefone ( atualizado )){ sendMessage ( "Telefone Atualizado 12121212" ); }else sendMessage ( "Náo existe o telefone 58585858" ); } } ); btnDeletar.setOnClickListener ( new View.OnClickListener () { @Override public void onClick(View view) { Telefone atualizado = new Telefone ( -1,-1,1,12121212 ); if(ct.deletaTelefone ( telefone )){ sendMessage ( "Telefone 12121212 Deletado" ); }else sendMessage ( "Telefone 12121212 não existe" ); } } ); } public void sendMessage(String texto){ Toast.makeText ( this, texto, Toast.LENGTH_SHORT ).show (); } }
package com.xinyuf.util; import android.content.Context; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.Locale; public class DateUtils { //2015年1月1日 00:00 public static String getFormatDate(Date date){ return new SimpleDateFormat("yyyy年MM月dd日 HH:mm").format(date); } }
package heylichen.alg.graph.structure.weighted.mst; import heylichen.alg.graph.structure.weighted.EdgeWeightedGraph; import heylichen.alg.graph.structure.weighted.WeightedEdge; import java.util.ArrayList; import java.util.List; import java.util.PriorityQueue; /** * @author lichen * @date 2020/4/8 15:43 * @desc */ public class LazyPrimMST implements MST { private EdgeWeightedGraph graph; private List<WeightedEdge> edges; private boolean marked[]; private static final int START_VERTEX = 0; private double weight; public LazyPrimMST(EdgeWeightedGraph graph) { this.graph = graph; init(); } private void init() { edges = new ArrayList<>(); marked = new boolean[graph.getVertexCount()]; PriorityQueue<WeightedEdge> weightedEdgesPQ = new PriorityQueue<>(); visitV(weightedEdgesPQ, START_VERTEX); while (!weightedEdgesPQ.isEmpty()) { WeightedEdge edge = weightedEdgesPQ.poll(); Integer unmarkedV = getUnmarkedVertex(edge); if (unmarkedV == null) { continue; } edges.add(edge); visitV(weightedEdgesPQ, unmarkedV); } calculateTotalWeight(); } private void visitV(PriorityQueue<WeightedEdge> weightedEdgesPQ, int v) { marked[v] = true; for (WeightedEdge weightedEdge : graph.getAdjacent(v)) { Integer theOtherV = weightedEdge.theOther(v); if (!marked[theOtherV]) { weightedEdgesPQ.add(weightedEdge); } } } private void calculateTotalWeight() { double totalWeight = 0d; for (WeightedEdge edge : edges) { totalWeight += edge.getWeight(); } this.weight = totalWeight; } private Integer getUnmarkedVertex(WeightedEdge edge) { Integer v = edge.either(); if (!marked[v]) { return v; } v = edge.theOther(v); if (!marked[v]) { return v; } else { return null; } } @Override public Iterable<WeightedEdge> edges() { return edges; } @Override public double weight() { return weight; } }
/** * Created by owen on 2017/6/14. */ public class FindNumberInTwoDArray { /** * 二维数组中数字从左到右,从上到下递增 * 给定一个数字,查找二维数组返回结果 */ public boolean find(int[][] a,int s){ //检查输入有效性 if (a==null) return false; int i = 0,j=a[i].length-1;//默认是矩形 while(i<a.length&&j>=0){ if (s<a[i][j])//去掉这一列 j=j-1; else if(s>a[i][j]) i=i+1;//去掉这一行 else return true; } return false; } }
package emp; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.*; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class LoginCheck extends HttpServlet { private static final long serialVersionUID = 1L; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out=response.getWriter(); int Emp_ID = Integer.parseInt(request.getParameter("id")),flag=0; String Password = request.getParameter("pwd"); try { Class.forName("com.mysql.jdbc.Driver"); Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/EmployeeDB","root","secret"); Statement s=con.createStatement(); String query="select * from Employee where EmpID='"+Emp_ID+"'"; ResultSet rs=s.executeQuery(query); while(rs.next()) { flag=1; if(Password.equals(rs.getString("Password"))) { flag=2; if(rs.getString("Did").equals("5")) { String fname=rs.getString("FirstName"); String lname=rs.getString("LastName"); String name=fname+" "+lname; HttpSession session=request.getSession(); session.setAttribute("AdminName",name); session.setAttribute("AdminID",Emp_ID); RequestDispatcher rd=request.getRequestDispatcher("AdminOptions.jsp"); rd.forward(request, response); } else { String fname=rs.getString("FirstName"); String lname=rs.getString("LastName"); String name=fname+" "+lname; HttpSession session=request.getSession(); session.setAttribute("Emp_Name",name); session.setAttribute("Emp_ID",Emp_ID); RequestDispatcher rd=request.getRequestDispatcher("Employeeoptions.jsp"); rd.forward(request, response); } break; } } if(flag==0) { RequestDispatcher rd=request.getRequestDispatcher("Login.jsp"); rd.include(request, response); out.println("<br><br><h3><center><font color=red>!!YOU ARE NOT REGISTERED.. CONTACT YOUR ADMIN!!</font></center></h3>"); } else if(flag==1) { RequestDispatcher rd=request.getRequestDispatcher("Login.jsp"); rd.include(request, response); out.println("<br><br><h3><center><font color=red>!!INVALID PASSWORD...TRY AGAIN!!</font></center></h3>"); } } catch(SQLException se) { se.printStackTrace(); } catch(Exception e) { out.println(e); e.printStackTrace(); } } }
package com.lumpofcode.collection.compare; import java.util.Comparator; /** * Created by emurphy on 10/21/15. */ public class DescendingComparator extends AscendingComparator implements Comparator<Comparable<Object>> { @Override public int compare(Comparable<Object> theValue, Comparable<Object> theOtherValue) { return super.compare(theValue, theOtherValue) * -1; // invert } }
package com.stratumn.sdk.model.misc; import java.util.function.Function; /*** * * A Class to hold the data identifying a specific property in an object hierarchy * V is the Type of the object we are searching for * Id a unique identifier of the value of the property * Path Json like path for a property. * Parent parent object of the property. * @param <V> */ public class Property<V extends Identifiable> { public Property(String id, V value, String path, Object parent) { super(); this.id = id; this.value = value; this.path = path; this.parent = parent; } private String id; private V value; private String path; private Object parent; public String getId() { return id; } public void setId(String id) { this.id = id; } public V getValue() { return value; } public void setValue(V value) { this.value = value; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public Object getParent() { return parent; } public void setParent(Object parent) { this.parent = parent; } @Override public String toString() { return "Property [id=" + id + ", value=" + value + ", path=" + path + "]"; } /*** * Transforms this property from one type to another * @param valuebuilder function to build the new value from current one * @return */ public <T extends Identifiable> Property<T> transform( Function<V,T> valuebuilder ) { T value = valuebuilder.apply(this.value); return new Property<T>(id,value,path,parent); } }
package com.company.game; import xyz.noark.core.annotation.ControllerAdvice; /** * 异常处理器 * * @author 小流氓[176543888@qq.com] */ @ControllerAdvice public class ExceptionHandlerAdvice { }
package com.hthj.utils; import com.baomidou.mybatisplus.core.metadata.IPage; import com.baomidou.mybatisplus.core.metadata.OrderItem; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; /** * @Description * @Author pengx * @Date 2020/4/17 23:57 */ public abstract class DefaultPageCondition<T> implements Pageable<T> { Integer pageIndex = 1; Integer pageSize = 10; String orderBy = "created_time"; Boolean isAsc = false; @Override public int pageIndex() { return pageIndex; } @Override public int pageSize() { return pageSize; } @Override public String orderBy() { return orderBy; } @Override public boolean isAsc() { return isAsc; } @Override public IPage<T> toPage() { Page page = new Page(pageIndex(), pageSize()); return page.addOrder(isAsc() ? OrderItem.asc(orderBy()) : OrderItem.desc(orderBy())); } public Integer getPageIndex() { return pageIndex; } public void setPageIndex(Integer pageIndex) { this.pageIndex = pageIndex; } public Integer getPageSize() { return pageSize; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } public String getOrderBy() { return orderBy; } public void setOrderBy(String orderBy) { this.orderBy = orderBy; } public Boolean getAsc() { return isAsc; } public void setAsc(Boolean asc) { isAsc = asc; } }
/** * Copyright (c) 2004-2021 All Rights Reserved. */ package com.adomy.mirpc.core.util.lang; /** * @author adomyzhao * @version $Id: ServiceUtil.java, v 0.1 2021年03月24日 12:59 PM adomyzhao Exp $ */ public class ServiceUtil { /** * 生成服务唯一KEY * * @param interfaceName * @param serviceVersion * @return */ public static String generateServiceKey(String interfaceName, String serviceVersion) { if (StringUtil.isBlank(serviceVersion)) { serviceVersion = "DEFAULT"; } return interfaceName + "#" + serviceVersion; } }
package com.gci.api.model.contract; import java.util.Date; import java.util.List; import com.gci.api.model.invoice.Invoice; public interface Contract { public void setId(String id); public void setStartDate(Date date); public void setEndDate(Date date); public void setInvoices(List<Invoice> date); public String getId(); public Date getStartDate(); public Date getEndDate(); public List<Invoice> getInvoices(); public boolean isExpiring(); public ContractType getType(); public Term getTerm(); }
package com.javarush.task.task08.task0817; import java.util.HashMap; import java.util.Map; /* Нам повторы не нужны */ public class Solution { public static Map<String, String> createMap() { Map<String, String> map = new HashMap<>(); map.put("Иванов", "Иван"); map.put("Федоров", "Альберт"); map.put("Соколов", "Олег"); map.put("Неиванов", "Павел"); map.put("Романов", "Виталий"); map.put("Новиков", "Иван"); map.put("Путин", "Андрей"); map.put("Горбачев", "Иван"); map.put("Иванович", "Сергей"); map.put("Петров", "Олег"); return map; } public static void removeTheFirstNameDuplicates(Map<String, String> map) { Map<String, String> copy = new HashMap<>(map); int count = 0; for (Map.Entry<String, String> pair : copy.entrySet()) { for(Map.Entry<String, String> pairMap : map.entrySet()){ if(pair.getValue().equals(pairMap.getValue())){ count++; } } if(count > 1){ removeItemFromMapByValue(map, pair.getValue()); } count = 0; } //System.out.println(map); } public static void removeItemFromMapByValue(Map<String, String> map, String value) { Map<String, String> copy = new HashMap<>(map); for (Map.Entry<String, String> pair : copy.entrySet()) { if (pair.getValue().equals(value)) { map.remove(pair.getKey()); } } } public static void main(String[] args) { Map<String, String> map = createMap(); removeTheFirstNameDuplicates(map); } }
package com.telpoo.hotpic.adapter; import java.util.ArrayList; import java.util.List; import java.util.Random; import android.content.Context; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.util.Log; import android.util.SparseArray; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.TextView; import com.etsy.android.grid.util.DynamicHeightImageView; import com.nostra13.universalimageloader.core.DisplayImageOptions; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.assist.FailReason; import com.nostra13.universalimageloader.core.assist.ViewScaleType; import com.nostra13.universalimageloader.core.imageaware.ImageAware; import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener; import com.telpoo.frame.object.BaseObject; import com.telpoo.anhnong.hotgirl.R; import com.telpoo.hotpic.object.AlbulmOj; import com.telpoo.hotpic.utils.Utils; public class HotStaggeredGridViewAdapter extends ArrayAdapter<BaseObject>{ Context context; int resource; ArrayList<BaseObject> objects; Random random; LayoutInflater inflater; private static final SparseArray<Double> sPositionHeightRatios = new SparseArray<Double>(); public HotStaggeredGridViewAdapter(Context context, int resource, ArrayList<BaseObject> objects) { super(context, resource, objects); // TODO Auto-generated constructor stub this.context = context; this.resource = resource; this.objects = objects; this.inflater = LayoutInflater.from(context); this.random = new Random(); for(BaseObject albulmOj: objects) { Log.d("testSTG", albulmOj.get(AlbulmOj.URL_THUMBNAIL)); } } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub final ViewHolder holder; //View v = convertView; if( convertView == null ) { convertView = inflater.inflate( R.layout.image_item_grid, parent ,false); holder = new ViewHolder(); holder.dynamicHeightImageView = (DynamicHeightImageView) convertView.findViewById(R.id.imgViewGrid); holder.textViewTittle = (TextView) convertView.findViewById(R.id.tittleImageGrid); // convertView.setTag(holder); } else { holder = (ViewHolder) convertView.getTag(); } double positionHeight = getPositionRatio(position); String imgLink = objects.get(position).get(AlbulmOj.URL_THUMBNAIL); // if( !objects.get(position).get(AlbulmOj.NAME).equals("")) { holder.textViewTittle.setText( objects.get(position).get(AlbulmOj.NAME)); } else holder.textViewTittle.setVisibility(View.GONE); Log.d("testSTG", imgLink); ImageLoader.getInstance().loadImage(imgLink,Utils.loadImgOption(), new SimpleImageLoadingListener(){ @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { super.onLoadingComplete(imageUri, view, loadedImage); holder.dynamicHeightImageView.setImageBitmap(loadedImage); } }); holder.dynamicHeightImageView.setHeightRatio(positionHeight); //notifyDataSetChanged(); return convertView; } private double getPositionRatio(final int position) { double ratio = sPositionHeightRatios.get(position, 0.0); // if not yet done generate and stash the columns height // in our real world scenario this will be determined by // some match based on the known height and width of the image // and maybe a helpful way to get the column height! if (ratio == 0) { ratio = getRandomHeightRatio(); sPositionHeightRatios.append(position, ratio); Log.d("", "getPositionRatio:" + position + " ratio:" + ratio); } return ratio; } private double getRandomHeightRatio() { return (random.nextDouble() / 2.0) + 1.0; // height will be 1.0 - 1.5 the width } class ViewHolder{ DynamicHeightImageView dynamicHeightImageView; TextView textViewTittle; } public void Adds(List<BaseObject> items) { if (items != null) { for (BaseObject item : items) { add(item); } } } public void setData(List<BaseObject> items){ clear(); Adds(items); } public ArrayList<BaseObject> getAll(){ return objects; } }
package com.aof.webapp.action.prm.report; import java.io.FileInputStream; import java.text.NumberFormat; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.poi.hssf.usermodel.HSSFCell; import org.apache.poi.hssf.usermodel.HSSFCellStyle; import org.apache.poi.hssf.usermodel.HSSFRow; import org.apache.poi.hssf.usermodel.HSSFSheet; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.hssf.util.Region; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import com.aof.core.persistence.Persistencer; import com.aof.core.persistence.jdbc.SQLExecutor; import com.aof.core.persistence.jdbc.SQLResults; import com.aof.core.persistence.util.EntityUtil; import com.aof.webapp.action.ActionErrorLog; public class ExpenseDetailRptAction extends ReportBaseAction { protected ActionErrors errors = new ActionErrors(); protected ActionErrorLog actionDebug = new ActionErrorLog(); public ActionForward perform(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { try { String action = request.getParameter("formAction"); String year = request.getParameter("year"); String strMonthStart = request.getParameter("monthStart"); String strMonthEnd = request.getParameter("monthEnd"); String expStatus = request.getParameter("expStatus"); String strMonth = request.getParameter("month"); String deptId = request.getParameter("deptId"); if (action == null){ action = "view"; } if(year == null){ year = ""; } if(strMonthStart == null){ strMonthStart = ""; } if(strMonthEnd == null){ strMonthEnd = ""; } if(expStatus == null){ expStatus = ""; } if(strMonth == null){ strMonth = ""; } if(deptId == null){ deptId = ""; } int monthStart = 0; int monthEnd = 0; if(strMonthStart != null && !(strMonthStart.equals(""))){ monthStart = Integer.parseInt(strMonthStart); } if(strMonthEnd != null && !(strMonthEnd.equals(""))){ monthEnd = Integer.parseInt(strMonthEnd); } if (action.equals("query")) { SQLResults detail = null; SQLResults summary = findSummaryResult(year, monthStart, monthEnd, expStatus, deptId); if(strMonth == null || strMonth.equals("")){ detail = findDetailResult(year, monthStart, expStatus, deptId); request.setAttribute("mFlag",strMonthStart); } else { int month = Integer.parseInt(strMonth); detail = findDetailResult(year, month, expStatus, deptId); request.setAttribute("mFlag",strMonth); } request.setAttribute("summary",summary); request.setAttribute("detail",detail); } if(action.equals("export")){ return exportExcel(request, response, year, monthStart, monthEnd, expStatus,deptId); } } catch (Exception e) { e.printStackTrace(); } return (mapping.findForward("success")); } private SQLResults findSummaryResult(String year, int monthStart, int monthEnd, String expStatus, String deptId) throws Exception { SQLExecutor sqlExec = new SQLExecutor(Persistencer.getSQLExecutorConnection(EntityUtil .getConnectionByName("jdbc/aofdb"))); String strSQL = "select p.party_id as p_id, p.description as p_desc,"; if(expStatus.equals("Submitted")){ for(int i = monthStart; i <= monthEnd; i++){ if(i==12){ strSQL += " isnull(sum(case when((em.em_claimtype='CN') and (em.em_exp_date >= '" + year + "-" + i + "-01' and em.em_exp_date <= '" + year + "-" + i + "-31' )) then ed.ed_amt_user end), 0) as exp_comp" + i + ","; strSQL += " isnull(sum(case when((em.em_claimtype='CY') and (em.em_exp_date >= '" + year + "-" + i + "-01' and em.em_exp_date <= '" + year + "-" + i + "-31' )) then ed.ed_amt_user end), 0) as exp_cust" + i + ","; }else{ strSQL += " isnull(sum(case when((em.em_claimtype='CN') and (em.em_exp_date >= '" + year + "-" + i + "-01' and em.em_exp_date < '" + year + "-" + (i + 1) + "-01' )) then ed.ed_amt_user end), 0) as exp_comp"+i+","; strSQL += " isnull(sum(case when((em.em_claimtype='CY') and (em.em_exp_date >= '" + year + "-" + i + "-01' and em.em_exp_date < '" + year + "-" + (i + 1) + "-01' )) then ed.ed_amt_user end), 0) as exp_cust"+i+","; } } } if(expStatus.equals("Approved")){ for(int i = monthStart; i <= monthEnd; i++){ if(i==12){ strSQL += " isnull(sum(case when((em.em_claimtype='CN') and (em.em_approval_date >= '" + year + "-" + i + "-01' and em.em_approval_date <= '" + year + "-" + i + "-31' )) then ed.ed_amt_user end), 0) as exp_comp"+i+","; strSQL += " isnull(sum(case when((em.em_claimtype='CY') and (em.em_approval_date >= '" + year + "-" + i + "-01' and em.em_approval_date <= '" + year + "-" + i + "-31' )) then ed.ed_amt_user end), 0) as exp_cust"+i+","; }else{ strSQL += " isnull(sum(case when((em.em_claimtype='CN') and (em.em_approval_date >= '" + year + "-" + i + "-01' and em.em_approval_date < '" + year + "-" + (i + 1) + "-01' )) then ed.ed_amt_user end), 0) as exp_comp"+i+","; strSQL += " isnull(sum(case when((em.em_claimtype='CY') and (em.em_approval_date >= '" + year + "-" + i + "-01' and em.em_approval_date < '" + year + "-" + (i + 1) + "-01' )) then ed.ed_amt_user end), 0) as exp_cust"+i+","; } } } if(expStatus.equals("Claimed")){ for(int i = monthStart; i <= monthEnd; i++){ if(i==12){ strSQL += " isnull(sum(case when((em.em_claimtype='CN') and ((em.em_receipt_date >= '" + year + "-" + i + "-01' and em.em_receipt_date <= '" + year + "-" + i + "-31') or (em.FAConfirmDate >= '" + year + "-" + i + "-01' and em.FAConfirmDate <= '" + year + "-" + i + "-31'))) then ed.ed_amt_user end), 0) as exp_comp" + i + ","; strSQL += " isnull(sum(case when((em.em_claimtype='CY') and ((em.em_receipt_date >= '" + year + "-" + i + "-01' and em.em_receipt_date <= '" + year + "-" + i + "-31') or (em.FAConfirmDate >= '" + year + "-" + i + "-01' and em.FAConfirmDate <= '" + year + "-" + i + "-31'))) then ed.ed_amt_user end), 0) as exp_cust" + i + ","; }else{ strSQL += " isnull(sum(case when((em.em_claimtype='CN') and ((em.em_receipt_date >= '" + year + "-" + i + "-01' and em.em_receipt_date < '" + year + "-" + (i + 1) + "-01' ) or (em.FAConfirmDate >= '" + year + "-" + i + "-01' and em.FAConfirmDate < '" + year + "-" + (i + 1) + "-01'))) then ed.ed_amt_user end), 0) as exp_comp" + i+ ","; strSQL += " isnull(sum(case when((em.em_claimtype='CY') and ((em.em_receipt_date >= '" + year + "-" + i + "-01' and em.em_receipt_date < '" + year + "-" + (i + 1) + "-01' ) or (em.FAConfirmDate >= '" + year + "-" + i + "-01' and em.FAConfirmDate < '" + year + "-" + (i + 1) + "-01'))) then ed.ed_amt_user end), 0) as exp_cust" + i + ","; } } } for(int i = monthStart; i <= monthEnd; i++){ strSQL += "isnull( td.allow_cust" + i + ", 0) as allow_cust" + i; if(i != monthEnd){ strSQL += ","; } } strSQL += " from proj_exp_mstr as em" + " inner join proj_exp_det as ed on ed.em_id = em.em_id" + " inner join proj_mstr as pm on pm.proj_id = em.em_proj_id" + " inner join party as p on pm.dep_id = p.party_id and p.party_id"; if(deptId != null && !deptId.equals("")){ strSQL += " = '" + deptId + "'"; } else { strSQL += " in ('005', '006','007','014')"; } strSQL += " left join(" + " select dept.party_id as dept_id,"; for(int i = monthStart; i <= monthEnd; i++){ if(i==12){ strSQL += "isnull(sum(case when(inv.inv_invoicedate >= '" + year + "-" + i + "-01' and inv.inv_invoicedate <= '" + year + "-" + i + "-31') then tr.tr_amount end),0) as allow_cust" + i; }else{ strSQL += "isnull(sum(case when(inv.inv_invoicedate >= '" + year + "-" + i + "-01' and inv.inv_invoicedate < '" + year + "-" + (i + 1) + "-01') then tr.tr_amount end),0) as allow_cust" + i; } if(i != monthEnd){ strSQL += ","; } } strSQL += " from proj_tr_det as tr" + " inner join proj_bill as bill on bill.bill_id = tr.tr_mstr_id" + " inner join proj_invoice as inv on inv.inv_bill_id = bill.bill_id" + " inner join proj_mstr as pm on tr.tr_proj_id = pm.proj_id" + " inner join party as dept on dept.party_id = pm.dep_id and dept.party_id"; if(deptId != null && !deptId.equals("")){ strSQL += " = '" + deptId + "'"; } else { strSQL += " in ('005', '006','007','014')"; } strSQL += " where tr.tr_type='bill' and tr.tr_category='allowance' and tr.tr_mstr_id is not null" + " group by dept.party_id" + " ) as td on td.dept_id = p.party_id" + " group by p.description, p.party_id"; for(int i = monthStart; i <= monthEnd; i++){ strSQL += ",td.allow_cust" + i; } strSQL += " order by p.party_id"; System.out.println("\n" + strSQL + "\n"); SQLResults result = sqlExec.runQueryCloseCon(strSQL); return result; } private SQLResults findDetailResult(String year, int month, String expStatus, String deptId) throws Exception { SQLExecutor sqlExec = new SQLExecutor(Persistencer.getSQLExecutorConnection(EntityUtil .getConnectionByName("jdbc/aofdb"))); String strSQL ="select amt.proj_code as proj_code, " + "amt.em_code as em_code, " + "amt.employee as employee, " + "amt.p_desc as p_desc," + "sum(amt.total) as total, " + "sum(amt.hotel) as hotel, " + "sum(amt.meal) as meal, " + "sum(amt.trans) as trans, " + "sum(amt.allow) as allow, " + "sum(amt.tel) as tel, " + "sum(amt.misc) as misc, " + "amt.curr as curr, " + "amt.claim_type as claim_type, " + "amt.status as status, " + "amt.entry_date as entry_date, " + "amt.exp_date as exp_date, " + "amt.app_date as app_date, " + "amt.claim_date as claim_date" + " from( "; strSQL += "select em.em_proj_id as proj_code, " + "em.em_code as em_code, " + "ul.name as employee, " + "p.description as p_desc, " + "isnull(sum(ea.ea_amt_user),0) as total, " + "isnull( (case when(ea.exp_id=1) then ea.ea_amt_user end),0) as hotel, " + "isnull( (case when(ea.exp_id=2) then ea.ea_amt_user end),0) as meal, " + "isnull( (case when(ea.exp_id=3) then ea.ea_amt_user end),0) as trans, " + "isnull( (case when(ea.exp_id=4) then ea.ea_amt_user end),0) as allow, " + "isnull( (case when(ea.exp_id=5) then ea.ea_amt_user end),0) as tel, " + "isnull( (case when(ea.exp_id=6) then ea.ea_amt_user end),0) as misc, " + "em.em_curr_id as curr, " + "em.em_claimtype as claim_type, " + "em.em_status as status, " + "em.em_entry_date as entry_date, " + "em.em_exp_date as exp_date, " + "em.em_approval_date as app_date, " + "em.em_receipt_date as claim_date " + "from proj_exp_mstr as em " + "inner join proj_exp_amt as ea on ea.em_id = em.em_id " + "inner join user_login as ul on em.em_userlogin = ul.user_login_id " + "inner join proj_mstr as pm on pm.proj_id = em.em_proj_id " + "inner join party as p on pm.dep_id = p.party_id and p.party_id"; if(deptId != null && !deptId.equals("")){ strSQL += " = '" + deptId + "'"; } else { strSQL += " in ('005', '006','007','014')"; } if(expStatus.equals("Submitted")){ if(month == 12){ strSQL += " where em.em_exp_date >= '" + year + "-" + month + "-01' and em.em_exp_date <= '" + year + "-" + month + "-31'"; }else{ strSQL += " where em.em_exp_date >= '" + year + "-" + month + "-01' and em.em_exp_date < '" + year + "-" + (month + 1) + "-01'"; } } if(expStatus.equals("Approved")){ if(month == 12){ strSQL += " where em.em_approval_date >= '" + year + "-" + month + "-01' and em.em_approval_date <= '" + year + "-" + month + "-31'"; }else{ strSQL += " where em.em_approval_date >= '" + year + "-" + month + "-01' and em.em_approval_date < '" + year + "-" + (month + 1) + "-01'"; } } if(expStatus.equals("Claimed")){ if(month == 12){ strSQL += " where (em.em_receipt_date >= '" + year + "-" + month + "-01' and em.em_receipt_date <= '" + year + "-" + month + "-31') or (em.FAConfirmDate >= '" + year + "-" + month + "-01' and em.FAConfirmDate <= '" + year + "-" + month + "-31')"; }else{ strSQL += " where (em.em_receipt_date >= '" + year + "-" + month + "-01' and em.em_receipt_date < '" + year + "-" + (month + 1) + "-01') or (em.FAConfirmDate >= '" + year + "-" + month + "-01' and em.FAConfirmDate < '" + year + "-" + (month + 1) + "-01')"; } } strSQL +=" group by em.em_proj_id, em.em_code, ul.name, p.description,em.em_curr_id, em.em_claimtype, em.em_status, em.em_entry_date, em.em_exp_date, em.em_approval_date, em.em_receipt_date, ea.exp_id, ea.ea_amt_user, em.em_id,ea.ea_id"; strSQL += " ) as amt " + "group by amt.proj_code, amt.em_code, amt.employee, amt.p_desc,amt.curr, amt.claim_type, amt.status, amt.entry_date, amt.exp_date, amt.app_date, amt.claim_date"; if(expStatus.equals("Submitted")){ strSQL += " order by amt.exp_date"; } if(expStatus.equals("Approved")){ strSQL += " order by amt.app_date"; } if(expStatus.equals("Claimed")){ strSQL += " order by amt.claim_date"; } System.out.println("\n" + strSQL + "\n"); SQLResults result = sqlExec.runQueryCloseCon(strSQL); return result; } private ActionForward exportExcel(HttpServletRequest request, HttpServletResponse response, String year, int monthStart, int monthEnd, String expStatus, String deptId) { try{ int summaryStartRow = 6; // Get Excel Template Path String templatePath = GetTemplateFolder(); if (templatePath == null) { return null; } SQLResults summary = findSummaryResult(year, monthStart, monthEnd, expStatus, deptId); if (summary == null || summary.getRowCount() <= 0) { return null; } NumberFormat numFormator = NumberFormat.getInstance(); numFormator.setMaximumFractionDigits(2); numFormator.setMinimumFractionDigits(2); // Start to output the excel file response.reset(); response.setHeader("Content-Disposition", "attachment;filename=\"" + SaveToFileName + "\""); response.setContentType("application/octet-stream"); // Use POI to read the selected Excel Spreadsheet HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(templatePath + "\\" + ExcelTemplate)); // Select the first worksheet HSSFSheet sheet = wb.getSheet(summaryFormSheetName); // Style HSSFCellStyle titleStyle = sheet.getRow(3).getCell((short) 1).getCellStyle(); HSSFCellStyle redStyle = sheet.getRow(5).getCell((short) 1).getCellStyle(); HSSFCellStyle yellowStyle = sheet.getRow(4).getCell((short) 3).getCellStyle(); HSSFCellStyle numStyle = sheet.getRow(6).getCell((short) 1).getCellStyle(); HSSFCellStyle numBoldStyle = sheet.getRow(7).getCell((short) 1).getCellStyle(); HSSFCellStyle totalStyle = sheet.getRow(11).getCell((short) 1).getCellStyle(); // Header HSSFRow HRow = null; HRow = sheet.createRow(3); HSSFCell cell = null; int cellStart = 1; for (int i = monthStart; i <= monthEnd; i++) { String strM = ""; if( i == 1) strM = "Jan"; if( i == 2) strM = "Feb"; if( i == 3) strM = "Mar"; if( i == 4) strM = "Apr"; if( i == 5) strM = "May"; if( i == 6) strM = "Jun"; if( i == 7) strM = "Jul"; if( i == 8) strM = "Aug"; if( i == 9) strM = "Sep"; if( i == 10) strM = "Oct"; if( i == 11) strM = "Nov"; if( i == 12) strM = "Dec"; sheet.addMergedRegion(new Region(3, (short) cellStart, 3, (short) (cellStart + 2))); cell = sheet.createRow(3).createCell((short)cellStart); cell.setCellValue(strM); cell.setCellStyle(titleStyle); sheet.addMergedRegion(new Region(4, (short) cellStart, 4, (short) (cellStart + 1))); cell = sheet.createRow(4).createCell((short)cellStart); cell.setCellValue("Company"); cell.setCellStyle(redStyle); sheet.addMergedRegion(new Region(4, (short) (cellStart+2), 5, (short) (cellStart + 2))); cell = sheet.createRow(4).createCell((short)(cellStart+2)); cell.setCellValue("Customer"); cell.setCellStyle(yellowStyle); HRow = sheet.createRow(5); cell = HRow.createCell((short) cellStart); cell.setCellValue("Total Expense by company"); cell.setCellStyle(redStyle); cell = HRow.createCell((short) (cellStart + 1)); cell.setCellValue("Allowance by customer"); cell.setCellStyle(redStyle); cellStart += 3; } sheet.addMergedRegion(new Region(3, (short) cellStart, 3, (short) (cellStart + 2))); cell = sheet.createRow(3).createCell((short)cellStart); cell.setCellValue("Total"); cell.setCellStyle(titleStyle); sheet.addMergedRegion(new Region(4, (short) cellStart, 4, (short) (cellStart + 1))); cell = sheet.createRow(4).createCell((short)cellStart); cell.setCellValue("Company"); cell.setCellStyle(redStyle); sheet.addMergedRegion(new Region(4, (short) (cellStart + 2), 5, (short) (cellStart + 2))); cell = sheet.createRow(4).createCell((short)(cellStart+2)); cell.setCellValue("Customer"); cell.setCellStyle(yellowStyle); HRow = sheet.createRow(5); cell = HRow.createCell((short) cellStart); cell.setCellValue("Total Expense by company"); cell.setCellStyle(redStyle); cell = HRow.createCell((short) (cellStart + 1)); cell.setCellValue("Allowance by customer"); cell.setCellStyle(redStyle); cellStart = 1; double expCompSub[] = new double[12]; double expCustSub[] = new double[12]; double allowCustSub[] = new double[12]; double total[] = new double[12]; double allExpCompSub = 0.0; double allExpCustSub = 0.0; double allAllowCustSub = 0.0; double allTotal = 0.0; for (int row = 0; row < summary.getRowCount(); row++) { int c = 1; double expCompTotal = 0.0; double expCustTotal = 0.0; double allowCustTotal = 0.0; HRow = sheet.createRow(summaryStartRow); cell = HRow.createCell((short) 0); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue(summary.getString(row,"p_desc")); cell.setCellStyle(titleStyle); for(int i = monthStart; i <= monthEnd; i++ ){ double expComp = summary.getDouble(row,"exp_comp" + i); double expCust = summary.getDouble(row,"exp_cust" + i); double allowCust = summary.getDouble(row,"allow_cust" + i); expCompTotal += expComp; expCustTotal += expCust; allowCustTotal += allowCust; expCompSub[i-1] += expComp; expCustSub[i-1] += expCust; allowCustSub[i-1] += allowCust; total[i-1] = expCompSub[i-1] - allowCustSub[i-1]; cell = HRow.createCell((short) c); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue(expComp == 0 ? "" : numFormator.format(expComp)); cell.setCellStyle(numStyle); cell = HRow.createCell((short) (c+1)); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue(allowCust == 0 ? "" : numFormator.format(allowCust)); cell.setCellStyle(numStyle); cell = HRow.createCell((short) (c+2)); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue(expCust == 0 ? "" : numFormator.format(expCust)); cell.setCellStyle(numStyle); c +=3; } cell = HRow.createCell((short) c); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue(expCompTotal == 0 ? "" : numFormator.format(expCompTotal)); cell.setCellStyle(numStyle); cell = HRow.createCell((short) (c+1)); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue(allowCustTotal == 0 ? "" : numFormator.format(allowCustTotal)); cell.setCellStyle(numStyle); cell = HRow.createCell((short) (c+2)); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue(expCustTotal == 0 ? "" : numFormator.format(expCustTotal)); cell.setCellStyle(numStyle); allExpCompSub += expCompTotal; allExpCustSub += expCustTotal; allAllowCustSub += allowCustTotal; summaryStartRow++; } HRow = sheet.createRow(summaryStartRow); cell = HRow.createCell((short) 0); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue("SubTotal"); cell.setCellStyle(titleStyle); for(int i = monthStart; i<= monthEnd; i++){ cell = HRow.createCell((short) cellStart); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue(expCompSub[i-1] == 0 ? "" : numFormator.format(expCompSub[i-1])); cell.setCellStyle(numBoldStyle); cell = HRow.createCell((short) (cellStart + 1)); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue(allowCustSub[i-1] == 0 ? "" : numFormator.format(allowCustSub[i-1])); cell.setCellStyle(numBoldStyle); cell = HRow.createCell((short) (cellStart + 2)); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue(expCustSub[i-1] == 0 ? "" : numFormator.format(expCustSub[i-1])); cell.setCellStyle(numBoldStyle); cellStart += 3; } cell = HRow.createCell((short) cellStart); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue(allExpCompSub == 0 ? "" : numFormator.format(allExpCompSub)); cell.setCellStyle(numBoldStyle); cell = HRow.createCell((short) (cellStart + 1)); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue(allAllowCustSub == 0 ? "" : numFormator.format(allAllowCustSub)); cell.setCellStyle(numBoldStyle); cell = HRow.createCell((short) (cellStart + 2)); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue(allExpCustSub == 0 ? "" : numFormator.format(allExpCustSub)); cell.setCellStyle(numBoldStyle); summaryStartRow++; cellStart = 1; HRow = sheet.createRow(summaryStartRow); cell = HRow.createCell((short) 0); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue("Total Paid By Company"); cell.setCellStyle(titleStyle); allTotal = allExpCompSub - allAllowCustSub; for(int i = monthStart; i<= monthEnd; i++){ sheet.addMergedRegion(new Region(summaryStartRow, (short) cellStart, summaryStartRow, (short) (cellStart + 2))); cell = sheet.createRow(summaryStartRow).createCell((short)cellStart); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue(total[i-1] == 0 ? "" : numFormator.format(total[i-1])); cell.setCellStyle(totalStyle); cellStart += 3; } sheet.addMergedRegion(new Region(summaryStartRow, (short) cellStart, summaryStartRow, (short) (cellStart + 2))); cell = sheet.createRow(summaryStartRow).createCell((short)cellStart); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue(allTotal == 0 ? "" : numFormator.format(allTotal)); cell.setCellStyle(totalStyle); for(int month = monthStart; month <= (monthEnd + 1); month++){ SQLResults detail = null; if(month == monthStart){ if(monthStart == monthEnd){ detail = findDetailResult(year, monthStart, expStatus,deptId); } else { continue; } } else if(month == (monthEnd + 1)){ detail = findDetailResult(year, monthStart, expStatus, deptId); }else{ detail = findDetailResult(year, month, expStatus, deptId); } String tmpName = ""; if( month == 1) tmpName = "Jan"; if( month == 2) tmpName = "Feb"; if( month == 3) tmpName = "Mar"; if( month == 4) tmpName = "Apr"; if( month == 5) tmpName = "May"; if( month == 6) tmpName = "Jun"; if( month == 7) tmpName = "Jul"; if( month == 8) tmpName = "Aug"; if( month == 9) tmpName = "Sep"; if( month == 10) tmpName = "Oct"; if( month == 11) tmpName = "Nov"; if( month == 12) tmpName = "Dec"; HSSFSheet detailSheet = null; if(month == monthStart){ if(monthStart == monthEnd){ detailSheet = wb.getSheet(detailFormSheetName); wb.setSheetName(1,tmpName); } else { continue; } }else if(month == (monthEnd + 1)){ detailSheet = wb.getSheet(detailFormSheetName); String ms = ""; if( monthStart == 1) ms = "Jan"; if( monthStart == 2) ms = "Feb"; if( monthStart == 3) ms = "Mar"; if( monthStart == 4) ms = "Apr"; if( monthStart == 5) ms = "May"; if( monthStart == 6) ms = "Jun"; if( monthStart == 7) ms = "Jul"; if( monthStart == 8) ms = "Aug"; if( monthStart == 9) ms = "Sep"; if( monthStart == 10) ms = "Oct"; if( monthStart == 11) ms = "Nov"; if( monthStart == 12) ms = "Dec"; wb.setSheetName(1,ms); }else{ detailSheet = wb.cloneSheet(1); wb.setSheetName((month-monthStart+1),tmpName); } HSSFCellStyle textStyle = detailSheet.getRow(1).getCell((short) 0).getCellStyle(); HSSFCellStyle numberStyle = detailSheet.getRow(1).getCell((short) 4).getCellStyle(); for(int row = 0; row < detail.getRowCount(); row++){ HRow = detailSheet.createRow(row + 1); cell = HRow.createCell((short) 0); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue(detail.getString(row,"proj_code") == null ? "" : detail.getString(row,"proj_code")); cell.setCellStyle(textStyle); cell = HRow.createCell((short) 1); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue(detail.getString(row,"em_code") == null ? "" : detail.getString(row,"em_code")); cell.setCellStyle(textStyle); cell = HRow.createCell((short) 2); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue(detail.getString(row,"employee") == null ? "" : detail.getString(row,"employee")); cell.setCellStyle(textStyle); cell = HRow.createCell((short) 3); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue(detail.getString(row,"p_desc") == null ? "" : detail.getString(row,"p_desc")); cell.setCellStyle(textStyle); cell = HRow.createCell((short) 4); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue(detail.getDouble(row,"total") == 0 ? "" : numFormator.format(detail.getDouble(row,"total"))); cell.setCellStyle(numberStyle); cell = HRow.createCell((short) 5); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue(detail.getDouble(row,"hotel") == 0 ? "" : numFormator.format(detail.getDouble(row,"hotel"))); cell.setCellStyle(numberStyle); cell = HRow.createCell((short) 6); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue(detail.getDouble(row,"meal") == 0 ? "" : numFormator.format(detail.getDouble(row,"meal"))); cell.setCellStyle(numberStyle); cell = HRow.createCell((short) 7); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue(detail.getDouble(row,"trans") == 0 ? "" : numFormator.format(detail.getDouble(row,"trans"))); cell.setCellStyle(numberStyle); cell = HRow.createCell((short) 8); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue(detail.getDouble(row,"allow") == 0 ? "" : numFormator.format(detail.getDouble(row,"allow"))); cell.setCellStyle(numberStyle); cell = HRow.createCell((short) 9); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue(detail.getDouble(row,"tel") == 0 ? "" : numFormator.format(detail.getDouble(row,"tel"))); cell.setCellStyle(numberStyle); cell = HRow.createCell((short) 10); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue(detail.getDouble(row,"misc") == 0 ? "" : numFormator.format(detail.getDouble(row,"misc"))); cell.setCellStyle(numberStyle); cell = HRow.createCell((short) 11); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue(detail.getString(row,"curr") == null ? "" : detail.getString(row,"curr")); cell.setCellStyle(textStyle); String paidBy = ""; String tmp = detail.getString(row,"claim_type"); if(tmp.equals("CN")){ paidBy = "Company"; } if(tmp.equals("CY")){ paidBy = "Customer"; } cell = HRow.createCell((short) 12); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue(paidBy); cell.setCellStyle(textStyle); cell = HRow.createCell((short) 13); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue(detail.getString(row,"status") == null ? "" : detail.getString(row,"status")); cell.setCellStyle(textStyle); cell = HRow.createCell((short) 14); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue(detail.getString(row,"entry_date") == null ? "" : detail.getString(row,"entry_date")); cell.setCellStyle(textStyle); cell = HRow.createCell((short) 15); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue(detail.getString(row,"exp_date") == null ? "" : detail.getString(row,"exp_date")); cell.setCellStyle(textStyle); cell = HRow.createCell((short) 16); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue(detail.getString(row,"app_date") == null ? "" : detail.getString(row,"app_date")); cell.setCellStyle(textStyle); cell = HRow.createCell((short) 17); cell.setEncoding(HSSFCell.ENCODING_UTF_16); cell.setCellValue(detail.getString(row,"claim_date") == null ? "" : detail.getString(row,"claim_date")); cell.setCellStyle(textStyle); } } // 写入Excel工作表 wb.write(response.getOutputStream()); // 关闭Excel工作薄对象 response.getOutputStream().close(); response.setStatus(HttpServletResponse.SC_OK); response.flushBuffer(); }catch(Exception e){ e.printStackTrace(); } return null; } private final static String ExcelTemplate = "ExpenseRpt.xls"; private final static String summaryFormSheetName="Summary"; private final static String detailFormSheetName="Jan"; private final static String SaveToFileName = "Expense Report.xls"; }
package com.fujitsu.frontech.palmsecure_smpl.segovia; import org.apache.commons.csv.*; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.Reader; import java.util.ArrayList; import java.util.Date; import java.util.TreeMap; public class CSVManager { private final String campaign; private final String infile; private final String outfile; private int count; public CSVManager(File dir, String campaign) { this.campaign = campaign; StringBuffer buff = new StringBuffer(dir.getAbsolutePath()); buff = buff.append(File.separator); buff = buff.append(campaign); buff = buff.append(".csv"); this.infile = buff.toString(); this.outfile = buff.toString(); File records = new File(this.outfile); FileWriter out = null; CSVPrinter printer = null; if (!records.exists()) { try { out = new FileWriter(records, true); printer = new CSVPrinter(out, CSVFormat.DEFAULT); printer.printRecord(Recipient.FIELD_NAMES); } catch (Exception e) { e.printStackTrace(); } finally { try { out.flush(); out.close(); printer.close(); } catch (Exception e) { e.printStackTrace(); } } } // Get current count this.count = 0; try { Reader in = new FileReader(this.infile); Iterable<CSVRecord> recipients = CSVFormat.DEFAULT.withHeader().parse(in); for (CSVRecord person : recipients) { this.count++; } } catch (Exception e) { e.printStackTrace(); } } public void updateRecord(Recipient recipient) { /* * todo: add update method */ } public Recipient getRecord(String fieldName, String fieldValue) { try { Reader in = new FileReader(infile); Iterable<CSVRecord> records = CSVFormat.DEFAULT.withHeader().parse(in); for (CSVRecord record : records) { if (record.get(fieldName).equals(fieldValue)) { return new Recipient(record); } } return null; } catch (Exception e) { e.printStackTrace(); return null; } } public void writeRecord(Recipient recipient) { File outfile = null; FileWriter out = null; CSVPrinter printer = null; try { outfile = new File(this.outfile); if (!outfile.exists()) { out = new FileWriter(outfile, true); printer = new CSVPrinter(out, CSVFormat.DEFAULT); printer.printRecord(Recipient.FIELD_NAMES); } else { out = new FileWriter(outfile, true); printer = new CSVPrinter(out, CSVFormat.DEFAULT); } //CSVPrinter printer = CSVFormat.DEFAULT.withHeader(this.csvFields).print(out); printer.printRecord(recipient.fields()); this.count++; } catch (Exception e) { e.printStackTrace(); } finally { try { out.flush(); out.close(); printer.close(); } catch (Exception e) { e.printStackTrace(); } } } public int count() { return this.count; } public String nextGDID() { return this.campaign + String.format("%04d",this.count+1); } public static void main(String args[]) { File dataDir = new File("Data"); CSVManager test = new CSVManager(dataDir,"CT201412"); try { Recipient recipient = test.getRecord("GDID", "KE2014036608"); System.out.println(recipient.get("GDID")); } catch (NullPointerException e) { System.out.println("Recipient not found."); Recipient user = new Recipient("KE2014036608", "Neil"); test.writeRecord(user); System.out.println("New record created."); } System.out.println("Num recipients: " + Integer.toString(test.count())); System.out.println("Next available GDID: " + test.nextGDID()); } }
/**************************************************************** * 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.james.jspf.core; /** * This object is used as the return value for spf resolving tasks. * Every time a DNS resolution is needed the task should simply return * this one including the DNSRequest and a listener to be invoked * when the answer will be available. */ public class DNSLookupContinuation { private DNSRequest request; private SPFCheckerDNSResponseListener listener; public DNSLookupContinuation(DNSRequest request, SPFCheckerDNSResponseListener listener) { this.request = request; this.listener = listener; } /** * Return the DNSRequest which was used * * @return request */ public DNSRequest getRequest() { return request; } /** * Return the SPFCheckerDNSResponseListener which should called for the DNSRequest * * @return listener */ public SPFCheckerDNSResponseListener getListener() { return listener; } }
package com.kun.security.core.properties; import org.springframework.boot.context.properties.ConfigurationProperties; /** * @author CaoZiye * @version 1.0 2017/11/19 21:59 */ @ConfigurationProperties(prefix = "kun.security") public class SecurityProperties { private CommonProperties common = new CommonProperties(); private BrowserProperties browser = new BrowserProperties(); private CaptchaProperties captcha = new CaptchaProperties(); public CommonProperties getCommon() { return common; } public void setCommon(CommonProperties common) { this.common = common; } public BrowserProperties getBrowser() { return browser; } public void setBrowser(BrowserProperties browser) { this.browser = browser; } public CaptchaProperties getCaptcha() { return captcha; } public void setCaptcha(CaptchaProperties captcha) { this.captcha = captcha; } }
/* * 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.scf.core.persistence.db.dao.mongodb.impl; import java.util.List; import org.mongodb.morphia.Datastore; import org.mongodb.morphia.dao.BasicDAO; import org.mongodb.morphia.query.Query; import com.scf.core.persistence.db.dao.mongodb.IMongodbDao; import com.scf.core.persistence.db.pagination.PaginationOrdersList; public class MongodbDao<T> extends BasicDAO<T, String> implements IMongodbDao<T> { public MongodbDao(Datastore ds) { super(ds); } @Override public PaginationOrdersList<T> findPagination(Query<T> query, PaginationOrdersList<T> paginationOrdersList) { long totalCount = count(query); List<T> list = find(query.offset(paginationOrdersList.getPagination().getOffset()).limit(paginationOrdersList.getPagination().getPageSize())).asList(); paginationOrdersList.setDatas(list); paginationOrdersList.getPagination().setRowCount((int)totalCount); return paginationOrdersList; } }
/* * 출처 : https://ko.wikipedia.org/wiki/%ED%8C%A9%ED%86%A0%EB%A6%AC_%EB%A9%94%EC%84%9C%EB%93%9C_%ED%8C%A8%ED%84%B4 https://refactoring.guru/design-patterns/factory-method/java/example https://gmlwjd9405.github.io/2018/08/07/factory-method-pattern.html * 역할 Creator : java.util.Calendar#getInstance() Product : Calendar ConcreteProduct : BuddhistCalendar, JapaneseImperialCalendar, GregorianCalendar FactoryMethod : createCalendar 주로 java core등 에서 locale 관련 instance 를 생성할때 사용함 number format, calendar, charset, resource builder 등 */ import java.util.Calendar; import java.util.Locale; public class FactoryMethod { public static void main(String[] args) { Calendar calendar = Calendar.getInstance(); //GregorianCalendar System.out.println(calendar.get(Calendar.YEAR)); Locale locale = new Locale("ja", "JP", "JP"); //JapaneseImperialCalendar Calendar now = Calendar.getInstance(locale); System.out.println(now.get(Calendar.YEAR)); } }
package com.mpower.database; import java.util.ArrayList; import java.util.List; import java.util.zip.Adler32; import com.mpower.model.Querydata; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; public class feedbackdatabase extends SQLiteOpenHelper { // All Static variables // Database Version private static final int DATABASE_VERSION = 1; // Database Name private static final String DATABASE_NAME = "mpower_database"; // Contacts table name private static final String TABLE = "querydata"; // Contacts Table Columns names String farmerID = "farmerID"; String farmerName = "farmerName"; String queryID = "queryID"; String comment = "comment"; String datetime = "datetime"; String problemtype = "problemtype"; String problemcrop = "problemcrop"; String farmerPhone = "farmerPhone"; String farmeraddress = "farmeraddress"; String seen = "seen"; String shown = "shown"; public feedbackdatabase(Context context) { super(context,DATABASE_NAME, null, DATABASE_VERSION); // TODO Auto-generated constructor stub } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE + "(" + queryID + " INTEGER PRIMARY KEY," + farmerName + " TEXT,"+ farmerPhone + " TEXT,"+ farmeraddress + " TEXT,"+ farmerID + " TEXT," + comment + " TEXT," +datetime + " TEXT," +problemtype + " TEXT," +seen + " TEXT," +problemcrop + " TEXT,"+shown + " TEXT)"; db.execSQL(CREATE_CONTACTS_TABLE); } @Override public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) { // TODO Auto-generated method stub } // addquery() // Adding new contact public void addQuerydata(Querydata qd) { // String farmerID = "farmerID"; // String farmerName = "farmerName"; // String queryID = "queryID"; // String comment = "comment"; // String datetime = "datetime"; // String problemtype = "problemtype"; // String problemcrop = "problemcrop"; // String farmerPhone = "farmerPhone"; // String farmeraddress = "farmeraddress"; SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(farmerID, qd.getfarmerID()); // Contact Name values.put(farmerName, qd.getfarmerName()); values.put(queryID, qd.getqueryID()); values.put(comment, qd.getcomment()); values.put(datetime, qd.getdatetime()); values.put(problemtype, qd.getproblemtype()); values.put(problemcrop, qd.getproblemcrop()); values.put(farmerPhone, qd.getfarmerPhone()); values.put(farmeraddress, qd.getfarmeraddress()); values.put(seen, ""+qd.isSeen()); values.put(shown, "false"); // Inserting Row db.insert(TABLE, null, values); db.close(); // Closing database connection } public int updateseen(Querydata qd) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(seen, "true"); // values.put(KEY_PH_NO, contact.getPhoneNumber()); // updating row return db.update(TABLE, values, queryID + " = ?", new String[] { String.valueOf(qd.getqueryID()) }); } public int updateshown() { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(shown, "true"); // values.put(KEY_PH_NO, contact.getPhoneNumber()); // updating row return db.update(TABLE, values, shown + " = ?", new String[] { "false" }); } public List<Querydata> getAllquerydata() { // + queryID + " INTEGER PRIMARY KEY," + farmerName + // " TEXT,"+ farmerPhone + " TEXT,"+ farmeraddress + // " TEXT,"+ farmerID + " TEXT," // + comment + " TEXT," +datetime + " TEXT," // +problemtype + " TEXT," +seen + " TEXT," +problemcrop + " TEXT)"; // List<Querydata> qdList = new ArrayList<Querydata>(); // Select All Query String selectQuery = "SELECT * FROM " + TABLE; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); // looping through all rows and adding to list if (cursor.moveToFirst()) { do { Querydata qd = new Querydata(); qd.setqueryID(cursor.getString(0)); qd.setfarmerName(cursor.getString(1)); qd.setfarmerPhone(cursor.getString(2)); qd.setfarmeraddress(cursor.getString(3)); qd.setfarmerID(cursor.getString(4)); qd.setcomment(cursor.getString(5)); qd.setdatetime(cursor.getString(6)); qd.setproblemtype(cursor.getString(7)); qd.setSeen(Boolean.parseBoolean(cursor.getString(8))); qd.setproblemcrop(cursor.getString(9)); // contact.setID(Integer.parseInt(cursor.getString(0))); // contact.setName(cursor.getString(1)); // contact.setPhoneNumber(cursor.getString(2)); // Adding contact to list qdList.add(qd); } while (cursor.moveToNext()); } try{ cursor.close(); }catch(Exception e){ } // return contact list return qdList; } public int updatecomments(Querydata qd) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(comment, qd.getcomment()); // values.put(KEY_PH_NO, contact.getPhoneNumber()); // updating row return db.update(TABLE, values, queryID + " = ?", new String[] { String.valueOf(qd.getqueryID()) }); } public void checkandinsert(Querydata qdnew){ List <Querydata> qdlist = getAllquerydata(); if(querydata_is_in_list(qdlist, qdnew)){ if(querydata_comment_is_in_list(qdlist, qdnew)){ updatecomments(qdnew); } }else{ addQuerydata(qdnew); } } public boolean querydata_is_in_list(List<Querydata> qdlist,Querydata qdnew){ for(int i = 0;i<qdlist.size();i++){ if(qdnew.getqueryID().equalsIgnoreCase(qdlist.get(i).getqueryID())){ return true; } } return false; } public boolean querydata_comment_is_in_list(List<Querydata> qdlist,Querydata qdnew){ for(int i = 0;i<qdlist.size();i++){ if(qdnew.getqueryID().equalsIgnoreCase(qdlist.get(i).getqueryID())){ if( qdnew.getcomment().equalsIgnoreCase(qdlist.get(i).getcomment())){ return true; } } } return false; } public int returnunseenmessages(){ int count = 0; List <Querydata> qdlist = getAllquerydata(); for(int i = 0;i<qdlist.size();i++){ if(qdlist.get(i).isSeen()){ }else{ count++; } } return count; } public int returnunshownmessages(){ int count = 0; String selectQuery = "SELECT * FROM " + TABLE; SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery(selectQuery, null); // looping through all rows and adding to list if (cursor.moveToFirst()) { do { if(cursor.getString(10).equalsIgnoreCase("false")){ count++; } // contact.setID(Integer.parseInt(cursor.getString(0))); // contact.setName(cursor.getString(1)); // contact.setPhoneNumber(cursor.getString(2)); // Adding contact to list } while (cursor.moveToNext()); } return count; } }
package io.gtrain.domain.model.dto; import io.gtrain.domain.model.PhoneNumber; import io.gtrain.domain.model.enums.Major; import io.gtrain.domain.model.enums.Minor; import io.gtrain.domain.model.enums.Year; import java.util.Objects; import java.util.StringJoiner; /** * @author William Gentry */ public class RegistrationForm { private String firstname; private String lastname; private String username; private String email; private String password; private String passwordVerify; private PhoneNumber phoneNumber; private Major major; private Minor minor; private Year year; public RegistrationForm() {} public RegistrationForm(String firstname, String lastname, String username, String email, String password, String passwordVerify, PhoneNumber phoneNumber, Major major, Minor minor, Year year) { this.firstname = firstname; this.lastname = lastname; this.username = username; this.email = email; this.password = password; this.passwordVerify = passwordVerify; this.phoneNumber = phoneNumber; this.major = major; this.minor = minor; this.year = year; } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getPasswordVerify() { return passwordVerify; } public void setPasswordVerify(String passwordVerify) { this.passwordVerify = passwordVerify; } public PhoneNumber getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(PhoneNumber phoneNumber) { this.phoneNumber = phoneNumber; } public Major getMajor() { return major; } public void setMajor(Major major) { this.major = major; } public Minor getMinor() { return minor; } public void setMinor(Minor minor) { this.minor = minor; } public Year getYear() { return year; } public void setYear(Year year) { this.year = year; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; RegistrationForm that = (RegistrationForm) o; return Objects.equals(firstname, that.firstname) && Objects.equals(lastname, that.lastname) && Objects.equals(username, that.username) && Objects.equals(email, that.email) && Objects.equals(password, that.password) && Objects.equals(passwordVerify, that.passwordVerify) && Objects.equals(phoneNumber, that.phoneNumber) && major == that.major && minor == that.minor && year == that.year; } @Override public int hashCode() { return Objects.hash(firstname, lastname, username, email, password, passwordVerify, phoneNumber, major, minor, year); } @Override public String toString() { return new StringJoiner(", ", RegistrationForm.class.getSimpleName() + "[", "]") .add("firstname='" + firstname + "'") .add("lastname='" + lastname + "'") .add("username='" + username + "'") .add("email='" + email + "'") .add("password='" + password + "'") .add("passwordVerify='" + passwordVerify + "'") .add("phoneNumber=" + phoneNumber) .add("major=" + major) .add("minor=" + minor) .add("year=" + year) .toString(); } }
// File generated by hadoop record compiler. Do not edit. package fm.last.hadoop.io.records; public class RowColumn extends org.apache.hadoop.record.Record { private static final org.apache.hadoop.record.meta.RecordTypeInfo _rio_recTypeInfo; private static org.apache.hadoop.record.meta.RecordTypeInfo _rio_rtiFilter; private static int[] _rio_rtiFilterFields; static { _rio_recTypeInfo = new org.apache.hadoop.record.meta.RecordTypeInfo("RowColumn"); _rio_recTypeInfo.addField("rowKey", org.apache.hadoop.record.meta.TypeID.StringTypeID); _rio_recTypeInfo.addField("superColumnName", org.apache.hadoop.record.meta.TypeID.BufferTypeID); _rio_recTypeInfo.addField("columnName", org.apache.hadoop.record.meta.TypeID.BufferTypeID); } private String rowKey; private org.apache.hadoop.record.Buffer superColumnName; private org.apache.hadoop.record.Buffer columnName; public RowColumn() { } public RowColumn( final String rowKey, final org.apache.hadoop.record.Buffer superColumnName, final org.apache.hadoop.record.Buffer columnName) { this.rowKey = rowKey; this.superColumnName = superColumnName; this.columnName = columnName; } public static org.apache.hadoop.record.meta.RecordTypeInfo getTypeInfo() { return _rio_recTypeInfo; } public static void setTypeFilter(org.apache.hadoop.record.meta.RecordTypeInfo rti) { if (null == rti) return; _rio_rtiFilter = rti; _rio_rtiFilterFields = null; } private static void setupRtiFields() { if (null == _rio_rtiFilter) return; // we may already have done this if (null != _rio_rtiFilterFields) return; int _rio_i, _rio_j; _rio_rtiFilterFields = new int [_rio_rtiFilter.getFieldTypeInfos().size()]; for (_rio_i=0; _rio_i<_rio_rtiFilterFields.length; _rio_i++) { _rio_rtiFilterFields[_rio_i] = 0; } java.util.Iterator<org.apache.hadoop.record.meta.FieldTypeInfo> _rio_itFilter = _rio_rtiFilter.getFieldTypeInfos().iterator(); _rio_i=0; while (_rio_itFilter.hasNext()) { org.apache.hadoop.record.meta.FieldTypeInfo _rio_tInfoFilter = _rio_itFilter.next(); java.util.Iterator<org.apache.hadoop.record.meta.FieldTypeInfo> _rio_it = _rio_recTypeInfo.getFieldTypeInfos().iterator(); _rio_j=1; while (_rio_it.hasNext()) { org.apache.hadoop.record.meta.FieldTypeInfo _rio_tInfo = _rio_it.next(); if (_rio_tInfo.equals(_rio_tInfoFilter)) { _rio_rtiFilterFields[_rio_i] = _rio_j; break; } _rio_j++; } _rio_i++; } } public String getRowKey() { return rowKey; } public void setRowKey(final String rowKey) { this.rowKey=rowKey; } public org.apache.hadoop.record.Buffer getSuperColumnName() { return superColumnName; } public void setSuperColumnName(final org.apache.hadoop.record.Buffer superColumnName) { this.superColumnName=superColumnName; } public org.apache.hadoop.record.Buffer getColumnName() { return columnName; } public void setColumnName(final org.apache.hadoop.record.Buffer columnName) { this.columnName=columnName; } public void serialize(final org.apache.hadoop.record.RecordOutput _rio_a, final String _rio_tag) throws java.io.IOException { _rio_a.startRecord(this,_rio_tag); _rio_a.writeString(rowKey,"rowKey"); _rio_a.writeBuffer(superColumnName,"superColumnName"); _rio_a.writeBuffer(columnName,"columnName"); _rio_a.endRecord(this,_rio_tag); } private void deserializeWithoutFilter(final org.apache.hadoop.record.RecordInput _rio_a, final String _rio_tag) throws java.io.IOException { _rio_a.startRecord(_rio_tag); rowKey=_rio_a.readString("rowKey"); superColumnName=_rio_a.readBuffer("superColumnName"); columnName=_rio_a.readBuffer("columnName"); _rio_a.endRecord(_rio_tag); } public void deserialize(final org.apache.hadoop.record.RecordInput _rio_a, final String _rio_tag) throws java.io.IOException { if (null == _rio_rtiFilter) { deserializeWithoutFilter(_rio_a, _rio_tag); return; } // if we're here, we need to read based on version info _rio_a.startRecord(_rio_tag); setupRtiFields(); for (int _rio_i=0; _rio_i<_rio_rtiFilter.getFieldTypeInfos().size(); _rio_i++) { if (1 == _rio_rtiFilterFields[_rio_i]) { rowKey=_rio_a.readString("rowKey"); } else if (2 == _rio_rtiFilterFields[_rio_i]) { superColumnName=_rio_a.readBuffer("superColumnName"); } else if (3 == _rio_rtiFilterFields[_rio_i]) { columnName=_rio_a.readBuffer("columnName"); } else { java.util.ArrayList<org.apache.hadoop.record.meta.FieldTypeInfo> typeInfos = (java.util.ArrayList<org.apache.hadoop.record.meta.FieldTypeInfo>)(_rio_rtiFilter.getFieldTypeInfos()); org.apache.hadoop.record.meta.Utils.skip(_rio_a, typeInfos.get(_rio_i).getFieldID(), typeInfos.get(_rio_i).getTypeID()); } } _rio_a.endRecord(_rio_tag); } public int compareTo (final Object _rio_peer_) throws ClassCastException { if (!(_rio_peer_ instanceof RowColumn)) { throw new ClassCastException("Comparing different types of records."); } RowColumn _rio_peer = (RowColumn) _rio_peer_; int _rio_ret = 0; _rio_ret = rowKey.compareTo(_rio_peer.rowKey); if (_rio_ret != 0) return _rio_ret; _rio_ret = superColumnName.compareTo(_rio_peer.superColumnName); if (_rio_ret != 0) return _rio_ret; _rio_ret = columnName.compareTo(_rio_peer.columnName); if (_rio_ret != 0) return _rio_ret; return _rio_ret; } public boolean equals(final Object _rio_peer_) { if (!(_rio_peer_ instanceof RowColumn)) { return false; } if (_rio_peer_ == this) { return true; } RowColumn _rio_peer = (RowColumn) _rio_peer_; boolean _rio_ret = false; _rio_ret = rowKey.equals(_rio_peer.rowKey); if (!_rio_ret) return _rio_ret; _rio_ret = superColumnName.equals(_rio_peer.superColumnName); if (!_rio_ret) return _rio_ret; _rio_ret = columnName.equals(_rio_peer.columnName); if (!_rio_ret) return _rio_ret; return _rio_ret; } public Object clone() throws CloneNotSupportedException { RowColumn _rio_other = new RowColumn(); _rio_other.rowKey = this.rowKey; _rio_other.superColumnName = (org.apache.hadoop.record.Buffer) this.superColumnName.clone(); _rio_other.columnName = (org.apache.hadoop.record.Buffer) this.columnName.clone(); return _rio_other; } public int hashCode() { int _rio_result = 17; int _rio_ret; _rio_ret = rowKey.hashCode(); _rio_result = 37*_rio_result + _rio_ret; _rio_ret = superColumnName.hashCode(); _rio_result = 37*_rio_result + _rio_ret; _rio_ret = columnName.hashCode(); _rio_result = 37*_rio_result + _rio_ret; return _rio_result; } public static String signature() { return "LRowColumn(sBB)"; } public static class Comparator extends org.apache.hadoop.record.RecordComparator { public Comparator() { super(RowColumn.class); } static public int slurpRaw(byte[] b, int s, int l) { try { int os = s; { int i = org.apache.hadoop.record.Utils.readVInt(b, s); int z = org.apache.hadoop.record.Utils.getVIntSize(i); s+=(z+i); l-= (z+i); } { int i = org.apache.hadoop.record.Utils.readVInt(b, s); int z = org.apache.hadoop.record.Utils.getVIntSize(i); s += z+i; l -= (z+i); } { int i = org.apache.hadoop.record.Utils.readVInt(b, s); int z = org.apache.hadoop.record.Utils.getVIntSize(i); s += z+i; l -= (z+i); } return (os - s); } catch(java.io.IOException e) { throw new RuntimeException(e); } } static public int compareRaw(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { try { int os1 = s1; { int i1 = org.apache.hadoop.record.Utils.readVInt(b1, s1); int i2 = org.apache.hadoop.record.Utils.readVInt(b2, s2); int z1 = org.apache.hadoop.record.Utils.getVIntSize(i1); int z2 = org.apache.hadoop.record.Utils.getVIntSize(i2); s1+=z1; s2+=z2; l1-=z1; l2-=z2; int r1 = org.apache.hadoop.record.Utils.compareBytes(b1,s1,i1,b2,s2,i2); if (r1 != 0) { return (r1<0)?-1:0; } s1+=i1; s2+=i2; l1-=i1; l1-=i2; } { int i1 = org.apache.hadoop.record.Utils.readVInt(b1, s1); int i2 = org.apache.hadoop.record.Utils.readVInt(b2, s2); int z1 = org.apache.hadoop.record.Utils.getVIntSize(i1); int z2 = org.apache.hadoop.record.Utils.getVIntSize(i2); s1+=z1; s2+=z2; l1-=z1; l2-=z2; int r1 = org.apache.hadoop.record.Utils.compareBytes(b1,s1,i1,b2,s2,i2); if (r1 != 0) { return (r1<0)?-1:0; } s1+=i1; s2+=i2; l1-=i1; l1-=i2; } { int i1 = org.apache.hadoop.record.Utils.readVInt(b1, s1); int i2 = org.apache.hadoop.record.Utils.readVInt(b2, s2); int z1 = org.apache.hadoop.record.Utils.getVIntSize(i1); int z2 = org.apache.hadoop.record.Utils.getVIntSize(i2); s1+=z1; s2+=z2; l1-=z1; l2-=z2; int r1 = org.apache.hadoop.record.Utils.compareBytes(b1,s1,i1,b2,s2,i2); if (r1 != 0) { return (r1<0)?-1:0; } s1+=i1; s2+=i2; l1-=i1; l1-=i2; } return (os1 - s1); } catch(java.io.IOException e) { throw new RuntimeException(e); } } public int compare(byte[] b1, int s1, int l1, byte[] b2, int s2, int l2) { int ret = compareRaw(b1,s1,l1,b2,s2,l2); return (ret == -1)? -1 : ((ret==0)? 1 : 0);} } static { org.apache.hadoop.record.RecordComparator.define(RowColumn.class, new Comparator()); } }
package vn.poly.hailt.bookmanager.ui; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.Toast; import java.util.List; import vn.poly.hailt.bookmanager.Constant; import vn.poly.hailt.bookmanager.R; import vn.poly.hailt.bookmanager.RecyclerItemClickListener; import vn.poly.hailt.bookmanager.adapter.CategoryAdapter; import vn.poly.hailt.bookmanager.dao.CategoryDAO; import vn.poly.hailt.bookmanager.model.Category; public class CategoryActivity extends AppCompatActivity implements Constant { private FloatingActionButton fabAddCategories; private RecyclerView lvListCategory; private List<Category> listCategories; private CategoryAdapter categoryAdapter; private CategoryDAO categoryDAO; private BroadcastReceiver brCategory; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_category); initViews(); initActions(); categoryDAO = new CategoryDAO(this); setUpRecyclerView(); setUpBroadcastReceiver(); } private void initViews() { Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowTitleEnabled(true); fabAddCategories = findViewById(R.id.fabAddCategories); lvListCategory = findViewById(R.id.lvCategories); } private void initActions() { fabAddCategories.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(CategoryActivity.this, AddCategoryActivity.class)); } }); } private void setUpRecyclerView() { listCategories = categoryDAO.getAllCategory(); categoryAdapter = new CategoryAdapter(this, listCategories); LinearLayoutManager manager = new LinearLayoutManager(this); lvListCategory.setLayoutManager(manager); lvListCategory.setAdapter(categoryAdapter); lvListCategory.addOnItemTouchListener( new RecyclerItemClickListener(this, lvListCategory, new RecyclerItemClickListener.OnItemClickListener() { @Override public void onItemClick(View view, int position) { showActBookOfCategory(position); } @Override public void onItemLongClick(View view, int position) { showActionsDialog(position); } })); } private void setUpBroadcastReceiver() { brCategory = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { Category categoryAdded = intent.getParcelableExtra("categoryAdded"); if (categoryAdded != null) { listCategories.add(categoryAdded); categoryAdapter.notifyDataSetChanged(); } int position = intent.getIntExtra("position", -1); Category categoryUpdated = intent.getParcelableExtra("categoryUpdated"); if (categoryUpdated != null && position != -1) { listCategories.set(position, categoryUpdated); categoryAdapter.notifyDataSetChanged(); Toast.makeText(CategoryActivity.this, R.string.toast_updated_successfully, Toast.LENGTH_SHORT).show(); } } }; } private void showActionsDialog(final int position) { CharSequence actions[] = new CharSequence[]{"Sửa", "Xóa"}; String categoryName = listCategories.get(position).getCategory_name(); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(categoryName); builder.setItems(actions, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (which == 0) { showActUpdateCategory(position); } else { showConfirmDeleteCategory(position); } } }); builder.show(); } private void showActUpdateCategory(int position) { Intent intent = new Intent(CategoryActivity.this, CategoryDetailActivity.class); Bundle bundle = new Bundle(); bundle.putInt("position", position); intent.putExtra("category", bundle); startActivity(intent); } private void showConfirmDeleteCategory(final int position) { String categoryName = listCategories.get(position).getCategory_name(); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(getString(R.string.action_delete) + " " + categoryName); builder.setMessage(getString(R.string.message_confirm_delete_category)); builder.setNegativeButton(getString(R.string.action_no), null); builder.setPositiveButton(getString(R.string.action_yes), new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { categoryDAO.deleteCategory(listCategories.get(position)); listCategories.remove(position); Toast.makeText(CategoryActivity.this, R.string.toast_deleted_successfully, Toast.LENGTH_SHORT).show(); categoryAdapter.notifyDataSetChanged(); } }); builder.show(); } private void showActBookOfCategory(int position) { String categoryID = listCategories.get(position).category_id; String categoryName = listCategories.get(position).category_name; Intent intent = new Intent(CategoryActivity.this, BookOfCategoryActivity.class); intent.putExtra("categoryID", categoryID); intent.putExtra("categoryName", categoryName); startActivity(intent); } @Override protected void onResume() { super.onResume(); IntentFilter intentFilter = new IntentFilter(ACTION_CATEGORY); registerReceiver(brCategory, intentFilter); } @Override protected void onDestroy() { super.onDestroy(); Log.e("onDestroy", "onDestroy"); unregisterReceiver(brCategory); } @Override public boolean onSupportNavigateUp() { onBackPressed(); return true; } }
package exceptionmulticatch.converter; public class BinaryStringConverter { public boolean[] binaryStringToBooleanArray(String str) { if (str == null) { throw new NullPointerException("binaryString null"); } boolean[] results = new boolean[str.length()]; for (int i = 0; i < str.length(); i++) { char chrValue = str.charAt(i); if (chrValue != '0' && chrValue != '1') { throw new IllegalArgumentException("binaryString not valid"); } results[i] = chrValue == '1'; } return results; } public String booleanArrayToBinaryString(boolean[] boolArray) { if (boolArray == null || boolArray.length == 0) { throw new IllegalArgumentException("Invalid parameter."); } StringBuilder resultStr = new StringBuilder(boolArray.length); for (boolean item : boolArray) { resultStr.append(item ? '1' : '0'); } return resultStr.toString(); } }
package ba.unsa.etf.rpr; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXMLLoader; import javafx.fxml.Initializable; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.control.cell.PropertyValueFactory; import javafx.stage.Stage; import java.io.File; import java.io.IOException; import java.net.URL; import java.util.ResourceBundle; public class Formular implements Initializable { public Button obrisiBtn; public TextField obrisi; public Button dodajGrad; public Button dodajDrzavu; public TableView drzave; public TableColumn naziv; public TableView gradovi; public TableColumn ime; public TableColumn brojStanovnika; private ObservableList<Drzava> drz = FXCollections.observableArrayList(); private ObservableList<Grad> grd = FXCollections.observableArrayList(); private GeografijaDAO geo; public Formular(){ GeografijaDAO.removeInstance(); File dbfile = new File("baza.db"); dbfile.delete(); geo = GeografijaDAO.getInstance(); obrisi= new TextField(); dodajDrzavu = new Button(); obrisiBtn = new Button(); dodajGrad = new Button(); drzave = new TableView(); naziv = new TableColumn(); gradovi = new TableView(); ime = new TableColumn(); brojStanovnika = new TableColumn(); } public void brisi(ActionEvent actionEvent) { geo.obrisiDrzavu(obrisi.textProperty().get()); drz.clear(); drz.addAll(geo.drzave()); grd.clear(); grd.addAll(geo.gradovi()); } public void dodajG(ActionEvent actionEvent) { Stage secStage= new Stage(); Grad g = new Grad(); Drzava d = new Drzava(); FXMLLoader loader = new FXMLLoader(getClass().getResource("/dodaj.fxml")); loader.setController(new Dodaj()); Parent root = null; try { root = loader.load(); } catch (IOException e) { e.printStackTrace(); } secStage.setTitle("Dodaj"); secStage.setScene(new Scene(root, 300, 275)); secStage.show(); secStage.setOnCloseRequest(event -> { drz.clear(); drz.addAll(geo.drzave()); grd.clear(); grd.addAll(geo.gradovi()); }); } public void dodajD(ActionEvent actionEvent) { Stage secStage= new Stage(); Grad g = new Grad(); Drzava d = new Drzava(); FXMLLoader loader = new FXMLLoader(getClass().getResource("/dodaj.fxml")); loader.setController(new Dodaj()); Parent root = null; try { root = loader.load(); } catch (IOException e) { e.printStackTrace(); } secStage.setTitle("Dodaj"); secStage.setScene(new Scene(root, 300, 275)); secStage.show(); secStage.setOnCloseRequest(event -> { drz.clear(); drz.addAll(geo.drzave()); grd.clear(); grd.addAll(geo.gradovi()); ; }); } @Override public void initialize(URL location, ResourceBundle resources) { drz.clear(); drz.addAll(geo.drzave()); grd.clear(); grd.addAll(geo.gradovi()); drzave.setItems(drz); gradovi.setItems(grd); naziv.setCellValueFactory(new PropertyValueFactory<>("naziv")); ime.setCellValueFactory(new PropertyValueFactory<>("ime")); brojStanovnika.setCellValueFactory(new PropertyValueFactory<>("brojStanovnika")); } }
package org.study.schedule; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.study.admin.ScheduleDAO; import org.study.admin.ScheduleVO; @Service public class ScheduleServiceImpl implements ScheduleService{ @Autowired private ScheduleDAO scheduleDAO; @Override public List<ScheduleVO> reserveSelectDay() throws Exception { return scheduleDAO.reserveSelectDay(); } @Override public List<ScheduleVO> reserveSelectTime(String movie_code, String cinema_code, String day) throws Exception { return scheduleDAO.reserveSelectTime(movie_code, cinema_code, day); } @Override public ScheduleVO reserveSelectSchedule(String schedule_code) throws Exception { return scheduleDAO.reserveSelectSchedule(schedule_code); } @Override public List<ScheduleVO> selectSchedule_date() throws Exception { return scheduleDAO.selectSchedule_date(); } }
package net.sf.throughglass.network.clients; import net.sf.throughglass.network.Network; import net.sf.throughglass.proto.Works; import net.sf.throughglass.utils.AndroidTaskQueueImpl; import ye2libs.utils.TaskQueue; public class BaseClient { private static TaskQueue queue = null; public synchronized static TaskQueue getMainQueue() { if (queue == null) { queue = new AndroidTaskQueueImpl(); } return queue; } protected static Works.BaseRequest getBaseRequest(int uin) { final Works.BaseRequest.Builder builder = Works.BaseRequest.newBuilder(); builder.setClientVersion(Network.CLIENT_VERSION); builder.setUin(uin); return builder.build(); } }
package com.exam.zzz_other_menu; import java.util.ArrayList; import android.content.Context; import android.database.Cursor; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.view.LayoutInflater; import android.widget.TextView; import android.widget.ImageView; import android.widget.BaseExpandableListAdapter; import android.widget.Button; import android.widget.Toast; import com.exam.zzz_other_menu_mysql.MySQLiteHandler; import com.example.n_mart.R; public class Select_mart_Adapter extends BaseExpandableListAdapter { MySQLiteHandler handler; Cursor c; Button btn; // LayoutInflater를 가저오려면 컨텍스트를 넘겨받아야 한다. private Context context; // 대 그룹에 보여줄 리스트 private ArrayList<Select_mart_GM> groups; // 대 그룹을 눌렀을때 보여주는 자식 리스트 private ArrayList<ArrayList<Select_mart_Model>> children; // xml으로 생성한 UI를 가저다 준다. private LayoutInflater inflater; public Select_mart_Adapter(Context context, ArrayList<Select_mart_GM> gropus, ArrayList<ArrayList<Select_mart_Model>> children) { this.groups = gropus; this.children = children; this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); this.context = context; } public ArrayList<ArrayList<Select_mart_Model>> getAllList() { return this.children; } @Override public boolean areAllItemsEnabled() { return false; } @Override public Select_mart_Model getChild(int groupPosition, int childPosition) { return children.get(groupPosition).get(childPosition); } @Override public long getChildId(int groupPosition, int childPosition) { return children.get(groupPosition).get(childPosition).getId(); } // children을 보여준다. ArrayAdapter의 getView와 동일하게 처리하면 된다. @Override public View getChildView(final int groupPosition, final int childPosition, boolean isLastChild, View convertView, ViewGroup parent) { final Select_mart_Model model = getChild(groupPosition, childPosition); View view = convertView; if (view == null) { view = inflater.inflate(R.layout.select_mart_child_row, null); } if (model != null) { handler = MySQLiteHandler.open(context); ImageView img = (ImageView) view.findViewById(R.id.Select_mart_imageView1); TextView childName = (TextView) view.findViewById(R.id.Select_mart_childname); TextView childAge = (TextView) view.findViewById(R.id.Select_mart_rgb); btn = (Button) view.findViewById(R.id.Select_mart_button1); btn.setFocusable(false); btn.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { c = handler.selectbookmarker(model.getMartName()); c.moveToFirst(); if(c.getInt(2)==0){ handler.updatebookmarker(model.getMartName(), 1); model.setBookMarker(1); notifyDataSetChanged(); Toast.makeText(context, "즐겨찾기에 추가되었습니다.", Toast.LENGTH_SHORT).show(); } else { handler.updatebookmarker(model.getMartName(), 0); model.setBookMarker(0); notifyDataSetChanged(); Toast.makeText(context, "즐겨찾기에서 해체되었습니다.", Toast.LENGTH_SHORT).show(); } } }); if(model.getBookMarker()==0){ btn.setBackgroundResource(R.drawable.book_no); notifyDataSetChanged(); } else { btn.setBackgroundResource(R.drawable.book_yes); notifyDataSetChanged(); } String divword = ""; String divword2 = ""; if (model.getMartName().contains("이마트")) { divword = model.getMartName().substring(0, 4); divword2 = model.getMartName().substring(4); } else if (model.getMartName().contains("롯데마트")) { divword = model.getMartName().substring(0, 5); divword2 = model.getMartName().substring(5); } else if (model.getMartName().contains("홈플러스")) { divword = model.getMartName().substring(0, 5); divword2 = model.getMartName().substring(5); } else if (model.getMartName().contains("하나로마트")) { divword = model.getMartName().substring(0, 6); divword2 = model.getMartName().substring(6); } else if (model.getMartName().contains("신세계백화점")) { divword = model.getMartName().substring(0, 7); divword2 = model.getMartName().substring(7); } else if (model.getMartName().contains("현대백화점")) { divword = model.getMartName().substring(0, 6); divword2 = model.getMartName().substring(6); } else if (model.getMartName().contains("롯데백화점")) { divword = model.getMartName().substring(0, 6); divword2 = model.getMartName().substring(6); } childName.setText(divword); childAge.setText(divword2); if (model.getMartName().contains("롯데마트 서울역점")) { img.setImageResource(R.drawable.l_seoulstation); }else if (model.getMartName().contains("롯데마트 강변점")){ img.setImageResource(R.drawable.l_gangbyun2); }else if (model.getMartName().contains("롯데마트 금천점")) { img.setImageResource(R.drawable.l_keumchon); }else if (model.getMartName().contains("홈플러스 잠실점")) { img.setImageResource(R.drawable.h_jamsil); }else if (model.getMartName().contains("홈플러스 강동점")) { img.setImageResource(R.drawable.h_gangdong); }else if (model.getMartName().contains("홈플러스 방학점")) { img.setImageResource(R.drawable.h_banghak); }else if (model.getMartName().contains("홈플러스 동대문점")) { img.setImageResource(R.drawable.h_dongdaemoon); }else if (model.getMartName().contains("홈플러스 면목점")) { img.setImageResource(R.drawable.h_myunmok); }else if (model.getMartName().contains("홈플러스 영등포점")) { img.setImageResource(R.drawable.h_youngdeungpo); }else if (model.getMartName().contains("홈플러스 시흥점")) { img.setImageResource(R.drawable.h_siheung); }else if (model.getMartName().contains("이마트 성수점")) { img.setImageResource(R.drawable.e_sungsoo); }else if (model.getMartName().contains("이마트 은평점")) { img.setImageResource(R.drawable.e_eunpyung); }else if (model.getMartName().contains("이마트 목동점")) { img.setImageResource(R.drawable.e_mokdong); }else if (model.getMartName().contains("이마트 용산점")) { img.setImageResource(R.drawable.e_yongsan); }else if (model.getMartName().contains("이마트 청계점")) { img.setImageResource(R.drawable.e_chungye); }else if (model.getMartName().contains("이마트 명일점")) { img.setImageResource(R.drawable.e_myungil); }else if (model.getMartName().contains("이마트 신도림점")) { img.setImageResource(R.drawable.e_sindorim); }else if (model.getMartName().contains("이마트 창동점")) { img.setImageResource(R.drawable.e_changdong); }else if (model.getMartName().contains("이마트 자양점")) { img.setImageResource(R.drawable.e_jayang); }else if (model.getMartName().contains("이마트 상봉점")) { img.setImageResource(R.drawable.e_sangbong); }else if (model.getMartName().contains("이마트 미아점")) { img.setImageResource(R.drawable.e_mia); }else if (model.getMartName().contains("이마트 가양점")) { img.setImageResource(R.drawable.e_gayang); }else if (model.getMartName().contains("이마트 여의도점")) { img.setImageResource(R.drawable.e_yuido); }else if (model.getMartName().contains("이마트 왕십리점")) { img.setImageResource(R.drawable.e_wangsiri); }else if (model.getMartName().contains("하나로마트 목동점")) { img.setImageResource(R.drawable.n_mokdong); }else if (model.getMartName().contains("하나로마트 미아점")) { img.setImageResource(R.drawable.n_mia); }else if (model.getMartName().contains("하나로마트 양재점")) { img.setImageResource(R.drawable.n_yangjae); }else if (model.getMartName().contains("하나로마트 용산점")) { img.setImageResource(R.drawable.n_yongsan); }else if (model.getMartName().contains("신세계백화점 본점")) { img.setImageResource(R.drawable.s_bon); }else if (model.getMartName().contains("신세계백화점 강남점")) { img.setImageResource(R.drawable.s_gangnam); }else if (model.getMartName().contains("롯데백화점 본점")) { img.setImageResource(R.drawable.ld_bon); }else if (model.getMartName().contains("롯데백화점 청량리점")) { img.setImageResource(R.drawable.ld_chungryangri); }else if (model.getMartName().contains("롯데백화점 강남점")) { img.setImageResource(R.drawable.ld_gangnam); }else if (model.getMartName().contains("롯데백화점 잠실점")) { img.setImageResource(R.drawable.ld_jamsil); }else if (model.getMartName().contains("롯데백화점 관악점")) { img.setImageResource(R.drawable.ld_khwanak); }else if (model.getMartName().contains("롯데백화점 미아점")) { img.setImageResource(R.drawable.ld_mia); }else if (model.getMartName().contains("롯데백화점 노원점")) { img.setImageResource(R.drawable.ld_nowon); }else if (model.getMartName().contains("롯데백화점 영등포점")) { img.setImageResource(R.drawable.ld_youngdeungpo); }else if (model.getMartName().contains("현대백화점 미아점")) { img.setImageResource(R.drawable.hd_mia); }else if (model.getMartName().contains("현대백화점 신촌점")) { img.setImageResource(R.drawable.hd_sinchon); } } handler.close(); return view; } @Override public int getChildrenCount(int groupPosition) { return children.get(groupPosition).size(); } @Override public String getGroup(int groupPosition) { return groups.get(groupPosition).getName(); } @Override public int getGroupCount() { return groups.size(); } @Override public long getGroupId(int groupPosition) { return groupPosition; } // 대그룹을 보여준다. ArrayAdapter의 getView와 동일하게 처리하면 된다. @Override public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) { View view = convertView; String group = (String) getGroup(groupPosition); if (view == null) { view = inflater.inflate(R.layout.group_row, null); } ImageView img = (ImageView) view.findViewById(R.id.Select_mart_imageView2); if (group.contains("롯데마트")) { img.setImageResource(R.drawable.l_logodown); } else if (group.contains("이마트")) { img.setImageResource(R.drawable.e_logodown); } else if (group.contains("홈플러스")) { img.setImageResource(R.drawable.h_logodown); } else if (group.contains("하나로마트")) { img.setImageResource(R.drawable.n_logodown); } else if (group.contains("신세계백화점")) { img.setImageResource(R.drawable.s_logodown); } else if (group.contains("롯데백화점")) { img.setImageResource(R.drawable.ld_logodown); } else if (group.contains("현대백화점")) { img.setImageResource(R.drawable.hd_logodown); } if(isExpanded){ if (group.contains("롯데마트")) { img.setImageResource(R.drawable.l_logoup); } else if (group.contains("이마트")) { img.setImageResource(R.drawable.e_logoup); } else if (group.contains("홈플러스")) { img.setImageResource(R.drawable.h_logoup); } else if (group.contains("하나로마트")) { img.setImageResource(R.drawable.n_logoup); } else if (group.contains("신세계백화점")) { img.setImageResource(R.drawable.s_logoup); } else if (group.contains("롯데백화점")) { img.setImageResource(R.drawable.ld_logoup); } else if (group.contains("현대백화점")) { img.setImageResource(R.drawable.hd_logoup); } } return view; } @Override public boolean hasStableIds() { return true; } @Override public boolean isChildSelectable(int groupPosition, int childPosition) { return true; } }
package nh.automation.tools.utils; import java.nio.charset.Charset; import org.apache.commons.httpclient.Header; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; /** * 项目 :UI自动化测试 SSM 类描述: HttpClientUtil * * @author Eric * @date 2017年3月12日 nh.automation.tools.emums */ public class HttpClientUtil { /** * * @author nh * @date * <p> * get response </p> * @param url * @param httpMethod * @param headerStr * @param postData * @return * @throws Exception */ public static Response callResponse(String url, String httpMethod, String headerStr, String postData) throws Exception { url = url.replace(" ", "%20").replace("|", "%7c").replace("[", "%5b").replace("]", "%5d").replace("{", "%7b") .replace("}", "%7d").replace("\"", "%22"); Response response = new Response(); // http method if (httpMethod == null || httpMethod.trim().isEmpty()) { httpMethod = "GET"; } // header Header[] headers = null; if (headerStr != null && !headerStr.equals("")) { String[] keyValuePairArray = headerStr.split("\\|\\|"); headers = new Header[keyValuePairArray.length]; for (int i = 0; i < keyValuePairArray.length; i++) { String[] keyValuePair = keyValuePairArray[i].split(":"); try { headers[i] = new Header(keyValuePair[0], keyValuePairArray[i].substring(keyValuePair[0].length() + 1)); } catch (Exception e) { headers[i] = new Header(keyValuePair[0], ""); } } } if (!httpMethod.equals("GET")) { response = doRequest(url, httpMethod, headers, postData); } else { postData = null; response = doRequest(url, httpMethod, headers, postData); } return response; } /** * * @author niuh * @date Jun 20, 2017 * <p> * do request url </p> * @param url * @param httpMethod * @param headerStr * @param postData * @return * @throws Exception */ public static Response doRequest(String url, String httpMethod, Header[] headers, String postData) throws Exception { CloseableHttpClient httpClient = HttpClients.createDefault(); Response response = new Response(); CloseableHttpResponse httpResponse = null; if (httpMethod == null || httpMethod.trim().isEmpty()) { httpMethod = "GET"; } if (httpMethod.equals("GET")) { HttpGet httpGet = new HttpGet(url); httpResponse = httpClient.execute(httpGet); response.setStatusCode(httpResponse.getStatusLine().getStatusCode()); response.setStatusLine(httpResponse.getStatusLine().getReasonPhrase()); response.setHeaders(httpResponse.getAllHeaders()); response.setBodyEntity(EntityUtils.toString(httpResponse.getEntity())); return response; } if (httpMethod.equals("POST")) { HttpPost httpPost = new HttpPost(url); for (Header header : headers) { httpPost.addHeader(header.getName(), header.getValue()); } StringEntity entity = new StringEntity(postData, Charset.forName("UTF-8")); httpPost.setEntity(entity); httpResponse = httpClient.execute(httpPost); response.setStatusCode(httpResponse.getStatusLine().getStatusCode()); response.setStatusLine(httpResponse.getStatusLine().getReasonPhrase()); response.setHeaders(httpResponse.getAllHeaders()); response.setBodyEntity(EntityUtils.toString(httpResponse.getEntity())); return response; } if (httpMethod.equals("PUT")) { HttpPut httpPut = new HttpPut(url); for (Header header : headers) { httpPut.addHeader(header.getName(), header.getValue()); } StringEntity entity = new StringEntity(postData, Charset.forName("UTF-8")); httpPut.setEntity(entity); httpResponse = httpClient.execute(httpPut); response.setStatusCode(httpResponse.getStatusLine().getStatusCode()); response.setStatusLine(httpResponse.getStatusLine().getReasonPhrase()); response.setHeaders(httpResponse.getAllHeaders()); response.setBodyEntity(EntityUtils.toString(httpResponse.getEntity())); return response; } if (httpMethod.equals("DELETE")) { MyHttpDelete httpDelete = new MyHttpDelete(url); for (Header header : headers) { httpDelete.addHeader(header.getName(), header.getValue()); } StringEntity entity = new StringEntity(postData, Charset.forName("UTF-8")); httpDelete.setEntity(entity); httpResponse = httpClient.execute(httpDelete); response.setStatusCode(httpResponse.getStatusLine().getStatusCode()); response.setStatusLine(httpResponse.getStatusLine().getReasonPhrase()); response.setHeaders(httpResponse.getAllHeaders()); response.setBodyEntity(EntityUtils.toString(httpResponse.getEntity())); return response; } return response; } }
package filesprocessing; import java.io.File; import java.io.FileFilter; import java.util.ArrayList; import java.util.Arrays; import static filesprocessing.DirectoryProcessor.*; import static filesprocessing.Errors.*; import static filesprocessing.FilterFactory.*; public class Filter { /** greater_than filter */ protected static final String GREATER_THAN = "greater_than"; /** between filter */ protected static final String BETWEEN = "between"; /** smaller_than filter */ protected static final String SMALLER_THAN = "smaller_than"; /** file filter */ protected static final String FILE = "file"; /** contains filter */ protected static final String CONTAINS = "contains"; /** prefix filter */ protected static final String PREFIX = "prefix"; /** suffix filter */ protected static final String SUFFIX = "suffix"; /** writable filter */ protected static final String WRITABLE = "writable"; /** executable filter */ protected static final String EXECUTABLE = "executable"; /** hidden filter */ protected static final String HIDDEN = "hidden"; /** all filter */ protected static final String ALL = "all"; /** NOT suffix */ protected static final String NOT = "NOT"; /** empty string */ protected static final String EMPTY_STRING = ""; /** length of array of size 1 */ protected static final int LENGTH_OF_ONE = 1; static boolean foundError = false; /** * check if the filter line has a NOT suffix * @param parsedLine: given parsed filter line * @return true if has and false if not */ private static boolean HasNotSuffix(String[] parsedLine) { return parsedLine[parsedLine.length - 1].equals(NOT); } /** * returns a filter by greater_than * @param parsedLine: given parsed filter line * @return FileFilter filtering files by greater_than */ private static FileFilter filterGreaterThan(String[] parsedLine) { try { hasErrorInGreaterThanFilter(parsedLine); // check for errors if (HasNotSuffix(parsedLine)) { return greaterThanCheck(Double.parseDouble(parsedLine[1]), true); } return greaterThanCheck(Double.parseDouble(parsedLine[1]), false); } catch (IllegalArgumentException e) { foundError = true; return null; } } /** * returns a filter by between * @param parsedLine: given parsed filter line * @return FileFilter filtering files by between */ private static FileFilter filterBetween(String[] parsedLine) { try { hasErrorInBetweenFilter(parsedLine);// check for errors if (HasNotSuffix(parsedLine)) { return betweenCheck(Double.parseDouble(parsedLine[1]), Double.parseDouble(parsedLine[2]), true); } return betweenCheck(Double.parseDouble(parsedLine[1]), Double.parseDouble(parsedLine[2]), false); } catch (IllegalArgumentException | ArithmeticException exception) { foundError = true; return null; } } /** * returns a filter by smaller_than * @param parsedLine: given parsed filter line * @return FileFilter filtering files by smaller_than */ private static FileFilter filterSmallerThan(String[] parsedLine) { try { hasErrorInSmallerThanFilter(parsedLine); // check for errors if (HasNotSuffix(parsedLine)) { return smallerThanCheck(Double.parseDouble(parsedLine[1]), true); } return smallerThanCheck(Double.parseDouble(parsedLine[1]), false); } catch (IllegalArgumentException exception) { foundError = true; return null; } } /** * returns a filter by file * @param parsedLine: given parsed filter line * @return FileFilter filtering files by file */ private static FileFilter filterFile(String[] parsedLine) { try { hasErrorInFileFilter(parsedLine); // check for errors if (HasNotSuffix(parsedLine)) { return fileCheck(parsedLine[1], true); } return fileCheck(parsedLine[1], false); } catch (IllegalArgumentException exception) { foundError = true; return null; } } /** * returns a filter by contains * @param parsedLine: given parsed filter line * @return FileFilter filtering files by contains */ private static FileFilter filterContains(String[] parsedLine) { try { hasErrorInContainsFilter(parsedLine); // check for errors if (HasNotSuffix(parsedLine)) { return containsCheck(parsedLine[1], true); } if (parsedLine.length == LENGTH_OF_ONE) { // in case for "contains#" (empty string after #) return containsCheck(EMPTY_STRING, false); } return containsCheck(parsedLine[1], false); } catch (IllegalArgumentException exception) { foundError = true; return null; } } /** * returns a filter by prefix * @param parsedLine: given parsed filter line * @return FileFilter filtering files by prefix */ private static FileFilter filterPrefix(String[] parsedLine) { try { hasErrorInPrefixFilter(parsedLine); // check for errors if (HasNotSuffix(parsedLine)) { return prefixCheck(parsedLine[1], true); } if (parsedLine.length == LENGTH_OF_ONE) { // in case for "prefix#" (empty string after #) return prefixCheck(EMPTY_STRING, false); } return prefixCheck(parsedLine[1], false); } catch (IllegalArgumentException exception) { foundError = true; return null; } } /** * returns a filter by suffix * @param parsedLine: given parsed filter line * @return FileFilter filtering files by suffix */ private static FileFilter filterSuffix(String[] parsedLine) { try { hasErrorInSuffixFilter(parsedLine); // check for errors if (HasNotSuffix(parsedLine)) { return suffixCheck(parsedLine[1], true); } if (parsedLine.length == LENGTH_OF_ONE) { // in case for "suffix#" (empty string after #) return suffixCheck(EMPTY_STRING, false); } return suffixCheck(parsedLine[1], false); } catch (IllegalArgumentException exception) { foundError = true; return null; } } /** * returns a filter by writable * @param parsedLine: given parsed filter line * @return FileFilter filtering files by writable */ private static FileFilter filterWritable(String[] parsedLine) { try { hasErrorInWritableFilter(parsedLine); // check for errors if (HasNotSuffix(parsedLine)) { return writableCheck(parsedLine[1], true); } return writableCheck(parsedLine[1], false); } catch (IllegalArgumentException exception) { foundError = true; return null; } } /** * returns a filter by executable * @param parsedLine: given parsed filter line * @return FileFilter filtering files by executable */ private static FileFilter filterExecutable(String[] parsedLine) { try { hasErrorInExecutableFilter(parsedLine); // check for errors if (HasNotSuffix(parsedLine)) { return executableCheck(parsedLine[1], true); } return executableCheck(parsedLine[1], false); } catch (IllegalArgumentException exception) { foundError = true; return null; } } /** * returns a filter by hidden * @param parsedLine: given parsed filter line * @return FileFilter filtering files by hidden */ private static FileFilter filterHidden(String[] parsedLine) { try { hasErrorInHiddenFilter(parsedLine); // check for errors if (HasNotSuffix(parsedLine)) { return hiddenCheck(parsedLine[1], true); } return hiddenCheck(parsedLine[1], false); } catch (IllegalArgumentException exception) { foundError = true; return null; } } /** * returns a filter by all * @param parsedLine: given parsed filter line * @return FileFilter filtering files by all */ private static FileFilter filterAll(String[] parsedLine) { try { hasErrorInAllFilter(parsedLine); // check for errors if (HasNotSuffix(parsedLine)) { return allCheck(true); } return allCheck(false); } catch (IllegalArgumentException exception) { foundError = true; return null; } } /** * filter the files in the sourceDir directory according to the filter in the given filter line * @param filterLine: String of the filter line * @param sourceDir: Directory to filter files from * @param line_counter: counter the current line in the Commands file * @return ArrayList<File> of the filtered files in the sourceDir directory */ protected static ArrayList<File> filterFiles(String filterLine, File sourceDir, int line_counter) { String[] parsedLine = filterLine.split(SEPARATOR_IN_LINE); File[] files; FileFilter filter = null; switch (parsedLine[0]) { case GREATER_THAN: filter = filterGreaterThan(parsedLine); break; case BETWEEN: filter = filterBetween(parsedLine); break; case SMALLER_THAN: filter = filterSmallerThan(parsedLine); break; case FILE: filter = filterFile(parsedLine); break; case CONTAINS: filter = filterContains(parsedLine); break; case PREFIX: filter = filterPrefix(parsedLine); break; case SUFFIX: filter = filterSuffix(parsedLine); break; case WRITABLE: filter = filterWritable(parsedLine); break; case EXECUTABLE: filter = filterExecutable(parsedLine); break; case HIDDEN: filter = filterHidden(parsedLine); break; case ALL: filter = filterAll(parsedLine); break; default: // name is not valid foundError = true; break; } if (foundError) { filter = allCheck(false); System.err.println(WARNING_MESSAGE + line_counter); foundError = false; } // filter the files files = sourceDir.listFiles(filter); // move filtered files to ArrayList (easier to sort with) ArrayList<File> filesArrayList = null; if (files != null) { filesArrayList = new ArrayList<File>(Arrays.asList(files)); } return filesArrayList; } }
//package com.my.moms.pantry.scraps; // // // //import androidx.fragment.app.Fragment; //import androidx.fragment.app.FragmentManager; //import androidx.fragment.app.FragmentPagerAdapter; // //import com.my.moms.pantry.GroceryListFragment; //import com.my.moms.pantry.PantryListFragment; //import com.my.moms.pantry.RecipeFragment; // // //public class ViewPagerAdapter extends FragmentPagerAdapter { // // public ViewPagerAdapter(FragmentManager fm) { // super(fm); // } // // // // @Override // public Fragment getItem(int position) { // switch (position) // { // case 0: // return new PantryListFragment(); //Pantry Fragment at position 0 // case 1: // return new GroceryListFragment(); //Grocery Fragment at position 1 // case 2: // return new RecipeFragment(); //Recipe Fragment at position 2 // } // return null; //does not happen // } // // @Override // public int getCount() { // return 3; //three fragments // } //}
package com.alibaba.druid.sql.dialect.mysql.ast.statement; import com.alibaba.druid.sql.dialect.mysql.visitor.MySqlASTVisitor; /** * @author lijun.cailj 2017/11/16 */ public class MysqlShowHtcStatement extends MySqlStatementImpl implements MySqlShowStatement { private boolean full; private boolean isHis; @Override public void accept0(MySqlASTVisitor visitor) { visitor.visit(this); visitor.endVisit(this); } public boolean isFull() { return full; } public void setFull(boolean full) { this.full = full; } public boolean isHis() { return isHis; } public void setHis(boolean his) { isHis = his; } }
package com.java.lock; /** * Created by Ness on 2017/7/4. */ public class Test2 { //资源类 static class Service { public void print(String stringParam) { try { synchronized (stringParam) { while (true) { System.out.println(Thread.currentThread().getName()); Thread.sleep(1000); } } } catch (InterruptedException e) { e.printStackTrace(); } } } //线程A static class ThreadA extends Thread { private Service service; public ThreadA(Service service) { super(); this.service = service; } @Override public void run() { service.print("AA"); } } //线程B static class ThreadB extends Thread { private Service service; public ThreadB(Service service) { super(); this.service = service; } @Override public void run() { service.print("AA"); } } public static void main(String[] args) { //临界资源 Service service = new Service(); //创建并启动线程A ThreadA a = new ThreadA(service); a.setName("A"); a.start(); //创建并启动线程B ThreadB b = new ThreadB(service); b.setName("B"); b.start(); } }
package scut218.pisces.view.fragments; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.DividerItemDecoration; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.OrientationHelper; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.util.TypedValue; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.Toast; import java.util.ArrayList; import java.util.List; import scut218.pisces.R; import scut218.pisces.adapters.MomentAdapter; import scut218.pisces.beans.Moment; import scut218.pisces.factory.UtilFactory; import scut218.pisces.utils.MomentUtil; import scut218.pisces.view.PostActivity; public class MomentFragment extends Fragment { private AppCompatActivity activity; private Button button; private RecyclerView mRecyclerView; private MomentAdapter momentAdapter; private SwipeRefreshLayout mSwipeRefreshLayout; private String uid; private RefreshTask mRefreshTask; private List<Moment> moments=new ArrayList<>(); private OnMomentFragmentInteractionListener mListener; public MomentFragment() { // Required empty public constructor } public static MomentFragment newInstance(AppCompatActivity activity,String uid) { MomentFragment fragment = new MomentFragment(); fragment.uid=uid; fragment.activity=activity; return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment View view=inflater.inflate(R.layout.fragment_moment, container, false); button=(Button)view.findViewById(R.id.fab); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent=new Intent(activity, PostActivity.class); intent.putExtra("flag",1); activity.startActivity(intent); } }); button.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View view) { Intent intent=new Intent(activity,PostActivity.class); intent.putExtra("flag",0); activity.startActivity(intent); return false; } }); mRecyclerView=(RecyclerView)view.findViewById(R.id.recyclerview_moment); momentAdapter=new MomentAdapter(moments,activity); mRecyclerView.setAdapter(momentAdapter); mSwipeRefreshLayout=(SwipeRefreshLayout)view.findViewById(R.id.swiperefreshlayout); mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { if(mRefreshTask!=null) return; Log.d("refresh moment","start"); mRefreshTask=new RefreshTask(momentAdapter,uid); mRefreshTask.execute(); } }); //设置刷新动画颜色,可以设置4个 mSwipeRefreshLayout.setProgressBackgroundColorSchemeResource(android.R.color.white); mSwipeRefreshLayout.setColorSchemeResources(android.R.color.holo_blue_light,android.R.color.holo_red_light, android.R.color.holo_orange_light,android.R.color.holo_green_light); //设置刷新动画位置 mSwipeRefreshLayout.setProgressViewOffset(false,0,(int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,24, getResources().getDisplayMetrics())); //设置recyclerview的布局 LinearLayoutManager linearLayoutManager=new LinearLayoutManager(activity); linearLayoutManager.setOrientation(OrientationHelper.VERTICAL); mRecyclerView.setLayoutManager(linearLayoutManager); //添加分割线 mRecyclerView.addItemDecoration(new DividerItemDecoration(activity,DividerItemDecoration.HORIZONTAL)); //添加动画 mRecyclerView.setItemAnimator(new DefaultItemAnimator()); return view; } // TODO: Rename method, update argument and hook method into UI event public void onButtonPressed(Uri uri) { if (mListener != null) { mListener.onMomentFragmentInteraction(uri); } } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnMomentFragmentInteractionListener) { mListener = (OnMomentFragmentInteractionListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnFragmentInteractionListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } public interface OnMomentFragmentInteractionListener { void onMomentFragmentInteraction(Uri uri); } class RefreshTask extends AsyncTask<Void, Boolean, Boolean>{ MomentAdapter momentAdapter; MomentUtil momentUtil; List<Moment> momentList; String id; public RefreshTask(MomentAdapter momentAdapter,String id) { this.momentAdapter=momentAdapter; this.id=id; momentUtil= UtilFactory.getMomentUtil(); } @Override protected Boolean doInBackground(Void... voids) { momentList=momentUtil.requestAllMoment(); if(momentList==null) return false; Log.e("momentSize",""+momentList.size()); publishProgress(); return true; } @Override protected void onPostExecute(Boolean aBoolean) { if(aBoolean){ Log.d("refresh","success"); }else{ Log.e("refresh","failure"); } mRefreshTask=null; } @Override protected void onProgressUpdate(Boolean... values) { momentAdapter.setData(momentList); mSwipeRefreshLayout.setRefreshing(false); } } }
package org.mike.licenses.services; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.mike.licenses.clients.OrganizationRestTemplateClient; import org.mike.licenses.model.License; import org.mike.licenses.model.Organization; import org.mike.licenses.repository.LicenseRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; import java.util.Random; import java.util.UUID; @Service public class LicenseService { private static final Logger log = LogManager.getLogger(LicenseService.class); @Autowired private LicenseRepository licenseRepository; private void randomlyRunLong() { Random rnd = new Random(); int rsl = rnd.nextInt(3) + 1; if (rsl == 3) { try { Thread.sleep(110000); } catch (InterruptedException e) { e.printStackTrace(); } } } private List<License> buildFallbackLicenseList(String organizationId) { return List.of( new License().withId("000000000-00-00000") .withOrganizationId(organizationId) .withProductName("Sorry, no licensing information currently available.") ); } // COMMON PROPERTIES CAN BE DEFINED ON THE CLASS LEVEL WITH ANNOTATION @DefaultProperties @HystrixCommand(fallbackMethod = "buildFallbackLicenseList", threadPoolKey = "getLicensesByOrgThreadPool", threadPoolProperties = { @HystrixProperty(name = "coreSize", value = "30"), @HystrixProperty(name = "maxQueueSize", value = "10") }, commandProperties = { @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"), @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "75"), @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "7000"), @HystrixProperty(name = "metrics.rollingStats.timeInMilliseconds", value = "15000"), @HystrixProperty(name = "metrics.rollingStats.numBuckets", value = "5") } ) public List<License> getLicensesByOrg(String organizationId) { //randomlyRunLong(); // FOR IMAGE CIRCUIT BREAKER WORK SAKE return licenseRepository.findByOrganizationId(organizationId); } @HystrixCommand public void saveLicense(License license) { license.withId(UUID.randomUUID().toString()); licenseRepository.save(license); } @HystrixCommand public void updateLicense(License license) { licenseRepository.save(license); } @HystrixCommand public void deleteLicense(License license) { licenseRepository.deleteById(license.getLicenseId()); } // DISCOVERY @Autowired OrganizationRestTemplateClient organizationRestClient; @HystrixCommand private Organization getOrganization(String organizationId) { return organizationRestClient.getOrganization(organizationId); } @HystrixCommand public License getLicense(String organizationId, String licenseId) { License license = licenseRepository.findByOrganizationIdAndLicenseId(organizationId, licenseId); Organization org = getOrganization(organizationId); if (org == null) return license; return license .withOrganizationName(org.getName()) .withContactName(org.getContactName()) .withContactEmail(org.getContactEmail()) .withContactPhone(org.getContactPhone()); } }
import java.util.*; import java.io.*; public class prob08 { public static void main(String[] args) throws IOException { // TODO Auto-generated method stub //Scanner in = new Scanner(System.in); Scanner in = new Scanner(new File("prob08-1-in.txt")); int N = in.nextInt(); for (int idx = 0; idx < N; idx++) { String word = in.next(); for (int i = 0; i < word.length() - 1; i++) { String line = ""; for (int k = word.length() - 1; k > i; k--) line += " "; for (int k = 0; k <= i; k++) line += word.charAt(k); System.out.println(line); } System.out.println(word); for (int i = 1; i <= word.length() - 1; i++) { System.out.println(word.substring(i)); } System.out.println(); } in.close(); } }
package com.learning.arrays; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class Task12272Test { Task12272 task12272; char[][] concreteArray; @Before public void init() { task12272 = new Task12272(); concreteArray = new char[3][3]; concreteArray[0][0] = 'a'; concreteArray[0][1] = 'b'; concreteArray[0][2] = 'c'; concreteArray[1][0] = 'd'; concreteArray[1][1] = 'e'; concreteArray[1][2] = 'f'; concreteArray[2][0] = 'g'; concreteArray[2][1] = 'h'; concreteArray[2][2] = 'i'; } @Test(expected = IllegalArgumentException.class) public void testListToArray() { Task12272.listToArray(null); } @Test(expected = IllegalArgumentException.class) public void testGetLeftToRightNullIn() { task12272.getLeftToRigth(null); } @Test(expected = IllegalArgumentException.class) public void testGetLeftToRightWrongLengthHorizontal() { char[][] temp = new char[1][1]; task12272.getLeftToRigth(temp); } @Test(expected = IllegalArgumentException.class) public void testGetLeftToRightWrongVertical() { char[][] temp = new char[1][1]; task12272.getLeftToRigth(temp); } @Test public void testGetLeftToRight() { String out = "left to right word is acegi\n"; Assert.assertEquals(out, task12272.getLeftToRigth(concreteArray).toString()); } @Test(expected = IllegalArgumentException.class) public void testUpToDownNullIn() { task12272.getUpToDown(null); } @Test(expected = IllegalArgumentException.class) public void testUpToDownWrongLengthHorizontal() { char[][] temp = new char[1][1]; task12272.getUpToDown(temp); } @Test(expected = IllegalArgumentException.class) public void testGetUpRoDownWrongVertical() { char[][] temp = new char[1][1]; task12272.getUpToDown(temp); } @Test public void testGetUpToDown() { String out = "up to down word is ageci\n"; Assert.assertEquals(out, task12272.getUpToDown(concreteArray).toString()); } }
package br.com.deguste.dao; import java.io.Serializable; import javax.enterprise.context.RequestScoped; import javax.enterprise.inject.Disposes; import javax.enterprise.inject.Produces; import javax.inject.Named; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.FlushModeType; import javax.persistence.Persistence; @Named public class EntityManagerProduces implements Serializable { private static final long serialVersionUID = -6880367101549848149L; private static final String PERSISTENCE_UNIT = "degustePU"; private static final EntityManagerFactory factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT); @Produces @RequestScoped public EntityManager createEntityManager(){ EntityManager em = factory.createEntityManager(); em.setFlushMode(FlushModeType.COMMIT); return em; } public void closeEntityManager(@Disposes EntityManager em) { if (em.isOpen()) { em.close(); } } public EntityManagerProduces(){ } }
package common.util; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class MD5 { public static String md5(Object original) { if ((original == null)) { return null; } byte[] defaultBytes = original.toString().getBytes(); try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(defaultBytes); byte messageDigest[] = algorithm.digest(); StringBuffer hexString = new StringBuffer(); for (int i = 0; i < messageDigest.length; i++) { String hex = Integer.toHexString(0xFF & messageDigest[i]); if (hex.length() == 0) { hex = "00"; } else if (hex.length() == 1) { hex = "0" + hex; } hexString.append(hex); } return hexString.toString(); } catch (Exception e) { throw new RuntimeException(e); } } public static String getCode(String number) throws Exception { byte[] digest_bytes = generateFullCode(number); StringBuilder encryptedString = new StringBuilder(8); if (digest_bytes != null) { for (int i = 0; i < digest_bytes.length; i++) { if (i == 14 || i == 9 || i == 1 || i == 11) { String st = Integer.toHexString(0xFF & digest_bytes[i]); encryptedString.append(st.charAt(0)); } } } return encryptedString.toString(); } public static byte[] generateFullCode(String number) throws Exception { java.security.MessageDigest digest; digest = java.security.MessageDigest.getInstance("MD5"); digest.reset(); digest.update(number.getBytes()); return digest.digest(); } public static void main(String[] args) throws Exception { String number = "6502247603"; java.security.MessageDigest digest; digest = java.security.MessageDigest.getInstance("MD5"); digest.reset(); digest.update(number.getBytes()); byte[] digest_bytes = digest.digest(); StringBuilder encryptedString = new StringBuilder(8); if (digest_bytes != null) { for (int i = 0; i < digest_bytes.length; i++) { if (i == 14 || i == 9 || i == 1 || i == 11) { String st = Integer.toHexString(0xFF & digest_bytes[i]); encryptedString.append(st.charAt(0)); } } } System.out.println(encryptedString.toString()); } }
package de.alexhausmann.parprog; import org.apache.commons.lang.NotImplementedException; public class Bank { /** * Erzeugt ein neues Konto mit initialem Kontostand 0. * @return das neue Konto */ public Account createAccount() { return new Account(); } /** * Ruft den aktuellen Kontostand ab * @param account Konto, dessen Kontostand bestimmt werden soll * @return der aktuelle Kontostand * @throws IllegalArgumentException bei ungültigen Parametern */ public long getBalance(Account account) throws IllegalArgumentException { return account.getMoney(); } /** * Einzahlen eines bestimmten Betrags * @param account das Konto, auf den der Betrag eingezahlt werden soll * @param amount der Betrag (muß >=0 sein) * @throws IllegalArgumentException bei ungültigen Parametern * @throws IllegalAccountStateException falls der Kontostand außerhalb des gültigen Wertebereichs geraten würde */ public void deposit(Account account, long amount) throws IllegalAccountStateException, IllegalArgumentException { if (account == null) throw new IllegalArgumentException("account"); if (amount < 0) throw new IllegalArgumentException("amount"); account.addMoney(amount); } /** * Abheben eines bestimmten Betrags * @param account das Konto, von dem der Betrag abgehoben werden soll * @param amount der Betrag (muß >=0 sein) * @throws IllegalArgumentException bei ungültigen Parametern * @throws IllegalAccountStateException falls der Kontostand außerhalb des gültigen Wertebereichs geraten würde */ public void withdraw(Account account, long amount) throws IllegalAccountStateException, IllegalArgumentException { if (account == null) throw new IllegalArgumentException("account"); if (amount < 0) throw new IllegalArgumentException("amount"); account.addMoney(-amount); } /** * Überweisen eines Betrags von einem Konto auf ein anderes * @param fromAccount Konto, von dem abgebucht werden soll * @param toAccount Konto, auf das gutgeschrieben werden soll * @param amount der zu transferierende Betrag (muß >=0 sein) * @throws IllegalArgumentException bei ungültigen Parametern * @throws IllegalAccountStateException falls einer der Kontostände außerhalb des gültigen Wertebereichs geraten würde */ public void transfer(Account fromAccount, Account toAccount, long amount) throws IllegalAccountStateException, IllegalArgumentException { // Geld von der Quelle holen withdraw(fromAccount, amount); try { // Geld beim Ziel deponieren deposit(toAccount, amount); } catch (IllegalAccountStateException ex) { // Wenn der Zielaccount zu viel Geld hat, dieses wieder beim Quellaccount ablegen. deposit(fromAccount, amount); // Exception wieder werfen, da der Transfer fehlgeschlagen ist. throw ex; } } }
package com.mygdx.story; /** * Contains all the flags for the story. */ public class StoryHandler { //Variables should be self-explanatory. public static Boolean introductionPart1 = false; public static Boolean startedIntroPart2 = false; public static Boolean introductionPart2 = false; public static Boolean tutorialDecisionMade = false; public static Boolean TutorialPart1 = false; public static Boolean TutorialPart2 = false; public static Boolean TutorialPart3 = false; public static Boolean TutorialDone = false; public static Boolean didCureFirstHouse = false; public static Boolean transitionEndOfDayTutorial = false; public static Boolean interactedWithSylvia = false; public static Boolean falseCure1 = false; public static Boolean falseCure2 = false; public static Boolean killedOtherGuy = false; public static Boolean allNotesSequence = false; public static Boolean haveBeenReCured = false; public static Boolean oDNotesPlaced = false; public static Boolean decision2Created = false; public static Boolean decision2Made = false; public static Boolean toldVillagers = false; public static Boolean cutscene81Played = false; public static Boolean cutscene82Played = false; public static Boolean cutscene83Played = false; public static Boolean cutscene84Played = false; public static int decisionNumber = 1; }
package com.designPatterns.iteratorPattern3; /** * * So in future you want to deal with ex. list of product or person object you don't need to * change the main method implementation, you only need to change BrowserHistory class implementation. * @Author Vaibhav */ public class Main { public static void main(String[] args) { var history = new BrowseHistory(); history.push("www.vvs.com"); history.push("www.vvsGlobal.com"); history.push("www.vvsDigitalProduct.com"); /*for (int h = 0; h < history.getUrls().size(); h++) { var url = history.getUrls().get(h); System.out.println("Urls " + url); }*/ Iterator iterator = history.createIterator(); while (iterator.hasNext()) { var url = iterator.current(); System.out.println(url); iterator.next(); } } }
package mx.infotec.dads.kukulkan.shell.commands.navigation; import static mx.infotec.dads.kukulkan.shell.util.TextFormatter.formatDirNotExistText; import static mx.infotec.dads.kukulkan.shell.util.TextFormatter.formatNormalText; import java.nio.file.Path; import java.nio.file.Paths; import org.jline.utils.AttributedString; import mx.infotec.dads.kukulkan.shell.component.Navigator; import mx.infotec.dads.kukulkan.shell.event.message.EventType; import mx.infotec.dads.kukulkan.shell.event.message.LocationUpdatedEvent; /** * File Navigation Helper, It is used for do common operations in the * FileNavigator Command * * @author Daniel Cortes Pichardo * */ public class FileNavigationHelper { private FileNavigationHelper() { } public static Path convertToPath(String dir) { Path toChange = null; if ("@home".equals(dir)) { toChange = Paths.get(System.getProperty("user.home")); } else { toChange = Paths.get(dir); } return toChange; } /** * Validate new path. * * @param newPath * the new path * @return the attributed string */ public static AttributedString processActions(Path newPath, Navigator nav) { if (newPath.toFile().exists()) { nav.setCurrentPath(newPath); // publisher.publishEvent(new // LocationUpdatedEvent(EventType.FILE_NAVIGATION)); return formatNormalText(newPath.toString()); } else { return formatDirNotExistText(newPath.toString()); } } /** * Gets the new path. * * @param toChange * the to change * @return the new path */ public static Path calculateNewPath(String dir, Navigator nav) { Path toChange = convertToPath(dir); Path newPath; if ("..".equals(toChange.toString())) { newPath = nav.getCurrentPath().getParent(); } else if (toChange.isAbsolute()) { newPath = toChange; } else { newPath = Paths.get(nav.getCurrentPath().toAbsolutePath().toString(), toChange.toString()); } return newPath; } }
package DesignPattern.Bridge; public class Docter implements PersonToBridge { @Override public void waitForPickUp() { // TODO Auto-generated method stub System.out.println("docker waiting"); } @Override public void followToDo() { // TODO Auto-generated method stub System.out.println("docter following to heal someone"); } }
package javaDay5; import java.util.Arrays; import java.util.List; public class Program11 { public static void main(String[] args) { List<Integer> lst = Arrays.asList(2,3,5,1); System.out.println( lst.stream().map(e->2*e).mapToInt(i -> i.intValue()).average().getAsDouble() ); } }
/* * char can be considered as a positive integer. * * Whatever, it may cause string out index bound exception. */ package String; /** * * @author YNZ */ public class CharAtChar { /** * @param args the command line arguments */ public static void main(String[] args) { String str = new String("Iamok"); System.out.println("char at charat = " + str.charAt(2)); System.out.println("sub string 0 2 = " + str.substring(0, 2)); str.replace('I', 'H'); //string is immutable System.out.println("" + str); //return a new string System.out.println("" + str.replace('I', 'H')); } }
package com.envisioniot.quartz.entity; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; /** * @author YangHaojie * @date 2020/8/31 */ public class ReportJob implements Job { @Override public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { } }
package com.tibco.as.util.convert.impl; public class NumberToLong extends AbstractConverter<Number, Long> { @Override protected Long doConvert(Number source) { return source.longValue(); } }
package com.example.android.offline; import android.arch.paging.PagedListAdapter; import android.content.Context; import android.support.v7.util.DiffUtil; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.sap.cloud.mobile.fiori.contact.ContactCell; import com.sap.cloud.mobile.fiori.object.ObjectCell; // Generically typed class to handle the common portions of the adapters public class BaseAdapter<T> extends PagedListAdapter<T, BaseAdapter<T>.ViewHolder> { protected LayoutInflater mInflater; protected ItemClickListener mClickListener; // data is passed into the constructor BaseAdapter(Context context, DiffUtil.ItemCallback<T> diffCallback) { super(diffCallback); this.mInflater = LayoutInflater.from(context); } // inflates the row layout from xml when needed @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new ViewHolder(new View(mInflater.getContext())); } // binds the data to the TextView in each row @Override public void onBindViewHolder(BaseAdapter<T>.ViewHolder holder, int position) { } // stores and recycles views as they are scrolled off screen public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { ObjectCell myObjectCell; ViewHolder(View itemView) { super(itemView); myObjectCell = itemView.findViewById(R.id.objectCell); itemView.setOnClickListener(this); } @Override public void onClick(View view) { if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition()); } } // parent activity will implement this method to respond to click events public interface ItemClickListener { void onItemClick(View view, int position); } // allows click events to be caught void setClickListener(ItemClickListener itemClickListener) { this.mClickListener = itemClickListener; } }
package ru.mcfr.oxygen.framework.extensions; import ro.sync.contentcompletion.xml.ContextElement; import ro.sync.contentcompletion.xml.WhatElementsCanGoHereContext; import ro.sync.ecss.extensions.api.*; import ro.sync.ecss.extensions.api.node.AuthorDocumentFragment; import ro.sync.ecss.extensions.api.node.AuthorElement; import ro.sync.ecss.extensions.api.node.AuthorNode; import javax.swing.text.BadLocationException; import java.util.List; /** * Specific editing support for SDF documents. Handles typing and paste events inside section and tables. */ public class MOFSchemaAwareEditingHandler extends AuthorSchemaAwareEditingHandlerAdapter { private static final String SDF_NAMESPACE = "http://www.oxygenxml.com/sample/documentation"; /** * SDF table element name. */ private static final String SDF_TABLE = "table"; /** * SDF table row name. */ private static final String SDF_TABLE_ROW = "tr"; /** * SDF table cell name. */ private static final String SDF_TABLE_CELL = "td"; /** * SDF section element name. */ private static final String SECTION = "section"; /** * SDF para element name. */ protected static final String PARA = "para"; /** * SDF title element name. */ protected static final String TITLE = "title"; /** * @see ro.sync.ecss.extensions.api.AuthorSchemaAwareEditingHandler#handleDelete(int, int, ro.sync.ecss.extensions.api.AuthorAccess, boolean) */ public boolean handleDelete(int offset, int deleteType, AuthorAccess authorAccess, boolean wordLevel) throws InvalidEditException { // Not handled. return false; } /** * @see ro.sync.ecss.extensions.api.AuthorSchemaAwareEditingHandler#handleDeleteElementTags(ro.sync.ecss.extensions.api.node.AuthorNode, ro.sync.ecss.extensions.api.AuthorAccess) */ public boolean handleDeleteElementTags(AuthorNode nodeToUnwrap, AuthorAccess authorAccess) throws InvalidEditException { // Not handled. return false; } /** * @see ro.sync.ecss.extensions.api.AuthorSchemaAwareEditingHandler#handleDeleteSelection(int, int, int, ro.sync.ecss.extensions.api.AuthorAccess) */ public boolean handleDeleteSelection(int selectionStart, int selectionEnd, int generatedByActionId, AuthorAccess authorAccess) throws InvalidEditException { // Not handled. return false; } /** * @see ro.sync.ecss.extensions.api.AuthorSchemaAwareEditingHandler#handleJoinElements(ro.sync.ecss.extensions.api.node.AuthorNode, java.util.List, ro.sync.ecss.extensions.api.AuthorAccess) */ public boolean handleJoinElements(AuthorNode targetNode, List<AuthorNode> nodesToJoin, AuthorAccess authorAccess) throws InvalidEditException { // Not handled. return false; } /** * @see ro.sync.ecss.extensions.api.AuthorSchemaAwareEditingHandler#handlePasteFragment(int, ro.sync.ecss.extensions.api.node.AuthorDocumentFragment[], int, ro.sync.ecss.extensions.api.AuthorAccess) */ public boolean handlePasteFragment(int offset, AuthorDocumentFragment[] fragmentsToInsert, int actionId, AuthorAccess authorAccess) throws InvalidEditException { boolean handleInsertionEvent = false; AuthorSchemaManager authorSchemaManager = authorAccess.getDocumentController().getAuthorSchemaManager(); if (!authorSchemaManager.isLearnSchema() && !authorSchemaManager.hasLoadingErrors() && authorSchemaManager.getAuthorSchemaAwareOptions().isEnableSmartPaste()) { handleInsertionEvent = handleInsertionEvent(offset, fragmentsToInsert, authorAccess); } return handleInsertionEvent; } /** * @see ro.sync.ecss.extensions.api.AuthorSchemaAwareEditingHandler#handleTyping(int, char, ro.sync.ecss.extensions.api.AuthorAccess) */ public boolean handleTyping(int offset, char ch, AuthorAccess authorAccess) throws InvalidEditException { boolean handleTyping = false; AuthorSchemaManager authorSchemaManager = authorAccess.getDocumentController().getAuthorSchemaManager(); if (!authorSchemaManager.isLearnSchema() && !authorSchemaManager.hasLoadingErrors() && authorSchemaManager.getAuthorSchemaAwareOptions().isEnableSmartTyping()) { try { AuthorDocumentFragment characterFragment = authorAccess.getDocumentController().createNewDocumentTextFragment(String.valueOf(ch)); handleTyping = handleInsertionEvent(offset, new AuthorDocumentFragment[]{characterFragment}, authorAccess); } catch (AuthorOperationException e) { throw new InvalidEditException(e.getMessage(), "Invalid typing event: " + e.getMessage(), e, false); } } return handleTyping; } /** * Handle an insertion event (either typing or paste). * * @param offset Offset where the insertion event occurred. * @param fragmentsToInsert Fragments that must be inserted at the given offset. * @param authorAccess Author access. * @return <code>true</code> if the event was handled, <code>false</code> otherwise. * @throws InvalidEditException The event was rejected because it is invalid. */ private boolean handleInsertionEvent( int offset, AuthorDocumentFragment[] fragmentsToInsert, AuthorAccess authorAccess) throws InvalidEditException { AuthorSchemaManager authorSchemaManager = authorAccess.getDocumentController().getAuthorSchemaManager(); boolean handleEvent = false; try { AuthorNode nodeAtInsertionOffset = authorAccess.getDocumentController().getNodeAtOffset(offset); if (isElementWithNameAndNamespace(nodeAtInsertionOffset, SDF_TABLE)) { // Check if the fragment is allowed as it is. boolean canInsertFragments = authorSchemaManager.canInsertDocumentFragments( fragmentsToInsert, offset, AuthorSchemaManager.VALIDATION_MODE_STRICT_FIRST_CHILD_LAX_OTHERS); if (!canInsertFragments) { handleEvent = handleInvalidInsertionEventInTable( offset, fragmentsToInsert, authorAccess, authorSchemaManager); } } else if (isElementWithNameAndNamespace(nodeAtInsertionOffset, SECTION)) { // Check if the fragment is allowed as it is. boolean canInsertFragments = authorSchemaManager.canInsertDocumentFragments( fragmentsToInsert, offset, AuthorSchemaManager.VALIDATION_MODE_STRICT_FIRST_CHILD_LAX_OTHERS); if (!canInsertFragments) { // Insertion in 'section' element handleEvent = handleInvalidInsertionEventInSect( offset, fragmentsToInsert, authorAccess, authorSchemaManager); } } } catch (BadLocationException e) { throw new InvalidEditException(e.getMessage(), "Invalid typing event: " + e.getMessage(), e, false); } catch (AuthorOperationException e) { throw new InvalidEditException(e.getMessage(), "Invalid typing event: " + e.getMessage(), e, false); } return handleEvent; } /** * @return <code>true</code> if the given node is an element with the given local name and from the SDF namespace. */ protected boolean isElementWithNameAndNamespace(AuthorNode node, String elementLocalName) { boolean result = false; if (node.getType() == AuthorNode.NODE_TYPE_ELEMENT) { AuthorElement element = (AuthorElement) node; result = elementLocalName.equals(element.getLocalName()) && element.getNamespace().equals(SDF_NAMESPACE); } return result; } /** * Try to handle invalid insertion events in a SDF 'table'. * A row element will be inserted with a new cell in which the fragments will be inserted. * * @param offset Offset where the insertion event occurred. * @param fragmentsToInsert Fragments that must be inserted at the given offset. * @param authorAccess Author access. * @return <code>true</code> if the event was handled, <code>false</code> otherwise. */ private boolean handleInvalidInsertionEventInTable( int offset, AuthorDocumentFragment[] fragmentsToInsert, AuthorAccess authorAccess, AuthorSchemaManager authorSchemaManager) throws BadLocationException, AuthorOperationException { boolean handleEvent = false; // Typing/paste inside a SDF table. We will try to wrap the fragment into a new cell and insert it inside a new row. WhatElementsCanGoHereContext context = authorSchemaManager.createWhatElementsCanGoHereContext(offset); StringBuilder xmlFragment = new StringBuilder("<"); xmlFragment.append(SDF_TABLE_ROW); if (SDF_NAMESPACE != null && SDF_NAMESPACE.length() != 0) { xmlFragment.append(" xmlns=\"").append(SDF_NAMESPACE).append("\""); } xmlFragment.append("/>"); // Check if a row can be inserted at the current offset. boolean canInsertRow = authorSchemaManager.canInsertDocumentFragments( new AuthorDocumentFragment[]{authorAccess.getDocumentController().createNewDocumentFragmentInContext(xmlFragment.toString(), offset)}, context, AuthorSchemaManager.VALIDATION_MODE_STRICT_FIRST_CHILD_LAX_OTHERS); // Derive the context by adding a new row element with a cell. if (canInsertRow) { pushContextElement(context, SDF_TABLE_ROW); pushContextElement(context, SDF_TABLE_CELL); // Test if fragments can be inserted in the new context. if (authorSchemaManager.canInsertDocumentFragments( fragmentsToInsert, context, AuthorSchemaManager.VALIDATION_MODE_STRICT_FIRST_CHILD_LAX_OTHERS)) { // Insert a new row with a cell. xmlFragment = new StringBuilder("<"); xmlFragment.append(SDF_TABLE_ROW); if (SDF_NAMESPACE != null && SDF_NAMESPACE.length() != 0) { xmlFragment.append(" xmlns=\"").append(SDF_NAMESPACE).append("\""); } xmlFragment.append("><"); xmlFragment.append(SDF_TABLE_CELL); xmlFragment.append("/></"); xmlFragment.append(SDF_TABLE_ROW); xmlFragment.append(">"); authorAccess.getDocumentController().insertXMLFragment(xmlFragment.toString(), offset); // Get the newly inserted cell. AuthorNode newCell = authorAccess.getDocumentController().getNodeAtOffset(offset + 2); for (int i = 0; i < fragmentsToInsert.length; i++) { authorAccess.getDocumentController().insertFragment(newCell.getEndOffset(), fragmentsToInsert[i]); } handleEvent = true; } } return handleEvent; } /** * Derive the given context by adding the specified element. */ protected void pushContextElement(WhatElementsCanGoHereContext context, String elementName) { ContextElement contextElement = new ContextElement(); contextElement.setQName(elementName); contextElement.setNamespace(SDF_NAMESPACE); context.pushContextElement(contextElement, null); } /** * Try to handle invalid insertion events in 'section'. * The solution is to insert the <code>fragmentsToInsert</code> into a 'title' element if the sect element is empty or * into a 'para' element if the sect already contains a 'title'. * * @param offset Offset where the insertion event occurred. * @param fragmentsToInsert Fragments that must be inserted at the given offset. * @param authorAccess Author access. * @return <code>true</code> if the event was handled, <code>false</code> otherwise. */ private boolean handleInvalidInsertionEventInSect(int offset, AuthorDocumentFragment[] fragmentsToInsert, AuthorAccess authorAccess, AuthorSchemaManager authorSchemaManager) throws BadLocationException, AuthorOperationException { boolean handleEvent = false; // Typing/paste inside an section. AuthorElement sectionElement = (AuthorElement) authorAccess.getDocumentController().getNodeAtOffset(offset); if (sectionElement.getStartOffset() + 1 == sectionElement.getEndOffset()) { // Empty section element WhatElementsCanGoHereContext context = authorSchemaManager.createWhatElementsCanGoHereContext(offset); // Derive the context by adding a title. pushContextElement(context, TITLE); // Test if fragments can be inserted in 'title' element if (authorSchemaManager.canInsertDocumentFragments( fragmentsToInsert, context, AuthorSchemaManager.VALIDATION_MODE_STRICT_FIRST_CHILD_LAX_OTHERS)) { // Create a title structure and insert fragments inside StringBuilder xmlFragment = new StringBuilder("<").append(TITLE); if (SDF_NAMESPACE != null && SDF_NAMESPACE.length() != 0) { xmlFragment.append(" xmlns=\"").append(SDF_NAMESPACE).append("\""); } xmlFragment.append(">").append("</").append(TITLE).append(">"); // Insert title authorAccess.getDocumentController().insertXMLFragment(xmlFragment.toString(), offset); // Insert fragments AuthorNode newParaNode = authorAccess.getDocumentController().getNodeAtOffset(offset + 1); for (int i = 0; i < fragmentsToInsert.length; i++) { authorAccess.getDocumentController().insertFragment(newParaNode.getEndOffset(), fragmentsToInsert[i]); } handleEvent = true; } } else { // Check if there is just a title. List<AuthorNode> contentNodes = sectionElement.getContentNodes(); if (contentNodes.size() == 1) { AuthorNode child = contentNodes.get(0); boolean isTitleChild = isElementWithNameAndNamespace(child, TITLE); if (isTitleChild && child.getEndOffset() < offset) { // We are after the title. // Empty sect element WhatElementsCanGoHereContext context = authorSchemaManager.createWhatElementsCanGoHereContext(offset); // Derive the context by adding a para pushContextElement(context, PARA); // Test if fragments can be inserted in 'para' element if (authorSchemaManager.canInsertDocumentFragments( fragmentsToInsert, context, AuthorSchemaManager.VALIDATION_MODE_STRICT_FIRST_CHILD_LAX_OTHERS)) { // Create a para structure and insert fragments inside StringBuilder xmlFragment = new StringBuilder("<").append(PARA); if (SDF_NAMESPACE != null && SDF_NAMESPACE.length() != 0) { xmlFragment.append(" xmlns=\"").append(SDF_NAMESPACE).append("\""); } xmlFragment.append(">").append("</").append(PARA).append(">"); // Insert para authorAccess.getDocumentController().insertXMLFragment(xmlFragment.toString(), offset); // Insert fragments AuthorNode newParaNode = authorAccess.getDocumentController().getNodeAtOffset(offset + 1); for (int i = 0; i < fragmentsToInsert.length; i++) { authorAccess.getDocumentController().insertFragment(newParaNode.getEndOffset(), fragmentsToInsert[i]); } handleEvent = true; } } } } return handleEvent; } }
package FileLecture; import java.io.File; import java.util.Date; public class FileExamples { /** * @param args */ public static void main(String[] args) { //You create the file object first //then you attem File f = new File("abc.txt"); // this is only a path name to some potential file in the working directory //Checks if a file is a director if (f.isDirectory()) System.out.println(f + " is a directory"); else System.out.println(f + " is not a directory"); //Checks if a file exists if (f.exists()) { System.out.println(f + " exists."); } else System.out.println("Doesn't exist"); //Makes a directory File dir = new File("MyDir"); if (dir.mkdir()) System.out.println(dir + " has been created."); else System.out.println("Could not create" + dir); //see if file is a directory or a file if (dir.isDirectory()) System.out.println(dir + " is a directory"); else System.out.println(dir + " is not a directory"); System.out.println(f.getAbsolutePath()); System.out.println(f.getName()); //rename a directory File dirNew = new File("NewMyDir"); dir.renameTo(dirNew); //Moves a file to a new directory //Create a file object with new path name //overwrite using renameTo() the old path name for //the file you want to move File fNew = new File (dirNew + File.separator + "abc.txt"); f.renameTo(fNew); //Deletes at file File fDelete = new File("xyz.txt"); fDelete.delete(); //How to find when the file was last modified //lastModified returns a long which is the amount of millisends //since the clocks first started in 1970 //can convert to current date using the date class File fStatic = new File("staticFile.txt"); long time = fStatic.lastModified(); Date d = new Date(time); System.out.println("Last modified: " + d); //Determine the length of a file long size = fStatic.length(); System.out.println("Length = " + size); File currWorkingDirectory = new File("."); String[] fileNames = currWorkingDirectory.list(); //lists all the files and directories within a directory for (int i = 0; i < fileNames.length; i++) { System.out.println(fileNames[i]); } } }
package com.lti.ComparatorComparable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; /** * Created by busis on 2020-12-05. */ public class Movie implements Comparable<Movie>{ private int relyear; private String Name; Movie(int year, String Name){ this.relyear=year; this.Name=Name; } @Override public int compareTo(Movie o) { //Since in the class definition,we wrote that the comparator with //this is another movie, we need to do it with o return this.getRelyear() - o.getRelyear();//Only one comparision //Wither year or name not both. IF you want both, use comparator //Swap in bubble sort if return <0; } public int getRelyear() { return relyear; } public void setRelyear(int relyear) { this.relyear = relyear; } public String getName() { return Name; } public void setName(String name) { Name = name; } } class Comparison{ public static void main(String[] args) { List<Movie> movies = new ArrayList<Movie>(); movies.add(new Movie(2012,"SSR")); movies.add(new Movie(2013,"S3R")); movies.add(new Movie(2010,"S4R")); Collections.sort(movies); //TO enable this sorting, we implement comparable class //The criteria is relYear for(Movie movie:movies){ System.out.println(movie.getRelyear()+" "+movie.getName()); } } }
package uz.otash.shop.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import uz.otash.shop.entity.template.AbsEntity; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.ManyToOne; @EqualsAndHashCode(callSuper = true) @Data @AllArgsConstructor @NoArgsConstructor @Entity public class Shop extends AbsEntity { @Column(nullable = false,unique = true) private String name; private String address; @ManyToOne(fetch = FetchType.LAZY) private User seller; }
public class Scope { public static void main(String[] args) { int age = 44; int adult = 18; String teacherName = "Rafael"; if(age>= adult) { System.out.println("Is Adult"); boolean isCefetTeacher = true; System.out.println("Name: " + teacherName + ", age: " + age + "\nCEFET Teacher: " + isCefetTeacher); } //System.out.println("Name: " + teacherName + ", age: " + age + "\n CEFET Teacher: " + isCefetTeacher); // Out of scope } }
package net.awesomekorean.podo.lesson.lessonReviewRewards; import net.awesomekorean.podo.lesson.lessons.Lesson; import net.awesomekorean.podo.lesson.lessons.Lesson00; import net.awesomekorean.podo.lesson.lessons.Lesson01; import net.awesomekorean.podo.lesson.lessons.Lesson02; import net.awesomekorean.podo.lesson.lessons.Lesson03; import net.awesomekorean.podo.lesson.lessons.Lesson04; import net.awesomekorean.podo.lesson.lessons.Lesson05; import net.awesomekorean.podo.lesson.lessons.Lesson06; import net.awesomekorean.podo.lesson.lessons.Lesson07; import net.awesomekorean.podo.lesson.lessons.Lesson08; import net.awesomekorean.podo.lesson.lessons.Lesson19; import net.awesomekorean.podo.lesson.lessons.LessonInit; import net.awesomekorean.podo.lesson.lessons.LessonItem; import java.io.Serializable; public class LessonReview01 extends LessonInit implements LessonItem, LessonReview, Serializable { private String lessonId = "LR_01"; private String lessonTitle = ""; private String lessonSubTitle = ""; private Lesson[] lessons = { new Lesson04(), new Lesson05(), new Lesson06(), new Lesson07(), new Lesson08() }; private String[] baseForm = { "재미있다", "춥다", "오다", "바쁘다", "피곤하다", "일어나다", "싸다", "비싸다", "사다", "팔다"}; private String[][] conjugation = { {"재미있었어요", "재미있을 거예요", "재미있어서"}, {"추웠어요", "추울 거예요", "안 추워요 / 춥지 않아요", "추워서"}, {"왔어요", "올 거예요", "오고 있어요", "안 와요 / 오지 않아요", "못 와요 / 오지 못해요", "와서"}, {"바빴어요", "바쁠 거예요", "안 바빠요 / 바쁘지 않아요", "바빠서"}, {"피곤했어요", "피곤할 거예요", "안 피곤해요 / 피곤하지 않아요", "피곤해서"}, {"일어났어요", "일어날 거예요", "안 일어나요 / 일어나지 않아요", "못 일어나요 / 일어나지 못해요", "일어나서"}, {"쌌어요", "쌀 거예요", "안 싸요 / 싸지 않아요", "싸서"}, {"비쌌어요", "비쌀 거예요", "안 비싸요 / 비싸지 않아요", "비싸서"}, {"샀어요", "살 거예요", "사고 있어요", "안 사요 / 사지 않아요", "못 사요 / 사지 못해요", "사서"}, {"팔았어요", "팔 거예요", "팔고 있어요", "안 팔아요 / 팔지 않아요", "못 팔아요 / 팔지 못해요", "팔아서"} }; private String[][] translate = { {"It was fun", "It will be fun", "Because it's fun"}, {"It was cold", "It will be cold", "It's not cold", "Because it's cold"}, {"He came", "He will come", "He is coming", "He is not coming", "He can't come", "Because he comes"}, {"I was busy", "I will be busy", "I'm not busy", "Because I'm busy"}, {"I was tired", "I will be tired", "I'm not tired", "Because I'm tired"}, {"I woke up", "I will wake up", "I don't wake up", "I can't wake up", "Because I wake up"}, {"It was cheap", "It will be cheap", "It's not cheap", "Because it's cheap"}, {"It was expensive", "It will be expensive", "It's not expensive", "Because it's expensive"}, {"I bought", "I will buy", "I'm buying", "I don't buy", "I can't buy", "Because I buy"}, {"I sold", "I will sell", "I'm selling", "I don't sell", "I can't sell", "Because I sell"} }; public String[] getBaseForm() { return baseForm; } public String[][] getConjugation() { return conjugation; } public String[][] getTranslate() { return translate; } public Lesson[] getLessons() { return lessons; } @Override public String getLessonId() { return lessonId; } @Override public String getLessonTitle() { return lessonTitle; } @Override public String getLessonSubTitle() { return lessonSubTitle; } }
import java.util.Scanner; class Lesson_30_Activity { public static String [] list = {"every", " near ing ", " checking", "food ", "stand", "value "}; public static void main(String[] args) { String[] list2 = new String[list.length]; for (int i = 0; i < list.length; i ++) { for (int a = 0; a < list[i].length(); a ++) { if (list[i].charAt(a) != ' ') { list2[i] += list[i].charAt(a); } } list[i] = list2[i].substring(4, list2[i].length()); } } }
//package alien4cloud.it.cloud; // //import java.util.List; //import java.util.Set; // //import org.apache.commons.lang3.StringUtils; //import org.apache.http.NameValuePair; //import org.apache.http.message.BasicNameValuePair; //import org.junit.Assert; // //import alien4cloud.it.Context; //import alien4cloud.model.cloud.MatchedStorageTemplate; //import alien4cloud.model.cloud.StorageTemplate; //import alien4cloud.rest.cloud.CloudDTO; //import alien4cloud.rest.utils.JsonUtil; // //import com.google.common.collect.Lists; //import com.google.common.collect.Sets; // //import cucumber.api.DataTable; //import cucumber.api.java.en.And; //import cucumber.api.java.en.Then; //import cucumber.api.java.en.When; // //public class CloudStorageStepDefinitions { // // @When("^I add the storage with id \"([^\"]*)\" and device \"([^\"]*)\" and size (\\d+) to the cloud \"([^\"]*)\"$") // public void I_add_the_storage_with_id_and_device_and_size_to_the_cloud(String id, String device, long size, // String cloudName) throws Throwable { // String cloudId = Context.getInstance().getCloudId(cloudName); // StorageTemplate storage = new StorageTemplate(); // storage.setId(id); // if (StringUtils.isNotBlank(device)) { // storage.setDevice(device); // } // storage.setSize(size); // Context.getInstance().registerRestResponse( // Context.getRestClientInstance().postJSon("/rest/clouds/" + cloudId + "/storages", JsonUtil.toString(storage))); // } // // @And("^The cloud with name \"([^\"]*)\" should have (\\d+) storages as resources:$") // public void The_cloud_with_name_should_have_storage_as_resources(String cloudName, int numberOfStorage, DataTable expectedStorageTable) throws Throwable { // String cloudId = Context.getInstance().getCloudId(cloudName); // CloudDTO cloudDTO = JsonUtil.read(Context.getRestClientInstance().get("/rest/clouds/" + cloudId), CloudDTO.class).getData(); // assertStorages(numberOfStorage, cloudDTO.getCloud().getStorages(), expectedStorageTable); // } // // public static void assertStorages(int numberOfStorage, Set<StorageTemplate> storages, DataTable expectedStorageTable) { // Assert.assertEquals(numberOfStorage, storages.size()); // Set<StorageTemplate> expectedStorages = Sets.newHashSet(); // if (expectedStorageTable != null) { // for (List<String> rows : expectedStorageTable.raw()) { // String id = rows.get(0); // String device = rows.get(1); // long size = Long.parseLong(rows.get(2)); // StorageTemplate storage = new StorageTemplate(); // storage.setId(id); // storage.setDevice(device); // storage.setSize(size); // expectedStorages.add(storage); // } // } // Assert.assertEquals(expectedStorages, storages); // } // // @When("^I remove the storage with name \"([^\"]*)\" from the cloud \"([^\"]*)\"$") // public void I_remove_the_storage_with_name_from_the_cloud(String storageName, String cloudName) throws Throwable { // String cloudId = Context.getInstance().getCloudId(cloudName); // Context.getInstance().registerRestResponse(Context.getRestClientInstance().delete("/rest/clouds/" + cloudId + "/storages/" + storageName)); // } // // @Then("^The cloud with name \"([^\"]*)\" should not have any storage as resources$") // public void The_cloud_with_name_should_not_have_any_storage_as_resources(String cloudName) throws Throwable { // String cloudId = Context.getInstance().getCloudId(cloudName); // CloudDTO cloudDTO = JsonUtil.read(Context.getRestClientInstance().get("/rest/clouds/" + cloudId), CloudDTO.class).getData(); // Assert.assertTrue(cloudDTO.getStorages() == null || cloudDTO.getStorages().isEmpty()); // } // // @When("^I match the storage with name \"([^\"]*)\" of the cloud \"([^\"]*)\" to the PaaS resource \"([^\"]*)\"$") // public void I_match_the_storage_with_name_of_the_cloud_to_the_PaaS_resource(String storageName, String cloudName, String paaSResourceId) throws Throwable { // String cloudId = Context.getInstance().getCloudId(cloudName); // Context.getInstance().registerRestResponse( // Context.getRestClientInstance().postUrlEncoded("/rest/clouds/" + cloudId + "/storages/" + storageName + "/resource", // Lists.<NameValuePair> newArrayList(new BasicNameValuePair("pasSResourceId", paaSResourceId)))); // } // // @And("^The cloud \"([^\"]*)\" should have storage mapping configuration as below:$") // public void The_cloud_should_have_storage_mapping_configuration_as_below(String cloudName, DataTable expectedMappings) throws Throwable { // new CloudDefinitionsSteps().I_get_the_cloud_by_id(cloudName); // CloudDTO cloudDTO = JsonUtil.read(Context.getInstance().getRestResponse(), CloudDTO.class).getData(); // Set<MatchedStorageTemplate> actualStorages = Sets.newHashSet(cloudDTO.getStorages().values()); // Set<MatchedStorageTemplate> expectedStorages = Sets.newHashSet(); // for (List<String> rows : expectedMappings.raw()) { // StorageTemplate storage = new StorageTemplate(); // String id = rows.get(0); // long size = Long.parseLong(rows.get(1)); // String device = rows.get(2); // storage.setId(id); // storage.setDevice(device); // storage.setSize(size); // String pasSResourceId = rows.get(3); // if (pasSResourceId.isEmpty()) { // pasSResourceId = null; // } // expectedStorages.add(new MatchedStorageTemplate(storage, pasSResourceId)); // } // Assert.assertEquals(expectedStorages, actualStorages); // } // // @When("^I delete the mapping for the storage \"([^\"]*)\" of the cloud \"([^\"]*)\"$") // public void I_delete_the_mapping_for_the_storage_of_the_cloud(String storageName, String cloudName) throws Throwable { // String cloudId = Context.getInstance().getCloudId(cloudName); // Context.getInstance().registerRestResponse( // Context.getRestClientInstance().postUrlEncoded("/rest/clouds/" + cloudId + "/storages/" + storageName + "/resource", // Lists.<NameValuePair> newArrayList())); // } // // @Then("^The cloud \"([^\"]*)\" should have empty storage mapping configuration$") // public void The_cloud_should_have_empty_storage_mapping_configuration(String cloudName) throws Throwable { // new CloudDefinitionsSteps().I_get_the_cloud_by_id(cloudName); // CloudDTO cloudDTO = JsonUtil.read(Context.getInstance().getRestResponse(), CloudDTO.class).getData(); // Assert.assertTrue(cloudDTO.getStorages().isEmpty()); // } //}
public class MergeAndSortArrayTest { public static void main(String[] params) { int[] array1 = new int[]{31, 88, 73, 41, 32, 53, 16, 24, 57, 42, 74, 55, 36}; int[] array2 = new int[]{22, 9, 16, 55, 32, 13, 38, 83, 66, 26, 49, 15, 44}; int[] resultArray = new int[array1.length + array2.length]; int count = 0; for (int i = 0; i < array1.length; i++) { resultArray[i] = array1[i]; count++; } for (int j = 0; j < array2.length; j++) { resultArray[count++] = array2[j]; } for (int i = 0; i < resultArray.length; i++) ; System.out.println("Объединенный массив: " + arrayToString(resultArray)); resultArray = mergeSort(resultArray); System.out.println("Объединенный и отсортированный массив: " + arrayToString(resultArray)); } public static int[] mergeSort(int[] array) { int[] tmp; int[] currentSrc = array; int[] currentDest = new int[array.length]; int size = 1; while (size < array.length) { for (int i = 0; i < array.length; i += 2 * size) { merge(currentSrc, i, currentSrc, i + size, currentDest, i, size); } tmp = currentSrc; currentSrc = currentDest; currentDest = tmp; size = size * 2; } return currentSrc; } private static void merge(int[] src1, int src1Start, int[] src2, int src2Start, int[] dest, int destStart, int size) { int index1 = src1Start; int index2 = src2Start; int src1End = Math.min(src1Start + size, src1.length); int src2End = Math.min(src2Start + size, src2.length); int iterationCount = src1End - src1Start + src2End - src2Start; for (int i = destStart; i < destStart + iterationCount; i++) { if (index1 < src1End && (index2 >= src2End || src1[index1] < src2[index2])) { dest[i] = src1[index1]; index1++; } else { dest[i] = src2[index2]; index2++; } } } private static String arrayToString(int[] array) { StringBuilder sb = new StringBuilder(); sb.append("["); for (int i = 0; i < array.length; i++) { if (i > 0) { sb.append(", "); } sb.append(array[i]); } sb.append("]"); return sb.toString(); } }
package com.learning.recursion; public interface Executable { StringBuilder execute(); /** * Utility method that return pseudo random number in range * from 0 to 25 * * @return long primitive type from 0 to 25 */ static Long getRandomPositiveNumber() { return (long) (Math.round(Math.random() * 25)); } /** * Utility method that return pseudo random number in range * from -25 to 25 * * @return long primitive type from -25 to 25 */ static Long getRandomNumber() { return -25 + Math.round(Math.random() * 50); } /** * Utility method that return pseudo random number in range * from -25 to 0 * * @return long primitive type from -25 to 0 */ static Long getRandomNegativeNumber() { return (long) (-Math.round(Math.random() * 25)); } }
package com.aowin.frame; import java.awt.Container; import java.awt.FlowLayout; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import com.aowin.Exceptions.FormatException; import com.aowin.stuff.Stuff; public class PlusView { JFrame frame; Container con; JTextField text1,text2,text5; JComboBox box,box1,box3; JButton button1,button2; JPanel panel5,panel6,panel7; public PlusView(){ frame=new JFrame(); con=frame.getContentPane(); con.setLayout(new FlowLayout(FlowLayout.LEFT)); JPanel panel1=new JPanel(); JLabel label1=new JLabel("编号:"); JLabel label2=new JLabel("姓名:"); JLabel label3=new JLabel("性别:"); JLabel label4=new JLabel("部门:"); JLabel label5=new JLabel("工资:"); JPanel panel2=new JPanel(); JPanel panel3=new JPanel(); JPanel panel4=new JPanel(); panel5=new JPanel(); panel1.add(label1); panel2.add(label2); panel3.add(label3); panel4.add(label4); panel5.add(label5); text1=new JTextField("",12); text2=new JTextField("",12); panel1.add(text1); panel2.add(text2); Object[] sexName={"男","女",""}; box=new JComboBox(sexName); panel3.add(box); Object[] departmentName={"","Secretary","Engineer","Lead","Logistics","Market","Finance"}; box1=new JComboBox(departmentName); panel4.add(box1); text5=new JTextField("",12); panel5.add(text5); panel6=new JPanel(); button1=new JButton("确认"); button2=new JButton("取消"); panel6.add(button1); panel6.add(button2); con.add(panel1); con.add(panel2); con.add(panel3); con.add(panel4); con.add(panel5); con.add(panel6); panel7=new JPanel(); JLabel label7=new JLabel("请选择查询条件"); Object[] items={"and","or"}; box3=new JComboBox(items); panel7.add(label7); panel7.add(box3); //con.add(panel7); frame.setSize(250,400); frame.setLocation(600, 200); } public JFrame getFrame(){ return frame; } public Container getCon(){ return con; } public JTextField getText1(){ return text1; } public JTextField getText2(){ return text2; } public JTextField getText5(){ return text5; } public JComboBox getBox(){ return box; } public JComboBox getBox1(){ return box1; } public JButton getButton1(){ return button1; } public JButton getButton2(){ return button2; } public JPanel getPanel6(){ return panel6; } public JPanel getPanel7(){ return panel7; } public JComboBox getBox3(){ return box3; } public JPanel getPanel5(){ return panel5; } public Stuff getStuff(){ Stuff stuff=new Stuff(); int idSet=Integer.parseInt(text1.getText()); System.out.println(idSet); stuff.setId(idSet); stuff.setName(text2.getText()); stuff.setSalary(Integer.valueOf(text5.getText())); Object sexO=box.getSelectedItem(); int sexSet=(sexO.equals("男"))?1:0; stuff.setSex(sexSet); stuff.setDepartment((String)(box1.getSelectedItem())); return stuff; } public void clear(){ text1.setText(""); text2.setText(""); text5.setText(""); box.setSelectedItem("男"); box1.setSelectedItem(""); } public Stuff getStaff2(){ Stuff stuff=new Stuff(); int idSet=Integer.parseInt(text1.getText()); System.out.println(idSet); stuff.setId(idSet); stuff.setName(text2.getText()); stuff.setSalary(0); Object sexO=box.getSelectedItem(); int sexSet=(sexO.equals("男"))?1:0; stuff.setSex(sexSet); stuff.setDepartment((String)(box1.getSelectedItem())); return stuff; } public boolean throwFormatException(){ String regID="\\d{2,8}"; String regName="[a-z||A-Z||\u4e00-\u9fa5]{1,30}"; String regSalary="\\d{3,9}"; boolean flag=false; if((!text1.getText().equals("")&&!text1.getText().matches(regID)||(!text2.getText().equals("")&&!text2.getText().matches(regName))||(!text5.getText().equals("")&&!text5.getText().matches(regSalary)))){ flag=true; try { throw new FormatException(); } catch (Exception e) { System.out.println(e.getMessage()); } } return flag; } }
package ar.edu.utn.d2s.externaldependencies.cgp; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; public class CgpAPIImplMock implements CgpAPIMock { private static CgpAPIImplMock instance = null; private List<CenterDTOMock> centersDTO = new ArrayList<>(); public CgpAPIImplMock() { initializeCenters(); } public static CgpAPIImplMock getInstance() { if (instance == null) { instance = new CgpAPIImplMock(); } return instance; } private void initializeCenters() { // TODO Create some centerDTO objects and add them to the centersDTO list } @Override public List<CenterDTOMock> searchCgps(String param) { return centersDTO.stream().filter(center -> center.getIncludedZones().contains(param) || center.getAddress().startsWith(param)).collect(Collectors.toList()); } }
package com.blog.bean; /** * <p>此javabean用于记录页面信息,分页时会使用</p> * @author duanjigui *@time 2016/5/15 *@version 1.0 */ public class PageInfoBean { private int currentPage; //当前属于第几页 private int maxPage; //所能分的最大页 private int pageItem; //每页能存放信息的条数 public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public int getMaxPage() { return maxPage; } public void setMaxPage(int maxPage) { this.maxPage = maxPage; } public int getPageItem() { return pageItem; } public void setPageItem(int pageItem) { this.pageItem = pageItem; } }
package sop.vo; import it.sauronsoftware.base64.Base64; /** * @Author: LCF * @Date: 2020/1/9 11:38 * @Package: sop.vo */ public class GlInterfaceVo { private Integer id; /** * gl_inf_code */ private String glInfCode; private String encodeGlInfCode; /** * gl_inf_desc */ private String glInfDesc; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getGlInfCode() { return glInfCode; } public void setGlInfCode(String glInfCode) { this.glInfCode = glInfCode; this.encodeGlInfCode = Base64.encode(glInfCode, "utf-8"); } public String getGlInfDesc() { return glInfDesc; } public void setGlInfDesc(String glInfDesc) { this.glInfDesc = glInfDesc; } public String getEncodeGlInfCode() { return encodeGlInfCode; } public void setEncodeGlInfCode(String encodeGlInfCode) { this.encodeGlInfCode = encodeGlInfCode; } }
package com.git.cloud.sys.service; import com.git.cloud.common.exception.RollbackableBizException; import java.lang.reflect.InvocationTargetException; /** * 执行定时任务Service * * @author w * @date 2018/09/19 * */ public interface ITimingTaskExecService { /** * 扫描并执行定时任务 */ void updateScanTimingTaskAndExecute() throws RollbackableBizException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException; }
package gov.nih.mipav.view.renderer.WildMagic.Interface; import gov.nih.mipav.model.file.FileIO; import gov.nih.mipav.model.file.FileInfoSurfaceRefXML; import gov.nih.mipav.model.file.FileInfoXML; import gov.nih.mipav.model.file.FileSurfaceXML; import WildMagic.LibFoundation.Mathematics.ColorRGB; import WildMagic.LibFoundation.Mathematics.Vector3f; import WildMagic.LibGraphics.Rendering.MaterialState; import java.util.Vector; /** * This structure contains the information that describes how an XML surface (see surface.xsd and FileSurfaceXML.java) * is stored on disk. * * @see FileIO * @see FileInfoXML * @see FileSurfaceXML */ public class FileInfoSurfaceGiftiXML_WM extends FileInfoSurfaceRefXML { //~ Static fields/initializers ------------------------------------------------------------------------------------- /** * */ private static final long serialVersionUID = 819907577181061024L; /** Material properties of the surface:. */ private MaterialState m_kMaterial = null; /** * Vector to hold the 3D coordinate positions */ private Vector<Vector3f> coordinates; /** * Vector to hold the connection index. */ private Vector<Integer> connectivity; //~ Constructors --------------------------------------------------------------------------------------------------- /** * Main constructor for FileInfoSurfaceXML. * * @param name String file name * @param directory String file directory * @param format int file format (data type) */ public FileInfoSurfaceGiftiXML_WM(String name, String directory, int format) { super(name, directory, format); m_kMaterial = new MaterialState(); } //~ Methods -------------------------------------------------------------------------------------------------------- /** * Set the default coordinate vector. */ public void setCoordinate(Vector<Vector3f> coords) { coordinates = coords; } /** * Set the default connectivity vector. * @param conn */ public void setConnectivity(Vector<Integer> conn) { connectivity = conn; } /** * Get the coordinate vector. * @return coordinate */ public Vector<Vector3f> getCoordinate() { return coordinates; } /** * Get the connectivity vector. * @return connectivity. */ public Vector<Integer> getConnectivity() { return connectivity; } /** * Prepares the class for cleanup. */ public void finalize() { m_kMaterial = null; super.finalize(); } /** * Returns the material properties for the surface:. * @return material properties for the surface. */ public MaterialState getMaterial() { return m_kMaterial; } /** * Sets the ambient color of the surface:. * @param kColor the ambient color of the surface. */ public void setAmbient(ColorRGB kColor) { m_kMaterial.Ambient.Copy(kColor); } /** * Sets the diffuse color of the surface:. * @param kColor the diffuse color of the surface. */ public void setDiffuse(ColorRGB kColor) { m_kMaterial.Diffuse.Copy(kColor); } /** * Sets the emissive color of the surface:. * @param kColor the emissive color of the surface. */ public void setEmissive(ColorRGB kColor) { m_kMaterial.Emissive.Copy(kColor); } /** * Sets the material properties for the surface:. * @param kMaterial material properties for the surface. */ public void setMaterial(MaterialState kMaterial) { m_kMaterial = kMaterial; } /** * Sets the surface shininess:. * @param fShininess surface shininess. */ public void setShininess(float fShininess) { m_kMaterial.Shininess = fShininess; } /** * Sets the specular color of the surface:. * @param kColor specular color of the surface. */ public void setSpecular(ColorRGB kColor) { m_kMaterial.Specular.Copy(kColor); } /** * Used to propagate all FileInfoSurfaceRefXML private variables to other FileInfosSurfaceRefXML. * @param fInfo FileInfoSurfaceRefXML file info to be copied into */ public void updateFileInfos(FileInfoXML fInfo) { if (this == fInfo) { return; } super.updateFileInfos(fInfo); ((FileInfoSurfaceRefXML_WM) fInfo).setMaterial(this.getMaterial()); } }
/** * Copyright (c) 2008-2011, Open & Green Inc. * All rights reserved. * info@gaoshin.com * * This version of SORMA is licensed under the terms of the Open Source GPL 3.0 license. http://www.gnu.org/licenses/gpl.html. Alternate Licenses are available. * * This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, * AND NON-INFRINGEMENT OF THIRD-PARTY INTELLECTUAL PROPERTY RIGHTS. * See the GNU General Public License for more details. * */ package com.gaoshin.sorma.reflection; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.TimeZone; public class XCalendarAdapter { private static final SimpleDateFormat sdf = ReflectionUtil.getIso8601DateFormat(); public static String marshal(Calendar arg0) throws Exception { return sdf.format(arg0.getTime()); } public static Calendar unmarshal(String arg0) throws Exception { Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); cal.setTime(sdf.parse(arg0)); return cal; } }
/****************************************************************************** * __ * * <-----/@@\-----> * * <-< < \\// > >-> * * <-<-\ __ /->-> * * Data / \ Crow * * ^ ^ * * info@datacrow.net * * * * This file is part of Data Crow. * * Data Crow is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public * * License as published by the Free Software Foundation; either * * version 3 of the License, or any later version. * * * * Data Crow is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public * * License along with this program. If not, see http://www.gnu.org/licenses * * * ******************************************************************************/ package net.datacrow.core.objects; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import net.datacrow.console.ComponentFactory; import net.datacrow.core.DcRepository; import net.datacrow.core.data.DataManager; import net.datacrow.core.modules.DcModules; import net.datacrow.util.Base64; import net.datacrow.util.Converter; import net.datacrow.util.DcImageIcon; import net.datacrow.util.Rating; import net.datacrow.util.Utilities; import org.apache.log4j.Logger; /** * The value class represents a field value. * It knows when it has been changed. * * @author Robert Jan van der Waals */ public class DcValue implements Serializable { private static final long serialVersionUID = 3222707222963657152L; private static Logger logger = Logger.getLogger(DcValue.class.getName()); private static final SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); private boolean changed = false; private Object value = null; /** * Indicates if the value has been changed. * @return */ public boolean isChanged() { return changed; } /** * Marks the value as changed. * @param b */ public void setChanged(boolean b) { changed = b; if (!b && value instanceof Picture && value != null) ((Picture) value).markAsUnchanged(); } /** * Bypasses all checks and sets the value directly. * @param newValue The new value to be used. * @param field The field for which the value is set. */ public void setValueLowLevel(Object newValue, DcField field) { if (!field.isUiOnly()) setChanged(true); setValueNative(newValue, field); } /** * Sets the new value for this object. * @param o The new value. * @param field The field for which the value is set. */ @SuppressWarnings("unchecked") public void setValue(Object o, DcField field) { o = o == null || o.equals("null") ? null : o; if (!field.isUiOnly()) setChanged(true); else if (field.getValueType() == DcRepository.ValueTypes._DCOBJECTCOLLECTION) setChanged(true); if (field.getValueType() == DcRepository.ValueTypes._PICTURE) { if (o instanceof Picture) { if (value != null) ((Picture) value).destroy(); setValueNative(o, field); } else { Picture picture = value == null ? (Picture) DcModules.get(DcModules._PICTURE).getItem() : (Picture) value; value = picture; DcImageIcon currentImage = (DcImageIcon) picture.getValue(Picture._D_IMAGE); DcImageIcon newImage = o instanceof DcImageIcon ? (DcImageIcon) o : o instanceof byte[] ? new DcImageIcon((byte[]) o) : null; // prevent empty and incorrect images to be saved if ( newImage != null && newImage.getIconHeight() != 0 && newImage.getIconWidth() != 0) { if (currentImage != null) currentImage.flush(); else picture.setNew(true); picture.setValue(Picture._D_IMAGE, newImage); picture.isEdited(true); setValueNative(picture, field); } else if (currentImage != null) { currentImage.flush(); ((Picture) value).isDeleted(true); setValueNative(picture, field); } } } else if (field.getValueType() == DcRepository.ValueTypes._ICON) { if (o instanceof DcImageIcon) { byte[] bytes = ((DcImageIcon) o).getBytes(); setValueNative(bytes != null ? new String(Base64.encode(bytes)) : null, field); } else if (o != null && o instanceof byte[] && ((byte[]) o).length > 0) setValueNative(new String(Base64.encode((byte[]) o)), field); else setValueNative(o, field); } else { if (o == null) { setValueNative(null, field); } else { if (field.getValueType() == DcRepository.ValueTypes._DCOBJECTCOLLECTION) { if (o instanceof Collection) // always create a new arraylist setValueNative(new ArrayList<DcMapping>((Collection) o), field); else logger.error("Trying to set " + o + " while expecting a collection of mappings object"); } else if (field.getValueType() == DcRepository.ValueTypes._DCOBJECTREFERENCE) { if (Utilities.isEmpty(o)) { setValueNative(null, field); } else if (o instanceof DcObject) { setValueNative(o, field); } else if (!Utilities.isEmpty(o) && field.getReferenceIdx() != field.getModule()) { setValueNative(DataManager.getItem(field.getReferenceIdx(), (String) o), field); } if (getValue() == null && !Utilities.isEmpty(o)) { setValueNative(o, field); // allow string reference to be set logger.debug("Value is still null but new value not empty. Setting value for reference field (" + field + ") value '" + o + "')"); } } else if ( (field.getValueType() == DcRepository.ValueTypes._LONG || field.getValueType() == DcRepository.ValueTypes._DOUBLE ) && !Utilities.isEmpty(o)) { try { if (field.getFieldType() == ComponentFactory._FILESIZEFIELD) { if (o instanceof Long) { setValueNative(o, field); } else if (o instanceof Number) { setValueNative(Long.valueOf(((Number) o).intValue()), field); } else if (o instanceof String && ((String) o).trim().length() > 0) { String num = ""; for (char c : ((String) o).toCharArray()) { if (Character.isDigit(c)) num += c; } setValueNative(Long.valueOf(num), field); } else { throw new NumberFormatException(); } } if (field.getValueType() == DcRepository.ValueTypes._LONG) { if (o instanceof Long) setValueNative(o, field); else if (o instanceof Number) setValueNative(Long.valueOf(((Number) o).intValue()), field); else if (o instanceof String && ((String) o).trim().length() > 0) setValueNative(Long.valueOf(((String) o).trim()), field); else throw new NumberFormatException(); } if (field.getValueType() == DcRepository.ValueTypes._DOUBLE) { if (o instanceof Double) { setValueNative(o, field); } else if (o instanceof Number) { setValueNative(new Double(((Number) o).doubleValue()), field); } else if (o instanceof String && ((String) o).trim().length() > 0) { String s = ((String) o).trim(); s = s.replaceAll(",", "."); try { setValueNative(Double.valueOf(s), field); } catch (NumberFormatException nfe) { logger.error("Could not set " + o + " for " + field.getDatabaseFieldName(), nfe); } } else { throw new NumberFormatException(); } } } catch (Exception e) { logger.error("Could not set " + o + " for " + field + ". Not a number and invalid String.", e); setValueNative(null, field); } } else if (field.getValueType() == DcRepository.ValueTypes._STRING) { String s = Converter.databaseValueConverter((o instanceof String ? (String) o : o.toString())); s = field.getMaximumLength() > 0 && s.length() > field.getMaximumLength() ? s.substring(0, field.getMaximumLength()) : s; setValueNative(s, field); } else if ( field.getValueType() == DcRepository.ValueTypes._DATE || field.getValueType() == DcRepository.ValueTypes._DATETIME) { if (o instanceof Date) { setValueNative(o, field); } else if (o instanceof String) { try { Date date = !o.equals("") ? formatter.parse((String) o) : null; setValueNative(date, field); } catch (java.text.ParseException e) { try { Date date = new SimpleDateFormat().parse((String) o); setValueNative(date, field); } catch (java.text.ParseException e2) { logger.debug("Could not parse date for field " + field.getLabel(), e2); } } } } else { // for all other cases: just set the value setValueNative(o, field); } } } } private void setValueNative(Object value, DcField field) { this.value = value; this.changed = true; } /** * Clears the value and sets it to null. * @param nochecks Just do it, do not check whether we are dealing with an edited item */ public void clear() { value = null; } public Object getValue() { return value; } /** * Creates a string representation. */ public String getValueAsString() { return value != null ? value.toString() : ""; } @SuppressWarnings("unchecked") public String getDisplayString(DcField field) { Object o = getValue(); String text = ""; try { if (!Utilities.isEmpty(o)) { if (field.getFieldType() == ComponentFactory._REFERENCESFIELD) { Collection<DcMapping> mappings = (Collection<DcMapping>) o; if (mappings != null) { boolean first = true; for (DcMapping mapping : mappings) { if (!first) text += ", "; text += mapping; first = false; } } } else if (field.getFieldType() == ComponentFactory._RATINGCOMBOBOX) { int value = o != null ? ((Long) o).intValue() : -1; text = Rating.getLabel(value); } else if (field.getFieldType() == ComponentFactory._TIMEFIELD) { Calendar cal = Calendar.getInstance(); cal.clear(); int value = 0; if (o instanceof String) value = Integer.parseInt((String) o); if (o instanceof Long) value = ((Long) o).intValue(); int minutes = 0; int seconds = 0; int hours = 0; if (value != 0) { cal.set(Calendar.SECOND, value); minutes = cal.get(Calendar.MINUTE); seconds = cal.get(Calendar.SECOND); hours = cal.get(Calendar.HOUR_OF_DAY); } String sSeconds = getDoubleDigitString(seconds); String sMinutes = getDoubleDigitString(minutes); text = "" + hours + ":" + sMinutes + ":" + sSeconds; } else if (field.getValueType() == DcRepository.ValueTypes._DOUBLE) { text = Utilities.toString((Double) o); } else if (field.getFieldType() == ComponentFactory._FILESIZEFIELD) { text = Utilities.toFileSizeString((Long) o); } else if (field.getFieldType() == ComponentFactory._FILEFIELD || field.getFieldType() == ComponentFactory._FILELAUNCHFIELD) { text = Utilities.getValidPath((String) o); } else { text = o == null ? "" : o instanceof String ? (String) o : o.toString(); } } } catch (Exception e) { logger.error("Error while creating the display string for field " + field + ", value " + o, e); } return text; } private String getDoubleDigitString(int value) { StringBuffer sb = new StringBuffer(); if (value == 0) { sb.append("00"); } else if (value < 10) { sb.append("0"); sb.append(value); } else { sb.append(value); } return sb.toString(); } @Override protected void finalize() throws Throwable { clear(); super.finalize(); } }
/* * 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 co.edu.uniandes.csw.mueblesdelosalpes.dto; /** * * @author don_d */ public class Oferta { private int idOferta; private String comprador; private int mRef; private int oferta; public Oferta() { } public Oferta(int idOferta,String comprador,int mRef,int oferta){ this.idOferta = idOferta; this.comprador=comprador; this.mRef=mRef; this.oferta = oferta; } public int getIdOferta() { return idOferta; } public void setIdOferta(int idOferta) { this.idOferta = idOferta; } public String getComprador() { return comprador; } public void setComprador(String comprador) { this.comprador = comprador; } public int getmRef() { return mRef; } public void setmRef(int mRef) { this.mRef = mRef; } }
package com.example.bublly.bemedisure; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import java.util.ArrayList; import java.util.Arrays; public class Doctor_Search extends AppCompatActivity { private static ListView mainListView; private ArrayAdapter<String> listAdapter ; String[] planets = new String[] { "Audiologist", "Allergist" , "Cardiologist", "Dentist", "Dermatologist", "Gynecologist" , "Microbiologist", "Orthopedic Surgeon" , "Physician" , "Pediatrician" , "Psychiatrist"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_doctor__search); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setDisplayShowHomeEnabled(true); mainListView = (ListView) findViewById(R.id.mainListView); // Create and populate a List of planet names ArrayList<String> planetList = new ArrayList<String>(); planetList.addAll(Arrays.asList(planets)); // Create ArrayAdapter using the planet list. listAdapter = new ArrayAdapter<String>(this, R.layout.list_view, planetList); // Add more planets. If you passed a String[] instead of a List<String> // into the ArrayAdapter constructor, you must not add more items. // Otherwise an exception will occur. // Set the ArrayAdapter as the ListView's adapter. mainListView.setAdapter(listAdapter); mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { switch (position) { case 0: Intent new_Activity = new Intent(Doctor_Search.this, Audiologist.class); startActivity(new_Activity); break; case 1: Intent newActivity1 = new Intent(Doctor_Search.this, Allergist.class); startActivity(newActivity1); break; case 2: Intent newActivity2 = new Intent(Doctor_Search.this, Cardiologist.class); startActivity(newActivity2); break; case 3: Intent newActivity3 = new Intent(Doctor_Search.this, Dentist.class); startActivity(newActivity3); break; case 4: Intent newActivity4 = new Intent(Doctor_Search.this, Dermatolosist.class); startActivity(newActivity4); break; case 5: Intent newActivity5 = new Intent(Doctor_Search.this, Microbiologist.class); startActivity(newActivity5); break; case 6: Intent newActivity6 = new Intent(Doctor_Search.this, Gynecologist.class); startActivity(newActivity6); break; case 7: Intent newActivity7 = new Intent(Doctor_Search.this, Orthopedic_Surgeon.class); startActivity(newActivity7); break; case 8: Intent newActivity8 = new Intent(Doctor_Search.this, Physician.class); startActivity(newActivity8); break; case 9: Intent newActivity9 = new Intent(Doctor_Search.this, Pediatrician.class); startActivity(newActivity9); break; case 10: Intent newActivity10 = new Intent(Doctor_Search.this, Psychiatrist.class); startActivity(newActivity10); break; } } @SuppressWarnings("unused") public void onClick(View v) { } }); } /*@Override protected void onListItemClick(ListView l, View v, int position, long id) { // TODO Auto-generated method stub super.onListItemClick(l, v, position, id); if (position == 0) { Intent intent = new Intent(this, QuizActivity.class); startActivity(intent); } else if (position == 1) { Intent intent = new Intent(this, SignUp.class); startActivity(intent); } else if (position == 2) { Intent intent = new Intent(this, FriendList.class); startActivity(intent); } }*/ }
package com.joalib.member.svc; import com.joalib.DAO.memberinfoDAO; public class MemberDeleteService { public boolean memberDelete (String member_id) { boolean isSuccess = false; memberinfoDAO dao = memberinfoDAO.getinstance(); int i = dao.memberDel(member_id); if(i > 0) { isSuccess = true; } return isSuccess; } }
package com.lenovohit.hcp.odws.web.rest; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import com.alibaba.fastjson.TypeReference; import com.lenovohit.core.dao.Page; import com.lenovohit.core.exception.BaseException; import com.lenovohit.core.manager.GenericManager; import com.lenovohit.core.utils.JSONUtils; import com.lenovohit.core.web.MediaTypes; import com.lenovohit.core.web.utils.Result; import com.lenovohit.core.web.utils.ResultUtils; import com.lenovohit.hcp.appointment.model.RegInfo; import com.lenovohit.hcp.base.manager.IRedisSequenceManager; import com.lenovohit.hcp.base.model.ChargeDetail; import com.lenovohit.hcp.base.model.ChargePkg; import com.lenovohit.hcp.base.model.CommonItemInfo; import com.lenovohit.hcp.base.model.HcpUser; import com.lenovohit.hcp.base.web.rest.HcpBaseRestController; import com.lenovohit.hcp.card.model.Patient; import com.lenovohit.hcp.finance.model.OutpatientChargeDetail; import com.lenovohit.hcp.odws.manager.OrderManager; import com.lenovohit.hcp.odws.manager.OrderRetreatManager; import com.lenovohit.hcp.odws.model.MedicalOrder; import com.lenovohit.hcp.pharmacy.model.PhaDrugInfo; import com.lenovohit.hcp.pharmacy.model.PhaRecipe; import com.lenovohit.hcp.pharmacy.model.RecipeInfo; /** * 医嘱 */ @RestController @RequestMapping("/hcp/odws/medicalOrder") public class MedicalOrderController extends HcpBaseRestController { @Autowired private GenericManager<MedicalOrder, String> medicalOrderManager; @Autowired private GenericManager<ChargePkg, String> chargePkgManager; @Autowired private GenericManager<ChargeDetail, String> chargeDetailManager; @Autowired private IRedisSequenceManager redisSequenceManager; @Autowired private GenericManager<CommonItemInfo, String> commonItemInfoManager; @Autowired private GenericManager<OutpatientChargeDetail, String> outpatientChargeDetailManager; @Autowired private GenericManager<RegInfo, String> regInfoManager; @Autowired private GenericManager<PhaRecipe, String> phaRecipeManager; @Autowired private GenericManager<RecipeInfo, String> recipeInfoManager; @Autowired private OrderRetreatManager orderReTreateManager; @Autowired private GenericManager<PhaDrugInfo, String> phaDrugInfoManager; @Autowired private OrderManager orderManager; /** * 根据挂号id取所有已下医嘱 * @param regId * @return */ @RequestMapping(value = "/list/{regId}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result forDiagnosisPage(@PathVariable("regId") String regId) { List<Object> values = new ArrayList<Object>(); StringBuilder jql = new StringBuilder("from MedicalOrder where regId = ? and ( orderState = 1 or orderState = 2 or orderState = 3 ) order by recipeId, recipeNo "); values.add(regId); List<MedicalOrder> list = (List<MedicalOrder>) medicalOrderManager.find(jql.toString(), values.toArray()); return ResultUtils.renderPageResult(list); } /** * 根据挂号id取所有已下医嘱,如果该医嘱已经修改过,则返回提示信息。 * @param regId * @return */ @RequestMapping(value = "/listorder/{regId}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result listorders(@PathVariable("regId") String regId) { List<Object> values = new ArrayList<Object>(); //StringBuilder jql = new StringBuilder("from MedicalOrder where regId = ? and orderState = 4 order by recipeId, recipeNo "); values.add(regId); //List<MedicalOrder> list = (List<MedicalOrder>) medicalOrderManager.find(jql.toString(), values.toArray()); //if(list.size()!=0){ // return ResultUtils.renderFailureResult("您的医嘱正在修改过程中,退药流程走完之后再来修改"); //} StringBuilder sql = new StringBuilder("from MedicalOrder where regId = ? and orderState != 5 order by recipeId, recipeNo "); List<MedicalOrder> lists = (List<MedicalOrder>) medicalOrderManager.find(sql.toString(), values.toArray()); for(MedicalOrder order : lists){ if(order.getItemId() != null){ PhaDrugInfo info = this.phaDrugInfoManager.findOneByProp("id", order.getItemId()); order.setPhaDrugInfo(info); } } return ResultUtils.renderPageResult(lists); } /** * 门诊退药 * @param regId * @return */ @RequestMapping(value = "/withDrawal", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8) public Result withDrawal(@RequestBody String data) { System.out.println(data); HcpUser user=this.getCurrentUser(); List<MedicalOrder> models = (List<MedicalOrder>) JSONUtils.parseObject(data,new TypeReference< List<MedicalOrder>>(){}); try{ orderReTreateManager.orderBack(models,user); return ResultUtils.renderSuccessResult(); }catch(Exception e){ System.err.println(e.getMessage()); return ResultUtils.renderFailureResult(e.getMessage()); } } /** * 根据条件查询患者医嘱 * @param * @return */ @RequestMapping(value = "/page/{start}/{limit}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result forPage(@PathVariable("start") String start, @PathVariable("limit") String limit, @RequestParam(value = "data", defaultValue = "") String data) { System.out.println(data); HcpUser user = this.getCurrentUser(); Page page = new Page(); page.setStart(start); page.setPageSize(limit); MedicalOrder query = JSONUtils.deserialize(data, MedicalOrder.class); System.out.println(query); Date[] date = query.getDateRange(); StringBuilder jql = new StringBuilder("from RegInfo ri where hosId = ? "); List<Object> values = new ArrayList<Object>(); values.add(user.getHosId()); if (date != null && date.length == 2) { jql.append("and ri.createTime between ? and ? "); values.add(query.getDateRange()[0]); values.add(query.getDateRange()[1]); } // 诊疗卡/患者姓名/患者身份证号 if (StringUtils.isNotBlank(query.getMedicalCardNo()) || StringUtils.isNotBlank(query.getPatientName()) || StringUtils.isNotBlank(query.getIdNo())) { // 诊疗卡 if (!StringUtils.isEmpty(query.getMedicalCardNo())) { jql.append("and ri.patient.medicalCardNo like ? "); values.add("%" + query.getMedicalCardNo() + "%"); } // 患者姓名 if (!StringUtils.isEmpty(query.getPatientName())) { jql.append("and ri.patient.name like ? "); values.add("%" + query.getPatientName() + "%"); } // 患者身份证号 if (!StringUtils.isEmpty(query.getIdNo())) { jql.append("and ri.patient.idNo like ? "); values.add("%" + query.getIdNo() + "%"); } } jql.append(" order by ri.regTime desc "); page.setQuery(jql.toString()); page.setValues(values.toArray()); regInfoManager.findPage(page); List<RegInfo> reginfos=(List<RegInfo>) page.getResult(); if(reginfos!=null&&reginfos.size()!=0) { for(int i=0;i<reginfos.size();i++){ List<MedicalOrder> orders=medicalOrderManager.findByProp("regId", reginfos.get(i).getId()); reginfos.get(i).setOrders(orders); } page.setResult(reginfos); } return ResultUtils.renderPageResult(page); } /** * 保存医嘱明细(门诊医生站医生直接开立医嘱明细) * @param data * @return */ @RequestMapping(value = "/item/save", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8) public Result forSaveItem(@RequestBody String data) { MedicalOrder model = JSONUtils.deserialize(data, MedicalOrder.class); MedicalOrder saved = orderManager.savItem(model,this.getCurrentUser()); return ResultUtils.renderSuccessResult(saved); } /** * 保存医嘱明细(门诊医生站医生通过模板开立医嘱) * @param tmplId * @return */ @RequestMapping(value = "/item/saveByTmpl/{tmplId}/{regId}/{patientId}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result forSaveByTmpl(@PathVariable("tmplId") String tmplId, @PathVariable("regId") String regId, @PathVariable("patientId") String patientId) { // 获取组套及组套明细信息 ChargePkg tmpl = chargePkgManager.get(tmplId); List<ChargeDetail> tmplItems = chargeDetailManager.find("from ChargeDetail where comboId = '" + tmplId + "' order by comboSort"); // 获取所有明细对应的通用收费项id List<Object> itemIds = (List<Object>)chargeDetailManager.findByJql("select itemId from ChargeDetail where comboId = '" + tmplId + "' order by comboSort"); // 获取收费项详情 StringBuffer ids = new StringBuffer("("); int i = 0; for (Object id : itemIds) { if (i != 0) ids.append(","); ids.append("'" + (String)id + "'"); i += 1; } ids.append(")"); if(ids.toString().equals("()")){ return ResultUtils.renderFailureResult("该套餐下没有套餐明细"); } List<CommonItemInfo> commonItems = (List<CommonItemInfo>)commonItemInfoManager.find("from CommonItemInfo where itemId in " + ids); HashMap<String, CommonItemInfo> commonItemsMap = new HashMap<String, CommonItemInfo>(); for (CommonItemInfo item : commonItems) { commonItemsMap.put(item.getItemId(), item); } // 获取已有的医嘱 List<Object> values = new ArrayList<Object>(); StringBuilder jql = new StringBuilder("from MedicalOrder a where a.regId = ? "); values.add(regId); List<MedicalOrder> orderList = medicalOrderManager.find(jql.toString(), values); // 根据组套明细循环插入医嘱表 for (ChargeDetail item : tmplItems) { MedicalOrder model = new MedicalOrder(); MedicalOrder order=isHasItemCode(orderList,item.getItemCode()); //如果已经存在该条医嘱(组号也相同),且未收费,则合并; if(order != null && "1".equals(order.getOrderState()) && item.getComboNo().equals(order.getComboNo())){ model = order; model.setQty(order.getQty().add(item.getDefaultNum())); }else{ model.setRegId(regId); // 挂号id Patient p = new Patient(); p.setId(patientId); model.setPatientInfo(p); // 患者id model.setDrugFlag(item.getDrugFlag()); // 药品标识 model.setComboNo(item.getComboNo()); // 组合号 model.setItemId(item.getItemId()); // 项目id model.setItemCode(item.getItemCode()); // 项目编码 model.setItemName(item.getItemName()); // 项目名称 model.setFeeCode(commonItemsMap.get(item.getItemId()).getFeeCode()); // 费用分类 model.setSpecs(commonItemsMap.get(item.getItemId()).getItemSpecs()); // 药品规格 model.setUnit(commonItemsMap.get(item.getItemId()).getItemUnit()); // 包装单位 model.setSalePrice(commonItemsMap.get(item.getItemId()).getSalePrice()); // 售价 model.setUsage(item.getUsage()); // 用法 model.setFreq(item.getFreq()); // 频次 model.setFreqDesc(item.getFreqDesc()); // 频次描述 model.setDays(item.getDays()); // 执行天数 model.setQty(item.getDefaultNum()); // 总数量 model.setDoseOnce(item.getDosage()); // 一次剂量 model.setDoseUnit(item.getDosageUnit()); // 剂量单位 model.setExeDept(item.getDefaultDept()); // 执行科室 } orderManager.savItem(model,this.getCurrentUser()); } return ResultUtils.renderSuccessResult(); } /** * 判断已有医嘱是否包含该药品 * @param orderList * @param comboNo * @return */ protected MedicalOrder isHasItemCode(List<MedicalOrder> orderList, String itemCode){ MedicalOrder MedicalOrder = null; if(orderList!=null&&orderList.size()>0){ for(MedicalOrder order : orderList){ if(itemCode.equals(order.getItemCode()) || order.getItemCode() == itemCode){ MedicalOrder = order; } } } return MedicalOrder; } /** * 删除明细 * @param id * @return */ @RequestMapping(value = "/item/remove/{id}", method = RequestMethod.DELETE, produces = MediaTypes.JSON_UTF_8) public Result forDeleteItem(@PathVariable("id") String id) { try { MedicalOrder toDel = this.medicalOrderManager.get(id); //如果是组套,会删除整个组套 if(toDel.getComboNo()!=null){ List<Object> val = new ArrayList<Object>(); StringBuilder jql = new StringBuilder("from MedicalOrder where comboNo = ? and regId = ? order by recipeId, recipeNo "); val.add(toDel.getComboNo()); val.add(toDel.getRegId()); List<MedicalOrder> list = medicalOrderManager.find(jql.toString(), val.toArray()); if(list!=null && list.size()>0){ for(MedicalOrder order: list){ // 更改排序 List<Object> values = new ArrayList<Object>(); values.add(order.getRecipeId()); values.add(order.getRecipeNo()); this.medicalOrderManager.executeSql("update OW_ORDER set RECIPE_NO = RECIPE_NO - 1 where RECIPE_ID = ? and RECIPE_NO > ? ", values.toArray()); this.medicalOrderManager.delete(order.getId()); // 更改收费明细中的排序 this.outpatientChargeDetailManager.executeSql("update OC_CHARGEDETAIL set RECIPE_NO = RECIPE_NO - 1 where RECIPE_ID = ? and RECIPE_NO > ? ", values.toArray()); // 删除收费明细 this.outpatientChargeDetailManager.executeSql("delete from OC_CHARGEDETAIL where ORDER_ID = '" + order.getId() + "'"); } } }else{ // 更改排序 List<Object> values = new ArrayList<Object>(); values.add(toDel.getRecipeId()); values.add(toDel.getRecipeNo()); this.medicalOrderManager.executeSql("update OW_ORDER set RECIPE_NO = RECIPE_NO - 1 where RECIPE_ID = ? and RECIPE_NO > ? ", values.toArray()); this.medicalOrderManager.delete(id); // 更改收费明细中的排序 this.outpatientChargeDetailManager.executeSql("update OC_CHARGEDETAIL set RECIPE_NO = RECIPE_NO - 1 where RECIPE_ID = ? and RECIPE_NO > ? ", values.toArray()); // 删除收费明细 this.outpatientChargeDetailManager.executeSql("delete from OC_CHARGEDETAIL where ORDER_ID = '" + toDel.getId() + "'"); } } catch (Exception e) { throw new BaseException("删除失败"); } return ResultUtils.renderSuccessResult(); } /** * 明细成组 * @param data * @return */ @RequestMapping(value = "/item/makeGruop", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result makeGroup(@RequestParam(value = "data", defaultValue = "") String data) { List ids = JSONUtils.deserialize(data, List.class); // 取自增组合号 int comboNo = redisSequenceManager.getSeq("OW_ORDER", "COMBO_NO").getSeq().intValue(); // 需要组合的id StringBuffer idsSymbol = new StringBuffer(""); List<Object> values = new ArrayList<Object>(); values.add(comboNo); for(int i = 0; i < ids.size(); i++){ idsSymbol.append("?"); values.add(ids.get(i).toString()); if(i != ids.size() - 1) idsSymbol.append(","); } // 更新医嘱表组合号 StringBuffer jql = new StringBuffer("update OW_ORDER set COMBO_NO = ? where ID in (").append(idsSymbol).append(")"); this.medicalOrderManager.executeSql(jql.toString(), values.toArray()); // 更新收费表组合号 jql = new StringBuffer("update OC_CHARGEDETAIL set COMB_NO = ? where ORDER_ID in (").append(idsSymbol).append(")"); this.outpatientChargeDetailManager.executeSql(jql.toString(), values.toArray()); return ResultUtils.renderSuccessResult(); } /** * 从组合中删除 * @param data * @return */ @RequestMapping(value = "/item/deleteFromGroup", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result deleteFromGroup(@RequestParam(value = "data", defaultValue = "") String data) { List ids = JSONUtils.deserialize(data, List.class); // 需要组合的id StringBuffer idsSymbol = new StringBuffer(""); List<Object> values = new ArrayList<Object>(); values.add(null); for(int i = 0; i < ids.size(); i++){ idsSymbol.append("?"); values.add(ids.get(i).toString()); if(i != ids.size() - 1) idsSymbol.append(","); } // 更新医嘱表组合号 StringBuffer jql = new StringBuffer("update OW_ORDER set COMBO_NO = ? where ID in (").append(idsSymbol).append(")"); this.medicalOrderManager.executeSql(jql.toString(), values.toArray()); // 更新收费表组合号 jql = new StringBuffer("update OC_CHARGEDETAIL set COMB_NO = ? where ORDER_ID in (").append(idsSymbol).append(")"); this.outpatientChargeDetailManager.executeSql(jql.toString(), values.toArray()); return ResultUtils.renderSuccessResult(); } /** * 明细排序 * @param data * @return */ @RequestMapping(value = "/item/sort", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result sortItems(@RequestParam(value = "data", defaultValue = "") String data) { List ids = JSONUtils.deserialize(data, List.class); StringBuffer orderJql = new StringBuffer("update OW_ORDER set RECIPE_NO = ? where ID = ? "); StringBuffer cdJql = new StringBuffer("update OC_CHARGEDETAIL set RECIPE_NO = ? where ORDER_ID = ? "); for(int i = 0; i < ids.size(); i++){ List<Object> values = new ArrayList<Object>(); values.add(i + 1); values.add(ids.get(i).toString()); this.medicalOrderManager.executeSql(orderJql.toString(), values.toArray()); this.outpatientChargeDetailManager.executeSql(cdJql.toString(), values.toArray()); } return ResultUtils.renderSuccessResult(); } /** * 根据条件查询退药情况 * @param * @return */ @RequestMapping(value = "/loadBack/{start}/{limit}", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8) public Result loadBack(@PathVariable("start") String start, @PathVariable("limit") String limit, @RequestParam(value = "data", defaultValue = "") String data) { HcpUser user = this.getCurrentUser(); Page page = new Page(); page.setStart(start); page.setPageSize(limit); MedicalOrder query = JSONUtils.deserialize(data, MedicalOrder.class); System.out.println(query); Date[] date = query.getDateRange(); StringBuilder jql = new StringBuilder("from RecipeInfo ri where ri.hosId = ? and ri.applyState = ? "); List<Object> values = new ArrayList<Object>(); values.add(user.getHosId()); values.add(RecipeInfo.APPLY_STATE_APPLY); //已申请未退药 if (date != null && date.length == 2) { jql.append("and ri.createTime between ? and ? "); values.add(query.getDateRange()[0]); values.add(query.getDateRange()[1]); } // 诊疗卡/患者姓名/患者身份证号 if (StringUtils.isNotBlank(query.getMedicalCardNo()) || StringUtils.isNotBlank(query.getPatientName()) || StringUtils.isNotBlank(query.getIdNo())) { // 诊疗卡 if (!StringUtils.isEmpty(query.getMedicalCardNo())) { jql.append("and ri.medicalCardNo like ? "); values.add("%" + query.getMedicalCardNo() + "%"); } // 患者姓名 if (!StringUtils.isEmpty(query.getPatientName())) { jql.append("and ri.name like ? "); values.add("%" + query.getPatientName() + "%"); } // 患者身份证号 if (!StringUtils.isEmpty(query.getIdNo())) { jql.append("and ri.idNo like ? "); values.add("%" + query.getIdNo() + "%"); } } jql.append(" order by ri.regTime desc "); page.setQuery(jql.toString()); page.setValues(values.toArray()); recipeInfoManager.findPage(page); List<RecipeInfo> reginfos=(List<RecipeInfo>) page.getResult(); if(reginfos!=null && reginfos.size()!=0) { for(int i=0;i<reginfos.size();i++){ StringBuilder j = new StringBuilder("from PhaRecipe ri where ri.hosId = ? and ri.regId = ? and ri.applyState in (? , ?) order by ri.drugCode "); List<Object> v = new ArrayList<Object>(); v.add(user.getHosId()); v.add(reginfos.get(i).getId()); v.add(PhaRecipe.APPLY_STATE_DISPENSED); v.add(PhaRecipe.APPLY_STATE_APPLY); List<PhaRecipe> orders=phaRecipeManager.find(j.toString(), v.toArray()); List<PhaRecipe> ordList = new ArrayList<PhaRecipe>(); //数据处理:获取退药的数量 if(orders != null && orders.size()>0){ for(int s = 0;s<orders.size(); s++){ if(PhaRecipe.APPLY_STATE_DISPENSED.equals(orders.get(s).getApplyState())){ if(s>0 && orders.get(s-1).getId().equals(orders.get(s).getDataFrom())){ orders.get(s).setApplyNum(orders.get(s-1).getApplyNum().subtract(orders.get(s).getApplyNum())); } if(s < orders.size()-1 && orders.get(s+1).getId().equals(orders.get(s).getDataFrom())){ orders.get(s).setApplyNum(orders.get(s+1).getApplyNum().subtract(orders.get(s).getApplyNum())); } if(orders.get(s).getApplyNum().compareTo(BigDecimal.ZERO)!=0){ ordList.add(orders.get(s)); } } } } reginfos.get(i).setDetailList(ordList); } page.setResult(reginfos); } return ResultUtils.renderPageResult(page); } }
package org.cloudbus.cloudsim.network.datacenter; import net.sourceforge.jswarm_pso.FitnessFunction; public class MyFitnessFunction extends FitnessFunction{ public MyFitnessFunction(double[][] td, double[] et, double[][] vd, double[][] vt){ super(false); workFlowDataTrans = td; workFlowTaskExcution = et; vmData = vd; vmTransferCost = vt; } public double evaluate(double position[]) { double fitnessValue = 0; int[] intPosition = new int[position.length]; //System.out.println("position.length: " + position.length); for(int i = 0; i < position.length; i++ ) { intPosition[i] = (int)position[i]; } double[] vmCost = new double[vmData.length]; // calculate each task's total cost, and add to the vm's cost the task assigned to for(int i = 0; i < position.length; i++ ) { int vmNum = intPosition[i]; System.out.print(intPosition[i]+"+"); double taskCost = workFlowTaskExcution[i] / vmData[vmNum][0] * vmData[vmNum][1]; //add execution cost //System.out.println("workFlowTaskExcution[i]: " + workFlowTaskExcution[i]); //System.out.println("vmData[vmNum][0]" + vmData[vmNum][0]); //System.out.println("vmData[vmNum][1]" + vmData[vmNum][1]); double taskDataTransferCost = 0; for(int j = 0; j < workFlowDataTrans[i].length; j++) { if(workFlowDataTrans[i][j] != 0) { taskDataTransferCost += workFlowDataTrans[i][j] * vmTransferCost[vmNum][intPosition[j]]; //add the task output file transfer cost } } //System.out.println("taskCost: " + taskCost); //System.out.println("taskDataTransferCost: " + taskDataTransferCost); vmCost[vmNum] = taskDataTransferCost + taskCost; //System.out.println("vmCost[vmNum]: " + vmCost[vmNum]); } fitnessValue = max(vmCost); System.out.println("fitnessValue: " + fitnessValue); return fitnessValue; } /** * get max value in a array * @param list input array * @return the max vlaue */ private double max(double[] list) { double max = 0; for(int i = 0; i < list.length; i++ ) { if (list[i] > max) { max = list[i]; } } return max; } private double[][] workFlowDataTrans; private double[] workFlowTaskExcution; private double[][] vmData; private double[][] vmTransferCost; }
package com.study.pattern.state; /** * @author * */ public class MobileRingMode { private AlertState alertState; public MobileRingMode() { alertState= new Ring(); } public void setAlertState(AlertState alertState) { this.alertState=alertState; } public void showAlert() { alertState.alert(); } }
package ex0428; import java.util.Date; public class SVO { private String scode; private String sdept; private String year; private Date birthday; private String pname; private String pdept; private String sname; public String getScode() { return scode; } public void setScode(String scode) { this.scode = scode; } public String getSdept() { return sdept; } public void setSdept(String sdept) { this.sdept = sdept; } public String getYear() { return year; } public void setYear(String year) { this.year = year; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getPname() { return pname; } public void setPname(String pname) { this.pname = pname; } public String getPdept() { return pdept; } public void setPdept(String pdept) { this.pdept = pdept; } public String getSname() { return sname; } public void setSname(String sname) { this.sname = sname; } }
/* * 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 object; import data.DataAccess; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author PhiLong */ public class BorrowingManagement { private String BorrowID; private String RdID; private String BookID; private Date BorrowDate; private Date ReturnDate; public DataAccess da = new DataAccess(); public PreparedStatement ps = null; public BorrowingManagement(String BorrowID, String RdID, String BookID, Date BorrowDate, Date ReturnDate) { this.BorrowID = BorrowID; this.RdID = RdID; this.BookID = BookID; this.BorrowDate = BorrowDate; this.ReturnDate = ReturnDate; } public String getBorrowID() { return BorrowID; } public void setBorrowID(String BorrowID) { this.BorrowID = BorrowID; } public String getRdID() { return RdID; } public void setRdID(String RdID) { this.RdID = RdID; } public String getBookID() { return BookID; } public void setBookID(String BookID) { this.BookID = BookID; } public Date getBorrowDate() { return BorrowDate; } public void setBorrowDate(Date BorrowDate) { this.BorrowDate = BorrowDate; } public Date getReturnDate() { return ReturnDate; } public void setReturnDate(Date ReturnDate) { this.ReturnDate = ReturnDate; } public String getRdName(String id) throws Exception { ResultSet re = da.getData("select RdName from reader,borrowingmanagement where BorrowID = '" + id + "' and reader.RdID = borrowingmanagement.RdID"); String kq = ""; while (re.next()) { kq = re.getString("RdName"); } return kq; } public String getRdEmail(String id) { ResultSet re = da.getData("select Email from reader,borrowingmanagement where BorrowID = '" + id + "' and reader.RdID = borrowingmanagement.RdID"); String kq = ""; try { while (re.next()) { kq = re.getString("Email"); } } catch (SQLException ex) { Logger.getLogger(BorrowingManagement.class.getName()).log(Level.SEVERE, null, ex); } return kq; } public Vector toVector() { DateFormat d = new SimpleDateFormat("yyyy-MM-dd"); Vector v = new Vector(); v.addElement(this.BorrowID); v.addElement(this.RdID); v.addElement(this.BookID); v.addElement(d.format(this.BorrowDate)); v.addElement(d.format(this.ReturnDate)); v.addElement("+"); return v; } }
package com.eme.aelegant.ui; import android.os.Bundle; import android.widget.RelativeLayout; import android.widget.TextView; import com.eme.aelegant.App; import com.eme.aelegant.R; import com.eme.aelegant.base.BaseRxActivity; import com.eme.aelegant.contract.MainContract; import com.eme.aelegant.injector.component.DaggerViewComponent; import com.eme.aelegant.injector.module.ViewModule; import com.eme.aelegant.model.bean.ZhihuDaily; import com.eme.aelegant.presenter.MainPresenter; import butterknife.BindView; import butterknife.ButterKnife; /** * 应用入口页 */ public class MainActivity extends BaseRxActivity<MainPresenter> implements MainContract.View { @BindView(R.id.tv_show) TextView tvShow; @BindView(R.id.activity_main) RelativeLayout activityMain; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // TODO: add setContentView(...) invocation ButterKnife.bind(this); } @Override public void show(ZhihuDaily zhihuDaily) { tvShow.setText(zhihuDaily.toString()); } @Override protected void initInject() { DaggerViewComponent.builder().appComponent(App.getAppInstance().getAppComponent()).viewModule(new ViewModule(this)).build().inject(this); } @Override protected int getLayout() { return R.layout.activity_main; } @Override protected void initEventAndData() { mPresenter.subscribe(); } }
package com.example.demo; public class Adapter { public static void main(String[] args) { //todo more logics //DispatcherServlet } }
package com.myvodafone.android.front.support; /** * Created by d.alexandrakis on 27/4/2016. */ public class UserInfo { private String username,password,number,afm,email = ""; public UserInfo(){} public UserInfo(String username, String msisdn, String afm){ this.username = username; this.number = msisdn; this.afm = afm; } 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 getNumber() { return number; } public void setNumber(String number) { this.number = number; } public String getAfm() { return afm; } public void setAfm(String afm) { this.afm = afm; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
package ru.bookstore.domain; import javax.persistence.*; @Entity @Table(name = "books_authors") public class BooksAuthorsEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", updatable = false, nullable = false) private Integer id; @Column(name = "book", nullable = false) private int book; @Column(name = "author", nullable = false) private int author; public BooksAuthorsEntity(int book, int author) { this.book = book; this.author = author; } public BooksAuthorsEntity() { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public int getBook() { return book; } public void setBook(int book) { this.book = book; } public int getAuthor() { return author; } public void setAuthor(int author) { this.author = author; } }
package com.yusys.workFlow; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Service; import com.yusys.Utils.DateTimeUtils; import com.yusys.Utils.RequestUtils; import com.yusys.Utils.TaskDBUtil; import com.yusys.workFlow.WorkFlowNodeDao; import com.yusys.workFlow.SWorkFlowInfoDao; @Service("iSWorkFlowNodeService") public class SWorkFlowNodeService implements ISWorkFlowNodeService{ @Resource private SWorkFlowInfoDao sWorkFlowInfoDao; @Resource private WorkFlowNodeDao workFlowNodeDao; @Resource private TaskDBUtil taskDBUtil; //新增保存 @Override public Map<String, String> addNodeInfo(HttpServletRequest req) { Map<String, String> resultMap=new HashMap<String, String>(); try { //必填参数列表 String[] must=new String[]{"wf_id","n_name","is_start","n_type","is_auto","n_v_type","r_exp","r_name","order_id","n_state"}; //非必填的参数列表 String[] nomust=new String[]{"memo"}; Map<String, String> pmap=RequestUtils.requestToMap(req, must, nomust); if (pmap==null) { resultMap.put("result", "false"); return resultMap; } String n_id= taskDBUtil.getSequenceValByName("WF_SEQ_WF_NOTE"); //生成规则id String r_id= taskDBUtil.getSequenceValByName("WF_SEQ_WF_RULE"); pmap.put("r_id", r_id);//规则ID pmap.put("n_id", n_id);//节点ID pmap.put("opt_person", "admin");//创建人 pmap.put("opt_time", DateTimeUtils.getFormatCurrentTime());//创建时间 //向节点表插入信息 workFlowNodeDao.addNodeInfo(pmap); //向规则表插入信息 sWorkFlowInfoDao.addOneRuleInfo(pmap); resultMap.put("result", "true"); return resultMap; } catch (Exception e) { e.printStackTrace(); } resultMap.put("result", "false"); return resultMap; } //修改保存 @Override public Map<String, String> updateNodeInfo(HttpServletRequest req) { Map<String, String> resultMap=new HashMap<String, String>(); try { //必填参数列表 String[] must=new String[]{"r_id","n_id","wf_id","n_name","is_start","n_type","is_auto","n_v_type","r_exp","r_name","order_id","n_state"}; //非必填的参数列表 String[] nomust=new String[]{"memo"}; Map<String, String> pmap=RequestUtils.requestToMap(req, must, nomust); if (pmap==null) { resultMap.put("result", "false"); return resultMap; } pmap.put("opt_person", "admin");//创建人 pmap.put("opt_time", DateTimeUtils.getFormatCurrentTime());//创建时间 //修改规则表数据 sWorkFlowInfoDao.updateOneRuleInfo(pmap); //修改节点表数据 workFlowNodeDao.updateNodeInfo(pmap); resultMap.put("result", "true"); return resultMap; } catch (Exception e) { e.printStackTrace(); } resultMap.put("result", "false"); return resultMap; } //删除节点 @Override public Map<String, String> deleteNodeInfo(HttpServletRequest req) { Map<String, String> resultMap=new HashMap<String, String>(); Map<String, String> pmap=new HashMap<String, String>(); String n_id = RequestUtils.getParamValue(req, "n_id"); pmap.put("n_id", n_id); pmap.put("n_state", "01"); /*//根据id获取节点信息 List<Map<String,Object>> list = workFlowNodeDao.queryOneNodeInfo(pmap); //根据节点id删除对应的规则表信息 if(list.size()>0){ for(Map<String,Object> map:list){ pmap.put("r_id", (String)map.get("R_ID")); sWorkFlowInfoDao.deleteOneRuleInfo(pmap); } } //删除节点表信息 workFlowNodeDao.deleteNodeInfo(pmap);*/ //点击删除按钮修改节点状态为停用 try { workFlowNodeDao.updateNodeStateById(pmap); resultMap.put("result", "true"); } catch (Exception e) { resultMap.put("result", "false"); e.printStackTrace(); } return resultMap; } //查询流程ID下的节点 @Override public Map<String, Object> queryAllNode4WF(HttpServletRequest req) { Map<String, Object> retmap=new HashMap<String, Object>(); Map<String, Object> pmap=new HashMap<String, Object>(); //从前台获取请求参数 String wf_id = RequestUtils.getParamValue(req, "wf_id"); String limit = RequestUtils.getParamValue(req,"limit"); String offset = RequestUtils.getParamValue(req,"offset"); pmap.put("wf_id",wf_id); pmap.put("limit",limit); pmap.put("offset",offset); //调用dao查询数据,返回所有的流程信息 List<Map<String, Object>> list=workFlowNodeDao.queryAllNode4WF(pmap); retmap.put("rows", list); retmap.put("total", pmap.get("total")); return retmap; } //根据条件查找一个节点信息 @Override public Map<String, String> queryOneNodeInfo(HttpServletRequest req) { Map<String, String> resultMap=new HashMap<String, String>(); Map<String, String> pmap=new HashMap<String, String>(); String wf_id = RequestUtils.getParamValue(req, "wf_id"); String order_id = RequestUtils.getParamValue(req, "order_id"); String flag = RequestUtils.getParamValue(req, "flag"); pmap.put("wf_id", wf_id); pmap.put("order_id", order_id); List<Map<String, Object>> nodeList = workFlowNodeDao.queryOneNodeInfo(pmap); //新增保存的校验 if("add".equals(flag)&&nodeList.size()>0){ resultMap.put("result", "true"); //修改保存的校验 }else if("update".equals(flag)&&nodeList.size()>1){ resultMap.put("result", "true"); }else{ resultMap.put("result", "false"); } return resultMap; } //根据ID查找一个节点信息 @Override public Map<String, Object> queryOneNodeById(HttpServletRequest req) { Map<String, Object> resultMap=new HashMap<String, Object>(); Map<String, String> pmap=new HashMap<String, String>(); String n_id = RequestUtils.getParamValue(req, "n_id"); pmap.put("n_id", n_id); List<Map<String, Object>> nodeList = workFlowNodeDao.queryOneNodeInfo(pmap); if(nodeList.size()>0){ resultMap = (Map<String, Object>)nodeList.get(0); }else{ resultMap.put("result", "false"); } return resultMap; } }
package com.lsm.boot.shiro.vo; public enum ResultCode { C200(200, "Success"), C203(203, "No Enough Authority"), C204(204, "No Content"), C301(301, "Request Error"), C400(400, "Client Error"), C403(403, "Forbidden"), C401(401, "Unauthorized Auth"), C412(412, "参数错误"), C415(415, "Error Format"), C422(422, "Error Valid"), C500(500, "Internal Server Error"), C501(501, "User No Login"), C502(502, "页面url不能重复"), C601(601,"外部接口调用出错"); ResultCode(int code, String desc) { this.code = code; this.desc = desc; } private int code; private String desc; public int getCode() { return code; } public String getDesc() { return desc; } }
package eu.tjenwellens.timetracker.main; import android.content.Context; import eu.tjenwellens.timetracker.R; import eu.tjenwellens.timetracker.calendar.Evenement; import eu.tjenwellens.timetracker.calendar.Kalender; import eu.tjenwellens.timetracker.database.DatabaseHandler; import eu.tjenwellens.timetracker.macro.MacroI; /** * * @author Tjen */ public class ActiviteitFactory { private static final String SPLITTER = "\n"; private ActiviteitFactory() { } public static String mergeDetailEntries(String[] strings) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < strings.length; i++) { sb.append(strings[i]); if (i < strings.length - 1) { sb.append(SPLITTER); } } return sb.toString(); } public static String[] splitDetailToEntries(String strings) { return strings.split(SPLITTER); } public static ActiviteitI createActiviteit(Context context, int id, Kalender kalender, String title, long startTimeMillis, long endTimeMillis) { Activiteit a = new Activiteit(id, kalender, title, startTimeMillis, endTimeMillis); a.saveDBActiviteit(context); return a; } public static ActiviteitI loadActiviteit(Context context, int id, Kalender kalender, String title, long startTimeMillis, long endTimeMillis, String description) { return new Activiteit(id, kalender, title, startTimeMillis, endTimeMillis, description); } public static ActiviteitI createActiviteit(Context context) { Activiteit a = new Activiteit(Kalender.getDefaultKalender(context), context.getString(R.string.activiteit_prefix)); a.saveDBActiviteit(context); return a; } public static ActiviteitI createActiviteit(Context context, MacroI macro) { Activiteit a = new Activiteit(macro); a.saveDBActiviteit(context); return a; } private static class Activiteit implements ActiviteitI { private static int activityCounter = 0; // private Kalender kalender = null; private long startTimeMillis; private long endTimeMillis; private String title; private int id; private String[] description = null; private Activiteit(int id, Kalender kalender, String title, long startTimeMillis, long endTimeMillis) { this.id = id; activityCounter = id + 1; this.kalender = kalender; this.title = title; this.startTimeMillis = startTimeMillis; this.endTimeMillis = endTimeMillis; this.description = null; } private Activiteit(int id, Kalender kalender, String title, long startTimeMillis, long endTimeMillis, String description) { this.id = id; activityCounter = id + 1; this.kalender = kalender; this.title = title; this.startTimeMillis = startTimeMillis; this.endTimeMillis = endTimeMillis; this.description = description.split(SPLITTER); } private Activiteit(Kalender kalender, String title_prefix) { this.startTimeMillis = System.currentTimeMillis(); this.endTimeMillis = -1; this.kalender = kalender; activityCounter++; this.title = "Activiteit" + activityCounter; this.id = activityCounter; this.description = null; } private Activiteit(MacroI macro) { this.startTimeMillis = System.currentTimeMillis(); this.title = macro.getActiviteitTitle(); this.kalender = macro.getKalender(); this.endTimeMillis = -1; activityCounter++; this.id = activityCounter; this.description = null; } @Override public boolean stopRunning() { if (isRunning()) { endTimeMillis = System.currentTimeMillis(); return true; } else { return false; } } @Override public boolean resumeRunning() { if (!isRunning()) { endTimeMillis = -1; return true; } else { return false; } } private String mergeDetails(String splitter) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < description.length; i++) { sb.append(description[i]); if (i < description.length - 1) { sb.append(splitter); } } return sb.toString(); } @Override public Evenement getEvenement() { if (!isRunning() && kalender != null) { Evenement e = new Evenement(kalender.getId(), title, startTimeMillis, endTimeMillis); if (description != null) { e.setDescription(mergeDetails(SPLITTER)); } return e; } else { return null; } } @Override public void setKalender(Kalender kalender) { this.kalender = kalender; } @Override public void setEndTimeMillis(long endTimeMillis) { this.endTimeMillis = endTimeMillis; } public void setStartTimeMillis(long startTimeMillis) { this.startTimeMillis = startTimeMillis; } @Override public void setActiviteitTitle(String title) { this.title = title; } public void setDescription(String[] description) { this.description = description; } @Override public String getDuration() { if (endTimeMillis < 0) { return "running"; } long temp = (endTimeMillis - startTimeMillis) / 1000; int sec = (int) temp % 60; temp /= 60; int min = (int) temp % 60; temp /= 60; int hour = (int) temp % 24; temp /= 24; int day = (int) temp % 7; temp /= 7; int week = (int) temp; String s = "0 s"; if (week > 0) { s = week + " w"; } else if (day > 0) { s = day + " d"; } else if (hour > 0) { s = hour + " h"; } else if (min > 0) { s = min + " m"; } else if (sec > 0) { s = sec + " s"; } return s; } @Override public String getKalenderName() { if (kalender == null) { return null; } return kalender.getName(); } @Override public String getStartTime() { return Time.timeToString(startTimeMillis); } @Override public String getStopTime() { return Time.timeToString(endTimeMillis); } @Override public String getActiviteitTitle() { return title; } @Override public int getActiviteitId() { return id; } @Override public boolean isRunning() { return endTimeMillis < 0; } public String getDescription() { return description != null ? mergeDetails(SPLITTER) : ""; } public String[] getDescriptionEntries() { return description; } public long getBeginMillis() { return startTimeMillis; } public long getEndMillis() { return endTimeMillis; } public void deleteDBActiviteit(Context context) { DatabaseHandler.getInstance(context).deleteActiviteit(this); } private void saveDBActiviteit(Context context) { DatabaseHandler.getInstance(context).addActiviteit(this); } public void updateDBActiviteit(Context context) { DatabaseHandler.getInstance(context).updateActiviteit(this); } } }