text
stringlengths
10
2.72M
/** * Created by nsp on 2015/10/21. */ public class WelcomeBank { public WelcomeBank() { System.out.println("Welcome to ABC Bank"); System.out.println("We are happy to give your money if we can find it"); } }
package lab.tiyo.trigonometry.adapters; import android.app.Activity; import android.content.Context; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.LinearLayout; import android.widget.TextView; import java.util.ArrayList; import lab.tiyo.fraction.models.FractionView; import lab.tiyo.trigonometry.R; import lab.tiyo.trigonometry.helpers.ConstantHelper; import lab.tiyo.trigonometry.models.ItemAnswer; import lab.tiyo.trigonometry.models.ItemDescriptionDialog; /** * Created by root on 01/01/17. */ public class AnswerItemAdapter extends BaseAdapter { private ArrayList<ItemAnswer> listItems = new ArrayList<>(); private Activity activity; private LayoutInflater layoutInflater; public AnswerItemAdapter(Activity activity, ArrayList<ItemAnswer> listItems){ this.activity = activity; this.listItems = listItems; layoutInflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { return listItems.size(); } @Override public Object getItem(int i) { return listItems.get(i); } @Override public long getItemId(int i) { return i; } @Override public View getView(int index, View convertView, ViewGroup viewGroup) { View itemView = convertView; if(itemView == null){ itemView = layoutInflater.inflate(R.layout.item_answer, null); ViewHolder holder = new ViewHolder(); holder.itemNumber = (TextView)itemView.findViewById(R.id.item_number); holder.itemAnswer = (LinearLayout)itemView.findViewById(R.id.item_answer); itemView.setTag(holder); } ViewHolder holder = (ViewHolder)itemView.getTag(); holder.itemNumber.setText((index + 1) + "."); if (listItems.get(index).getLeftOperand().getInputType().equals(ItemDescriptionDialog.INPUT_CONSTANTA)) { TextView leftOperandView = new TextView(activity); leftOperandView.setText(listItems.get(index).getLeftOperand().getTitle()); holder.itemAnswer.addView(leftOperandView); } else { FractionView leftOperandView = new FractionView(activity); leftOperandView.setNumber(listItems.get(index).getLeftOperand().getTNumber()); holder.itemAnswer.addView(leftOperandView); } TextView equalView = new TextView(activity); equalView.setText("="); holder.itemAnswer.addView(equalView); for(ItemDescriptionDialog i : listItems.get(index).getRightOperand()){ if (i.getInputType().equals(ItemDescriptionDialog.INPUT_CONSTANTA)) { TextView rightOperandView = new TextView(activity); rightOperandView.setText(i.getTitle()); holder.itemAnswer.addView(rightOperandView); } else { FractionView rightOperandView = new FractionView(activity); rightOperandView.setNumber(i.getTNumber()); holder.itemAnswer.addView(rightOperandView); } } return itemView; } private static class ViewHolder{ public TextView itemNumber; public LinearLayout itemAnswer; } }
package application; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import javafx.scene.control.ListView; public class collaborateur_principal { ArrayList<Integer> users_select_list_id = new ArrayList<Integer>(); // create principal collaborator method -----------------// void créer_collab_princ(ListView<String> selected_users,int id_pro){ get_selected_users_id(selected_users); for (int i = 0; i < users_select_list_id.size(); i++) { try { jdbc.setConnection(); Statement stm=jdbc.setConnection().createStatement(); Statement stm2=jdbc.setConnection().createStatement(); Statement stm3=jdbc.setConnection().createStatement(); String val="select id from collaborateur_principal where id="+'"'+users_select_list_id.get(i)+'"'; String strcheck="insert into collaborateur_principal (id) values ("+'"'+users_select_list_id.get(i)+'"'+")"; String strcheck2="insert into collab_projet (id_collab_princ,id_projet) values("+'"'+users_select_list_id.get(i)+'"'+","+'"'+id_pro+'"'+")"; ResultSet res = stm.executeQuery(val); while (res.next()==false) { stm2.execute(strcheck); break; } stm3.execute(strcheck2); jdbc.setConnection().close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } //------------ END create principal collaborater method---------------// //------ get selected users id method -------------------------------------// private void get_selected_users_id(ListView<String> selected_users) { for (int i = 0; i <selected_users.getItems().size(); i++) { try { jdbc.setConnection(); Statement stm=jdbc.setConnection().createStatement(); String strcheck="select id from utilisateur where username = "+'"'+selected_users.getItems().get(i)+'"'; ResultSet res = stm.executeQuery(strcheck); while (res.next()) { users_select_list_id.add(res.getInt("id")); } jdbc.setConnection().close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } //--------END get selected users id method--------------// public boolean vérification_collab_princ(String username) { try { jdbc.setConnection(); Statement stm=jdbc.setConnection().createStatement(); String strcheck="select collaborateur_principal.id from collaborateur_principal,utilisateur where collaborateur_principal.id=utilisateur.id and utilisateur.username="+'"'+username+'"'; ResultSet res = stm.executeQuery(strcheck); while (res.next()) { return true; } jdbc.setConnection().close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return false; } //----------------------------------------------------- //delete_collab_prnc------------------------------------- void delete_collab_prnc(String username) { try { jdbc.setConnection(); Statement stm=jdbc.setConnection().createStatement(); String strcheck="delete from collab_projet where id_collab_princ=\r\n" + "(select collaborateur_principal.id from collaborateur_principal,utilisateur \r\n" + "where collaborateur_principal.id=utilisateur.id and utilisateur.username="+'"'+username+'"'+")"; String strcheck2="delete from collaborateur_principal \r\n" + "where id=(select id from utilisateur where username="+'"'+username+'"'+")"; stm.executeUpdate(strcheck); stm.executeUpdate(strcheck2); jdbc.setConnection().close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } void delete_collab_prnc_pr(String nom_projet) { try { jdbc.setConnection(); Statement stm=jdbc.setConnection().createStatement(); String strcheck="delete from collab_projet where id_projet=(select id from projet where nom_projet=+"+'"'+nom_projet+'"'+")"; stm.executeUpdate(strcheck); String strcheck1="delete from collaborateur_principal where id not in(select id_collab_princ from collab_projet)"; stm.executeUpdate(strcheck1); jdbc.setConnection().close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
package ru.job4j.htmlcss; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.HashMap; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletException; import org.apache.logging.log4j.core.config.Configuration; import org.apache.logging.log4j.core.config.ConfigurationSource; import org.apache.logging.log4j.core.config.xml.XmlConfigurationFactory; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.LogManager; /** * Класс Delete реализует функционал удаления пользователя. * * @author Gureyev Ilya (mailto:ill-jah@yandex.ru) * @version 2019-03-18 * @since 2017-11-10 */ public class Delete extends HttpServlet { /** * Кодировка окружения. */ private String enc = "UTF-8"; /** * Карта фильтров. */ private HashMap<String, Filter> filters; /** * Логгер. */ private Logger logger; /** * UserService. */ private UserService us; /** * Инициализатор. * * @throws javax.servlet.ServletException исключение сервлета. */ @Override public void init() throws ServletException { try { // /var/lib/tomcat8/webapps/ch8_html_css-1.0/WEB-INF/classes // \Program FIles\Apache Software Foundation\Tomcat 8.5\webapps\ch8_html_css-1.0\WEB-INF\classes String path = new File(Delete.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getAbsolutePath() + "/"; path = path.replaceFirst("^/(.:/)", "$1"); XmlConfigurationFactory xcf = new XmlConfigurationFactory(); ConfigurationSource source = new ConfigurationSource(new FileInputStream(new File(path + "log4j2.xml"))); Configuration conf = xcf.getConfiguration(new LoggerContext("ch8_html_css_context"), source); LoggerContext ctx = (LoggerContext) LogManager.getContext(true); ctx.stop(); ctx.start(conf); this.logger = LogManager.getLogger("Delete"); this.us = new UserService(); this.filters = new HashMap<>(); this.filters.put("id", new Filter("id", new String[]{"isExists", "isFilled", "isDecimal"})); } catch (Exception ex) { this.logger.error("ERROR", ex); } } /** * Обрабатывает GET-запросы. * http://bot.net:8080/ch8_html_css-1.0/delete/?id=100500 * @param req запрос. * @param resp ответ. * @throws javax.servlet.ServletException исключение сервлета. * @throws java.io.IOException исключение ввода-вывода. */ @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { resp.setContentType("text/html"); resp.setCharacterEncoding(this.enc); req.setAttribute("encoding", this.enc); String id = req.getParameter("id"); Validation va = new Validation(this.logger, this.enc); va.validate("id", id, this.filters.get("id").getFilters()); String message = ""; User user = null; if (va.hasErrors()) { HashMap<String, String> result = va.getResult(); message = String.format("Ошибка при попытке получить пользователя с id: %s<br />Текст ошибки: %s", id, result.get("id")); } else { user = this.us.getUserById(Integer.parseInt(req.getParameter("id"))); if (user == null) { message = String.format("Ошибка при попытке получить пользователя с id: %s<br />Нет такого пользователя.", id); } } req.setAttribute("action", String.format("%s://%s:%s%s%s", req.getScheme(), req.getServerName(), req.getServerPort(), req.getContextPath(), req.getServletPath())); req.setAttribute("refBack", String.format("%s://%s:%s%s/", req.getScheme(), req.getServerName(), req.getServerPort(), req.getContextPath())); req.setAttribute("refLogin", String.format("%s://%s:%s%s/login/", req.getScheme(), req.getServerName(), req.getServerPort(), req.getContextPath())); req.setAttribute("user", user); req.setAttribute("message", message); this.getServletContext().getRequestDispatcher("/WEB-INF/views/deleteGet.jsp").include(req, resp); } catch (Exception ex) { this.logger.error("ERROR", ex); } } /** * Обрабатывает POST-запросы. http://bot.net:8080/ch8_html_css-1.0/delete/ * @param req запрос. * @param resp ответ. * @throws javax.servlet.ServletException исключение сервлета. * @throws java.io.IOException исключение ввода-вывода. */ @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { try { resp.setContentType("text/html"); resp.setCharacterEncoding(this.enc); req.setAttribute("encoding", this.enc); String id = req.getParameter("id"); Validation va = new Validation(this.logger, this.enc); va.validate("id", id, this.filters.get("id").getFilters()); req.setAttribute("refHome", String.format("%s://%s:%s%s/", req.getScheme(), req.getServerName(), req.getServerPort(), req.getContextPath())); String message = String.format("Пользователь id:%s удалён.", id); if (va.hasErrors()) { HashMap<String, String> result = va.getResult(); message = String.format("Ошибка при удалении пользователя id:%s. %s", id, result.get("id")); } else { if (!this.us.deleteUser(Integer.parseInt(id))) { message = String.format("Ошибка при удалении пользователя id:%s.", id); } } req.setAttribute("message", message); this.getServletContext().getRequestDispatcher("/WEB-INF/views/deletePost.jsp").include(req, resp); } catch (Exception ex) { this.logger.error("ERROR", ex); } } }
package com.yxb.contentproviderdemo; import android.content.ContentProvider; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.util.Log; public class MyContentProvider extends ContentProvider { public static final String CONTENT = "content://"; public static final String AUTHORY = "com.yxb.contentproviderdemo.MyContentProvider"; public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd." + AUTHORY; public static final String CONTENT_TYPE_ITEM = "vnd.android.cursor.item/vnd." + AUTHORY; public static final Uri USER_INTO_URI = Uri.parse(CONTENT + AUTHORY + "/" + ContentProviderDemoSQLiteHelper.USER_INFO); static final int USER_INFOS = 1; static final int USER_ITEM = 2; static UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); static { uriMatcher.addURI(AUTHORY,ContentProviderDemoSQLiteHelper.USER_INFO,USER_INFOS); uriMatcher.addURI(AUTHORY,ContentProviderDemoSQLiteHelper.USER_INFO + "/#",USER_ITEM); } private SQLiteDatabase mSQLiteDatabase; public MyContentProvider() { } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { int count = mSQLiteDatabase.delete(ContentProviderDemoSQLiteHelper.USER_INFO,selection,selectionArgs); if(count >= 1){ // 此处向外界通知ContentProvider的数据发生了变化,由于ContentProvider的调用是跟调用者是同一个进程中 // 所以getContext()取得了同一个对象,从而getContentResolver()也是同一个对象 getContext().getContentResolver().notifyChange(USER_INTO_URI,null); } return count; } @Override public String getType(Uri uri) { Log.d(this.getClass().getSimpleName(),uri.toString()); switch (uriMatcher.match(uri)){ case USER_INFOS: return CONTENT_TYPE; //return null; case USER_ITEM: return CONTENT_TYPE_ITEM; //return null; default: throw new UnsupportedOperationException("Not yet implemented"); } // TODO: Implement this to handle requests for the MIME type of the data // at the given URI. } @Override public Uri insert(Uri uri, ContentValues values) { Log.d(this.getClass().getSimpleName(),uri.toString()); long newId = 0; Uri newUri = null; Log.d(this.getClass().getSimpleName(),"match uri is " + uriMatcher.match(uri)); switch (uriMatcher.match(uri)){ case USER_INFOS: newId = mSQLiteDatabase.insert(ContentProviderDemoSQLiteHelper.USER_INFO,null,values); newUri = Uri.parse(CONTENT + AUTHORY + "/" + ContentProviderDemoSQLiteHelper.USER_INFO + "/" + newId); break; default: break; } if(newId > 0){ // 此处向外界通知ContentProvider的数据发生了变化,由于ContentProvider的调用是跟调用者是同一个进程中 // 所以getContext()取得了同一个对象,从而getContentResolver()也是同一个对象 getContext().getContentResolver().notifyChange(newUri,null); return newUri; } // TODO: Implement this to handle requests to insert a new row. throw new UnsupportedOperationException("Not yet implemented"); } @Override public boolean onCreate() { mSQLiteDatabase = new ContentProviderDemoSQLiteHelper(getContext()).getWritableDatabase(); return true; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { Log.d(this.getClass().getSimpleName(),"query match uri is " + uriMatcher.match(uri)); Log.d(getClass().getSimpleName(),uri.toString()); Cursor cursor = null; switch (uriMatcher.match(uri)){ case USER_INFOS: cursor = mSQLiteDatabase.query(ContentProviderDemoSQLiteHelper.USER_INFO,projection,selection, selectionArgs,null,null,sortOrder); break; case USER_ITEM: String id = uri.getPathSegments().get(1); cursor = mSQLiteDatabase.query(ContentProviderDemoSQLiteHelper.USER_INFO,projection,"id = ?", new String[]{id},null,null,sortOrder); break; } return cursor; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { int count = mSQLiteDatabase.update(uri.getPath(),values,selection,selectionArgs); if(count >= 1){ // 此处向外界通知ContentProvider的数据发生了变化,由于ContentProvider的调用是跟调用者是同一个进程中 // 所以getContext()取得了同一个对象,从而getContentResolver()也是同一个对象 getContext().getContentResolver().notifyChange(USER_INTO_URI,null); } return count; } }
package com.alvin.demo.design; import com.alvin.demo.design.store.ICommodity; import com.alvin.demo.design.store.Impl.CardCommodityService; import com.alvin.demo.design.store.Impl.CouponCommodityService; import com.alvin.demo.design.store.Impl.GoodsCommodityService; public class StoreFactory { public ICommodity getCommdityService(Integer commdityType) { if (null == commdityType) { return null; } if (1 == commdityType) { return new CouponCommodityService(); } if (2 == commdityType) { return new GoodsCommodityService(); } if (3 == commdityType) { return new CardCommodityService(); } throw new RuntimeException("不存在的商品的服务类型"); } }
package bn; import bn.distributions.Distribution.SufficientStatistic; /** * Basic Bayesian node interface. Methods held by static and dynamic nodes * @author Nils F. Sandell */ public interface IBayesNode { /** * Get a sufficient statistic object for this node's distribution. * @return A sufficient statistic object, appropriate for this node's distribution type * and matching its expected sufficient statistics. * @throws BNException If error. */ public SufficientStatistic getSufficientStatistic() throws BNException; /** * Optimize this node's distribution according to a sufficient statistic object. * @param stat The sufficient statistic object to optimize based on. * @return The maximum parameter change based on the optimization. * @throws BNException Most likely if the statistic is wrong for this node's distribution * type, else if the statistic is invalid in some way. */ public double optimizeParameters(SufficientStatistic stat) throws BNException; /** * Optimize this node's distribution according to its expected sufficient statistics. * @return The maximum parameter change based on the optimization. * @throws BNException If an error occurs. */ public double optimizeParameters() throws BNException; /** * Get the name of this node. * @return Name in string form. */ String getName(); /** * Get the number of parents this node has. For a dynamic node this is * the number of intra-slice parents for internal reasons. * @return The number of parents. */ int numParents(); /** * Get the number of children this node has. * @return The number of children. */ int numChildren(); /** * Get an iterator over all the children of this node. This is the intra-children * for a dynamic node. * @return */ Iterable<? extends IBayesNode> getChildren(); /** * Get an iterator over all the parents of this node. This is the intra-parents * for a dynamic node. * @return */ Iterable<? extends IBayesNode> getParents(); /** * Get the network this node belongs to. * @return The network. */ IBayesNet<? extends IBayesNode> getNetwork(); /** * Validate the well-formedness of this node. * @throws BNException If the node is not well formed. */ void validate() throws BNException; /** * Lock this node's distribution parameters so that any optimization calls will * be ignored. Useful for when certain node's paramters are "known" and global * optimization calls should be ignored. */ void lockParameters(); /** * Unlocks parameters so optimization calls are heeded. */ void unlockParameters(); /** * Determine whether or not this node's distribution parameters are locked. * @return True of false, as appropriate. */ boolean isLocked(); }
package generator.util.structures; import generator.visitors.AtomicValueType; import java.util.List; public class PythonFunction { private String name; private AtomicValueType returnValue; private List<AtomicValueType> parameters; public PythonFunction(String name, AtomicValueType returnValue, List<AtomicValueType> parameters) { this.name = name; this.returnValue = returnValue; this.parameters = parameters; } public AtomicValueType getReturnValue() { return returnValue; } public String getName() { return name; } public List<AtomicValueType> getParameters() { return parameters; } }
package backend; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.TreeSet; import java.util.HashSet; import java.util.Set; import java.util.TreeMap; import java.util.Vector; import java.util.Collection; import java.sql.ResultSet; import java.sql.SQLException; import util.Utilities; /* * This group class is heavy weight, e.g. loads all the group annotation */ public class Group { public String name;// prefix removed public String fullname; public int idx; public HashSet<AnnotElem> allAnnot; private Map<AnnotAction,AnnotHash> annotByAction; private TreeMap<Integer,Vector<HitBin>> hitBinMap; private Vector<HitBin> hitBins; private int hitBinSize; private int annotBinSize; private int maxWindow; private int topN = 0; //private int topNGene = 0; // mdb removed 12/13/09 private QueryType qType; private int avgGeneLength; // mdb added 7/31/09 #167 private int minGeneLength; // mdb added 7/31/09 #167 private int maxGeneLength; // mdb added 7/31/09 #167 private int maxGap; public static int annotIdx = 0; // unique id for the nongene clusters public boolean mPreClust = false; public Group(SyProps props, String name, String fullname, int idx, QueryType qt) { this.name = name; this.fullname = fullname; this.idx = idx; this.qType = qt; annotByAction = new TreeMap<AnnotAction,AnnotHash>(); annotByAction.put(AnnotAction.Include, new AnnotHash()); annotByAction.put(AnnotAction.Exclude, new AnnotHash()); annotByAction.put(AnnotAction.Mark, new AnnotHash()); hitBins = new Vector<HitBin>(); hitBinMap = new TreeMap<Integer,Vector<HitBin>>(); allAnnot = new HashSet<AnnotElem>(); if (qt != QueryType.Either) { hitBinSize = props.getInt("hit_bin"); annotBinSize = props.getInt("annot_bin"); // mdb added 8/3/09 maxWindow = props.getInt("topn_maxwindow"); // mdb removed 12/13/09 // mTopN = (qt == QueryType.Query ? mProps.getInt("query_topn") : // mProps.getInt("target_topn") ); // mTopNGene = (qt == QueryType.Query ? // mProps.getInt("query_topn_gene") : // mProps.getInt("target_topn_gene") ); // mdb added 12/13/09 topN = props.getInt("topn"); } } // mdb added 8/3/09 public String getName() { return name; } public int getAvgGeneLength() { return avgGeneLength; } public int getMinGeneLength() { return minGeneLength; } public int getMaxGeneLength() { return maxGeneLength; } public int getIdx() { return idx; } // mdb added 7/31/09 #167 public void addAnnotations(AnnotAction action, Vector<AnnotElem> newAnnots) { for (AnnotElem a : newAnnots) { updateAnnotBins(a, action); } } public void updateAnnotBins(AnnotElem a, AnnotAction action) { int bs = a.start/annotBinSize; int be = a.end/annotBinSize; allAnnot.add(a); for (int b = bs; b <= be; b++) { if (!annotByAction.get(action).containsKey(b) ) { annotByAction.get(action).initializeKey(b); } annotByAction.get(action).add(b,a); } } public void removeAnnotation(AnnotElem a, AnnotAction action) { int bs = a.start/annotBinSize; int be = a.end/annotBinSize; allAnnot.remove(a); for (int b = bs; b <= be; b++) { if (annotByAction.get(action).containsKey(b) ) { annotByAction.get(action).get(b).remove(a); } } } // collect, and/or print, the real gene/predicted gene counts public void collectPGInfo(String proj) { int gene = 0; int ng = 0; Vector<String> output = new Vector<String>(); for (AnnotElem a : allAnnot) { if (!a.isGene()) { ng++; } else { gene++; } // if (!a.isGene()) // { // output.add(idStr() + " nongeneclust " + a.start + ":" + a.end); // } // else // { // output.add(idStr() + " geneclust " + a.start + ":" + a.end); // } } // Collections.sort(output); // for (String s : output) // { // System.out.println(s); // } // System.out.println(idStr() + " clusters gene:" + gene + " ng:" + ng); Utils.incStat("AnnotatedGenes_" + proj, gene); Utils.incStat("PredictedGenes_" + proj, ng); mPreClust = true; hitBinsFromAnnotation(); } public void loadAnnotation(UpdatePool pool, TreeMap<String,AnnotAction> annotSpec, TreeMap<String,Integer> annotData, TreeMap<Integer,Integer> annotIdx2GrpIdx, TreeMap<Integer,AnnotElem> annotIdx2Elem //TreeMap<String,Integer> geneName2AnnotIdx // mdb removed 8/12/09 - unused ) throws SQLException { String stmtStr = "SELECT type,start,end,idx " + "FROM pseudo_annot " + "WHERE grp_idx=" + idx + " and type ='gene'"; // we don't use anything else ResultSet rs = pool.executeQuery(stmtStr); // mdb added 7/31/09 #167 avgGeneLength = 0; minGeneLength = Integer.MAX_VALUE; maxGeneLength = 0; int totalGenes = 0; while (rs.next()) { String type = rs.getString("type").intern(); // mdb added "intern" 8/14/09 - reduce memory usage int s = rs.getInt("start"); int e = rs.getInt("end"); int annotIdx = rs.getInt("idx"); AnnotElem ae = new AnnotElem(s,e,(type.equals("gene") ? GeneType.Gene : GeneType.NonGene),annotIdx ); annotIdx2GrpIdx.put(annotIdx,idx); annotIdx2Elem.put(annotIdx,ae); if (type.equals("gene")) { totalGenes++; int length = (e-s+1); avgGeneLength += length; minGeneLength = Math.min(minGeneLength, length); maxGeneLength = Math.max(maxGeneLength, length); } if (annotSpec.containsKey(type)) { incAnnotDataCount(annotData,type); AnnotAction atype = annotSpec.get(type); updateAnnotBins(ae, atype); } // This is set up to mark all hits overlapping any kind of annotation. // However, this is pretty slow. // TODO: revisit what to do about this in 4.0. // For the moment all we use is the gene_olap field anyway. // mdb removed 7/29/09 #167 - now using "annot_mark1/2" in props // if (true) { // for (int b = bs; b <= be; b++) { // if (!mAnnotByType.get(AnnotAction.Mark).containsKey(b) ) // mAnnotByType.get(AnnotAction.Mark).initializeKey(b); // mAnnotByType.get(AnnotAction.Mark).add(b,ae); // } // } } rs.close(); if (totalGenes > 0) avgGeneLength /= totalGenes; if (minGeneLength == Integer.MAX_VALUE) minGeneLength = 0; } private void incAnnotDataCount(TreeMap<String,Integer> AnnotData, String type) { if (!AnnotData.containsKey(type)) AnnotData.put(type, 0); AnnotData.put(type,AnnotData.get(type) + 1); } public boolean checkAnnotHash(AnnotAction aa, int bin) { if (annotByAction.containsKey(aa)) return annotByAction.get(aa).checkBin(bin); return false; } public HashSet<AnnotElem> getBinList(AnnotAction aa, int bin) { return annotByAction.get(aa).getBinList(bin).mList; } public HashMap<AnnotElem,Integer> getAllOverlappingAnnots(int start, int end) { int bs = start/annotBinSize; int be = 1 + end/annotBinSize; HashMap<AnnotElem,Integer> ret = new HashMap<AnnotElem,Integer>(); for (int b = bs; b <= be; b++) { for (AnnotElem ae : getBinList(AnnotAction.Mark,b)) { int overlap = Utils.intervalsOverlap(start,end,ae.start,ae.end); if (overlap >= 0) { if (!ret.containsKey(ae) || overlap > ret.get(ae)) { ret.put(ae, overlap); } } } } return ret; } public String idStr() { return "" + idx + "(" + name + ")"; } public AnnotElem getMostOverlappingAnnot(int start, int end) { HashMap<AnnotElem,Integer> annots = getAllOverlappingAnnots(start, end); AnnotElem ret = null; for (AnnotElem a : annots.keySet()) { // WMN changes to prefer merging with real genes if (ret == null ) { ret = a; } else { if (!a.isGene()) { if (!ret.isGene() ) { if (annots.get(a) > annots.get(ret)) { ret = a; } else if (annots.get(a) == annots.get(ret) ) { if (a.getLength() > ret.getLength()) { ret = a; } else if (a.getLength() == ret.getLength()) { if (a.start < ret.start) { ret = a; } } } } } else // we're looking at a real gene { if (ret.isGene()) { int olapnew = annots.get(a); int olapold = annots.get(ret); if (olapnew > olapold ) { ret = a; } else if (olapnew == olapold ) { if (a.idx < ret.idx) { ret = a; } // if (a.getLength() > ret.getLength()) // { // ret = a; // } // else if (a.getLength() == ret.getLength()) // { // if (a.start < ret.start) // { // ret = a; // } // } } } else { ret = a; } } } } return ret; } public boolean testHitForAnnotOverlap(SubHit sh) { return testHitForAnnotOverlap(sh.start, sh.end); } public boolean testHitForAnnotOverlap(int start, int end) { int bs = start/annotBinSize; int be = 1 + end/annotBinSize; for (int b = bs; b <= be; b++) { for (AnnotElem ae : getBinList(AnnotAction.Mark,b)) { if (Utils.intervalsTouch(start,end,ae.start,ae.end)) return true; } } return false; } // If it hits a gene, skip it. // If hits a non-gene, either grow that annotation or break it up. // Otherwise, make a new annotation. public void testHitForAnnotOverlapAndUpdate(int start, int end, int maxLen, int maxGap) { int newStart = start; int newEnd = end; int bs = Math.max(0,(newStart - maxGap)/annotBinSize); int be = (newEnd + maxGap)/annotBinSize; TreeSet<AnnotElem> ngOlaps = new TreeSet<AnnotElem>(); for (int b = bs; b <= be; b++) { for (AnnotElem ae : getBinList(AnnotAction.Mark,b)) { int olap = Utils.intervalsOverlap(start,end,ae.start,ae.end); if (ae.isGene()) { if (olap > 0) { return; // Hits a gene - no need to inquire further } } else { if (olap > -maxGap) { ngOlaps.add(ae); newStart = Math.min(newStart,ae.start); newEnd = Math.max(newEnd,ae.end); } } } } //System.out.println(idStr() + ":add hit start:" + start + " end:" + end + " ngolaps:" + ngOlaps.size()); // if it already covers the whole hit then do nothing if (ngOlaps.size() == 1 ) { if (ngOlaps.first().start <= start && ngOlaps.first().end >= end) return; } // remove all the affected annots for (AnnotElem ae : ngOlaps) { //System.out.println(idStr() + ":remove annot " + ae.mID + " start:" + ae.start + " end:" + ae.end); removeAnnotation(ae,AnnotAction.Mark); } // add one or more new ones spanning the region for (int s = newStart; s < newEnd; s += maxLen) { int e = Math.min(newEnd, s + maxLen - 1); AnnotElem ae = new AnnotElem(s,e,GeneType.NonGene,0); //System.out.println(idStr() + ":new annot " + ae.mID + " start:" + ae.start + " end:" + ae.end); updateAnnotBins(ae,AnnotAction.Mark); } } // If it hits a gene, skip it. // If hits a non-gene, either grow that annotation or break it up. // Otherwise, make a new annotation. public void testHitForAnnotOverlapAndUpdate2(int start, int end) { int newStart = start; int newEnd = end; int bs = Math.max(0,(newStart - maxGap)/annotBinSize); int be = (newEnd + maxGap)/annotBinSize; TreeSet<AnnotElem> ngOlaps = new TreeSet<AnnotElem>(); for (int b = bs; b <= be; b++) { for (AnnotElem ae : getBinList(AnnotAction.Mark,b)) { int olap = Utils.intervalsOverlap(start,end,ae.start,ae.end); if (ae.isGene()) { if (olap > 0) { return; // Hits a gene - no need to inquire further } } else { if (olap > -maxGap) { ngOlaps.add(ae); newStart = Math.min(newStart,ae.start); newEnd = Math.max(newEnd,ae.end); } } } } //System.out.println(idStr() + ":add hit start:" + start + " end:" + end + " ngolaps:" + ngOlaps.size()); // if it already covers the whole hit then do nothing if (ngOlaps.size() == 1 ) { if (ngOlaps.first().start <= start && ngOlaps.first().end >= end) return; } // remove all the affected annots for (AnnotElem ae : ngOlaps) { //System.out.println(idStr() + ":remove annot " + ae.mID + " start:" + ae.start + " end:" + ae.end); removeAnnotation(ae,AnnotAction.Mark); } // add one or more new ones spanning the region for (int s = newStart; s < newEnd; s += maxGeneLength) { int e = Math.min(newEnd, s + maxGeneLength - 1); AnnotElem ae = new AnnotElem(s,e,GeneType.NonGene,0); //System.out.println(idStr() + ":new annot " + ae.mID + " start:" + ae.start + " end:" + ae.end); updateAnnotBins(ae,AnnotAction.Mark); } } // mdb added 8/3/09 public boolean testHitForAnnotContainment(SubHit sh, int pad) { int bs = sh.start/annotBinSize; int be = sh.end/annotBinSize; for (int b = bs; b <= be; b++) { for (AnnotElem ae : getBinList(AnnotAction.Mark,b)) { if (Utilities.isContained(sh.start,sh.end,ae.start-pad,ae.end+pad)) return true; } } return false; } public void addAnnotHitOverlaps(Hit h, SubHit sh, UpdatePool conn, HashMap<String,Integer> counts) throws SQLException { // Only count one per type so that we get the number of hits hitting // each type, not the total number of annotations which are overlapped. TreeSet<GeneType> usedTypes = new TreeSet<GeneType>(); for (AnnotElem ae : getAllOverlappingAnnots(sh.start, sh.end).keySet()) { if (ae.idx == 0) continue; Vector<String> vals = new Vector<String>(); vals.add(String.valueOf(h.idx)); vals.add(String.valueOf(ae.idx)); vals.add(String.valueOf(Utils.intervalsOverlap(ae.start,ae.end,sh.start,sh.end))); conn.bulkInsertAdd("pseudo_hits_annot", vals); if (!usedTypes.contains(ae.mGT)) { if (counts.containsKey(ae.mGT.toString())) counts.put(ae.mGT.toString(), counts.get(ae.mGT.toString()) + 1); else counts.put(ae.mGT.toString(),1); usedTypes.add(ae.mGT); } } } public void hitBinsFromAnnotation() { for (AnnotElem ae : allAnnot) { HitBin hb = new HitBin(ae, topN, qType); hitBins.add(hb); int bs = ae.start/hitBinSize; int be = ae.end/hitBinSize; for (int b = bs; b <= be; b++) { if (!hitBinMap.containsKey(b)) hitBinMap.put(b, new Vector<HitBin>()); hitBinMap.get(b).add(hb); } } mPreClust = true; } public void checkAddToHitBin(Hit hit, SubHit sh) throws Exception { // Add to existing hit bin, if not already ruled out by TopN; or, start a new bin int bs = sh.start/hitBinSize; int be = sh.end/hitBinSize; HitBin hb = null; int bestOlap = 0; for (int b = bs; b <= be; b++) { if (hitBinMap.containsKey(b)) { for (HitBin hbcheck : hitBinMap.get(b)) { int olap = Utils.intervalsOverlap(hbcheck.start, hbcheck.end, sh.start, sh.end); if (olap <= 0) continue; if (olap > bestOlap) { hb = hbcheck; bestOlap = olap; } else if (olap == bestOlap) { if (hbcheck.start < hb.start) { hb = hbcheck; bestOlap = olap; } else if (hbcheck.start == hb.start) { if (hbcheck.end > hb.end) { hb = hbcheck; bestOlap = olap; } } } } } } if (hb == null) { if (mPreClust) { // If the bins came from annotation, we expect each hit to find at least one throw(new Exception("No bin for hit!")); } } else { hb.checkAddHit(hit, sh); //hb.addHit(hit, sh); return; } if (mPreClust) throw(new Exception("")); hb = new HitBin(hit,sh,topN,qType); hb.mHitsConsidered = 1; hitBins.add(hb); for (int b = bs; b <= be; b++) { if (!hitBinMap.containsKey(b)) hitBinMap.put(b, new Vector<HitBin>()); hitBinMap.get(b).add(hb); } } public void setGeneParams(int maxGapDef, int maxGeneDef) { if (avgGeneLength > 0) maxGap = avgGeneLength; else maxGap = maxGapDef; if (maxGeneLength == 0) maxGeneLength = maxGeneDef; } public void collectBinStats(BinStats bs) { bs.mNBins += hitBins.size(); for (HitBin hb : hitBins) { bs.mTotalSize += Math.abs(hb.end - hb.start); bs.mTotalHits += hb.mHitsConsidered; } } public void filterHits(Set<Hit> hits, boolean keepFamilies) throws Exception { int totalHits = 0; for (HitBin hb : hitBins) { if (hb.mGT != null) { if (qType == QueryType.Query) { Utils.incHist("TopNHist1" + hb.mGT.toString(), hb.mHitsConsidered, hb.mHitsConsidered); Utils.incHist("TopNHistTotal1", hb.mHitsConsidered,hb.mHitsConsidered); } else { Utils.incHist("TopNHist2" + hb.mGT.toString(), hb.mHitsConsidered, hb.mHitsConsidered); Utils.incHist("TopNHistTotal2", hb.mHitsConsidered,hb.mHitsConsidered); } } hb.filterHits(hits, keepFamilies); } } /* * This class stores a map of sequence bins to annotation, enabling * fast lookup of annotations which overlap hits. */ private class AnnotHash { TreeMap<Integer,AnnotList> mAnnotMap; public AnnotHash() { mAnnotMap = new TreeMap<Integer,AnnotList>(); } public boolean containsKey(Integer key) { return mAnnotMap.containsKey(key); } public AnnotList get(Integer key) { return mAnnotMap.get(key); } public void initializeKey(Integer key) { AnnotList l = new AnnotList(); mAnnotMap.put(key,l); } public void add(Integer key, AnnotElem ae) { get(key).add(ae); } public boolean checkBin(Integer b) { return mAnnotMap.containsKey(b); } public AnnotList getBinList(Integer b) { if (mAnnotMap.containsKey(b)) return mAnnotMap.get(b); return new AnnotList(); } public Set<Integer> keySet() { return mAnnotMap.keySet(); } // mdb added 9/3/09 #167 public Collection<AnnotList> values() { return mAnnotMap.values(); } public int size() { return mAnnotMap.size(); } } }
package com.qt.welcome.controller; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.apache.struts2.ServletActionContext; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import com.qt.functionsPage.service.QrInfoService; import com.qt.quartz.service.QuartzJobService; import com.qt.util.AesException; import com.qt.util.WXBizMsgCrypt; import com.qt.util.WriterLog; import com.qt.welcome.service.EventService; import com.qt.welcome.service.impl.EventServiceImpl; @Controller public class ReceiveControler { private WXBizMsgCrypt wxbiz; @Autowired private QuartzJobService quartzJobService; @Autowired private QrInfoService qrInfoService; //签名串 private String signature; //时间戳 private String timestamp; //随机数 private String nonce; //随机字符串(验证微信服务器用) private String echostr; //接收的用户消息 private String receive; //返回值 private String result; private InputStream inStream; public void setWxbiz(WXBizMsgCrypt wxbiz) { this.wxbiz = wxbiz; } public void setSignature(String signature) { this.signature = signature; } public void setTimestamp(String timestamp) { this.timestamp = timestamp; } public void setNonce(String nonce) { this.nonce = nonce; } public void setEchostr(String echostr) { this.echostr = echostr; } public String getResult() { return result; } public InputStream getInStream() { return inStream; } public String receiveMsg(){ //URL:http://qtwxbp.duapp.com/receiveMsg try { wxbiz = new WXBizMsgCrypt("qt001", quartzJobService.selectWxTicket("EncodingAESKey"), quartzJobService.selectWxTicket("appID")); } catch (AesException e) { System.out.println("消息接收初始化失败!"); } if(echostr == null || echostr.equals("")){ StringBuilder sb = new StringBuilder();; try { HttpServletRequest request = ServletActionContext.getRequest(); BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream())); String line = null; while((line = br.readLine())!=null){ sb.append(line); } receive = wxbiz.decryptMsg(signature, timestamp, nonce, sb.toString());//解密,返回用户消息明文 String msg = choiceMsg();//生成自动回复内容 result = wxbiz.encryptMsg(msg, timestamp, nonce);//加密返回结果 } catch (AesException e) { WriterLog.writerLog("解密数据失败! Decrypt the data failed"); try {//尝试不加密 receive = sb.toString(); result = choiceMsg();//生成自动回复内容 } catch (AesException e1) { } } catch (IOException e) { WriterLog.writerLog("数据读取异常! Data read exception"); } }else{ try { result = wxbiz.verifyUrl(signature, timestamp, nonce, echostr); } catch (AesException e) { WriterLog.writerLog("合法性验证失败! Validation failed"); } } try { if(result==null)result=""; //定义返回流(将返回给微信) inStream = new ByteArrayInputStream(result.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return "success"; } //判断用户发送的消息并生成自动回复消息 private String choiceMsg() throws AesException{ String msgType = wxbiz.msgType(receive);//获取消息类型 //初始化向用户发送的信息参数 String msg = ""; if(msgType.equalsIgnoreCase("text")){//用户发送文本消息 //获得用户发送的消息 Object[] encrypt = wxbiz.readXml(receive); //生成回复消息 msg = reMsg(wxbiz,encrypt,""); } else if("event".equalsIgnoreCase(msgType)){//接收事件 EventService event = new EventServiceImpl(); String eventType = event.findEvent(receive); if("subscribe".equalsIgnoreCase(eventType)){//新用户订阅 String[] subInfo = event.subscribeXML(receive); if(subInfo[4]!=null&&!"".equals(subInfo[4])){ subInfo[4] = subInfo[4].replace("qrscene_", ""); msg = reMsg(wxbiz,subInfo,"1"); }else{ msg = reMsg(wxbiz,subInfo,"0"); } } else if("SCAN".equalsIgnoreCase(eventType)){//二维码 String[] subInfo = event.ticketXML(receive); msg = reMsg(wxbiz,subInfo,"1"); } } return msg; } //生成自动回复消息 private String reMsg(WXBizMsgCrypt wxbiz, Object[] encrypt,String option){ if("0".equals(option)){//图文消息参数 return wxbiz.textImageRe(textImageMap(encrypt)); }else if("1".equals(option)){//二维码消息 String sid = encrypt[4].toString().trim(); WriterLog.writerLog(sid); String info = qrInfoService.searchQrInformation(sid); if(info==null)info="内容为空"; return wxbiz.textRe(encrypt[2].toString(), encrypt[1].toString(), timestamp, "text", "二维码内容:"+info); } String userMsg = encrypt[5].toString(); if("1".equals(userMsg)){//用户发送的消息为 1 return wxbiz.textImageRe(textImageMap(encrypt)); // return wxbiz.textRe(encrypt[2].toString(), encrypt[1].toString(), timestamp, "text", "<a href=\"http://qtwxbp.duapp.com/myQt_index/\">oo清汀驿站oo</a>"); }else if("0".equals(userMsg)){ return wxbiz.textRe(encrypt[2].toString(), encrypt[1].toString(), timestamp, "text", menu()); }else if("2".equals(userMsg)){ return wxbiz.textRe(encrypt[2].toString(), encrypt[1].toString(), timestamp, "text", sswd(encrypt)); }else if("3".equals(userMsg)){ return wxbiz.textRe(encrypt[2].toString(), encrypt[1].toString(), timestamp, "text", elsb(encrypt)); } return wxbiz.textRe(encrypt[2].toString(), encrypt[1].toString(), timestamp, "text", "收到您的留言,请允许我在后台默默地看>_<...\r\n回复0可获取菜单\r\n<a href=\"http://qtwxbp.duapp.com/myQt_index/?openId="+encrypt[2].toString()+"\">oo清汀驿站oo</a>"); } //新用户关注自动回复消息内容 private Map<String,String> textImageMap(Object[] encrypt){ Map<String,String> map = new HashMap<String, String>(); map.put("ToUserName",encrypt[2].toString()); map.put("FromUserName",encrypt[1].toString()); map.put("CreateTime",timestamp); map.put("MsgType","news"); map.put("ArticleCount","1"); map.put("Title","清汀驿站"); map.put("Description","一段旋律,一篇文字,共筑心灵的桃花运..."); map.put("PicUrl","http://bcs.duapp.com/qt-resources/firstImage.jpeg"); map.put("Url","http://qtwxbp.duapp.com/myQt_index/?openId="+encrypt[2].toString()); return map; } //获取菜单 private String menu(){ String menu = "回复1.欢迎图文\r\n" + "回复2.谁是卧底\r\n" + "回复3.2048\r\n" + "回复文字向我提建议"; return menu; } //谁是卧底链接 private String sswd(Object[] encrypt){ String sswd = "欢迎进入\r<a href=\"http://qtwxbp.duapp.com/myQt_index/sswd?openId="+encrypt[2].toString()+"\">谁是卧底</a>"; return sswd; } //2048链接 private String elsb(Object[] encrypt){ String sswd = "欢迎进入\r<a href=\"http://qtwxbp.duapp.com/myQt_index/2048Judge?openId="+encrypt[2].toString()+"\">2048</a>"; return sswd; } }
package testo.pl.giphyapitest.connection; /** * Created by Lukasz Marczak on 2015-08-07. */ public class Run { public static GiphyWebService run(String endpoint) { return new retrofit.RestAdapter.Builder().setEndpoint(endpoint) .build().create(GiphyWebService.class); } public static GoogleWebService runGoogle(String endpoint) { return new retrofit.RestAdapter.Builder().setEndpoint(endpoint) .build().create(GoogleWebService.class); } public static PokemonService runPokemon(String endpoint) { return new retrofit.RestAdapter.Builder().setEndpoint(endpoint) .build().create(PokemonService.class); } }
package fr.lteconsulting.pomexplorer.commands; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Created by ebour on 02/11/15. */ @Retention(RetentionPolicy.RUNTIME) public @interface Command { }
package com.swjt.xingzishop.Service; import com.swjt.xingzishop.Bean.XzUser; import com.swjt.xingzishop.Mapper.XzUserMapper; import com.swjt.xingzishop.SpringTest; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import javax.annotation.Resource; import java.util.Date; @FixMethodOrder(MethodSorters.JVM) public class UserServiceTest extends SpringTest { @Resource private XzUserMapper mapper; @Test public void save() { XzUser xzUser = new XzUser(); xzUser.setUserId("qwertyuiopasd"); xzUser.setUserCreatetime(new Date()); xzUser.setUserUpdatetime(new Date()); xzUser.setUserLoginname("123456789"); xzUser.setUserPassword("123456789"); xzUser.setUserName("wpf"); xzUser.setUserIsban(true); mapper.insert(xzUser); } @Test public void findUser() { XzUser xzUser = mapper.selectByPrimaryKey("qwertyuiopasd"); System.out.println(xzUser.toString()); } @Test public void updateUser() { XzUser xzUser = new XzUser(); xzUser.setUserId("qwertyuiopasd"); xzUser.setUserCreatetime(new Date()); xzUser.setUserUpdatetime(new Date()); xzUser.setUserLoginname("123456789"); xzUser.setUserPassword("123456789"); xzUser.setUserName("zhy"); xzUser.setUserIsban(true); int i = mapper.updateByPrimaryKey(xzUser); System.out.println(i); } @Test public void delUser() { mapper.deleteByPrimaryKey("qwertyuiopasd"); } }
// https://www.youtube.com/watch?v=pGVnBT1bI6E class Solution { public int reachNumber(int target) { int sum = 0, k = 0; target = Math.abs(target); while (sum < target || (sum != target && (sum - target) % 2 != 0)) { sum = sum + k; k++; } return k > 0 ? k - 1 : 0; } }
package net.grupocae.cd; public class NumerosRomanos { public static void main(String[] args) { //regresaRomano("MCMLXXIX"); regresaRomano("1979"); } public static void regresaRomano(String numero) { String[] arreglo_miles = { "", "M", "MM", "MMM" }; String[] arreglo_cienes = { "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" }; String[] arreglo_diezes = { "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" }; String[] arreglo_unos = { "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" }; int unos, diezes, cienes, miles, numeroInt; numeroInt = Integer.parseInt(numero); if (!(numeroInt < 3900) || !(numeroInt > 0)) { System.out.println("Los Romanos no contaban mas alla de lo evidente"); } else { unos = numeroInt % 10; diezes = numeroInt % 100 - unos; cienes = numeroInt % 1000 - (diezes + unos); miles = numeroInt - (cienes + diezes + unos); System.out.println(arreglo_miles[miles / 1000] + arreglo_cienes[cienes / 100] + arreglo_diezes[diezes / 10] + arreglo_unos[unos]); } } }
package com.feedback.model; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; @Entity @Table(name="courses") public class Enroll1 { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private int id; @Column(name="roll_no") private String roll_no; @Column(name="enroll1") private String enroll1; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getRoll_no() { return roll_no; } public void setRoll_no(String roll_no) { this.roll_no = roll_no; } public String getEnroll1() { return enroll1; } public void setEnroll1(String enroll1) { this.enroll1 = enroll1; } public Enroll1() { } public Enroll1(String roll_no, String enroll1) { this.roll_no = roll_no; this.enroll1 = enroll1; } }
package com.worldchip.bbp.ect.receiver; import com.worldchip.bbp.ect.service.BootService; import com.worldchip.bbp.ect.util.AlarmUtil; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; public class BootReceiver extends BroadcastReceiver { private static final String TAG = "-----BootReceiver------"; @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) { Log.i(TAG, "start BootReceiver from broadcast receiver"); //Intent startService=new Intent(context, BootService.class); //context.startService(startService); AlarmUtil.initAllAlarmByBootCompleted(); } } }
package basic; //yield()메서드 연습용 예제 public class ThreadTest13 { public static void main(String[] args) { ThreadYield th1 = new ThreadYield("1번 쓰레드"); ThreadYield th2 = new ThreadYield("2번 쓰레드"); th1.start(); th2.start(); try { Thread.sleep(10); } catch (InterruptedException e) { }System.out.println("=========================11111111111111111111111"); th1.work = false; try { Thread.sleep(10); } catch (InterruptedException e) { }System.out.println("=========================22222222222222222222222222"); th1.work = true; try { Thread.sleep(10); } catch (InterruptedException e) { } th1.stop = true; th2.stop = true; } } //yield()메서드 연습용 쓰레드 class ThreadYield extends Thread{ //쉽게 접근을 위해 public으로 함 public boolean stop = false; //쓰레드 전체의 실행 제어용 public boolean work = true; // 쓰레드 작동 중 작업의 실행 여부 제어용 public ThreadYield(String name) { super(name); //쓰레드의 이름 설정(Thread클래스에 name 속성이 있는데 이 속성에는 쓰레드의 이름이 저장된다. } @Override public void run() { while(!stop){ //stop이 true가 되면 반복문 종료 if(work){//true이면 여기가 작동 // getName()메서드 ==> 현재 쓰레드의 name속성값을 반환한다. System.err.println(getName()+"작업중..."); }else{//false이면 여기가 작동 Thread.yield(); // yield()메서드는 Thread의 정적(static) 메서드이다. //Threa.yield 를 넣는 이유 시간을 줄여 효율성을 높이기 위해서 } } System.out.println(getName() +"종료..."); } }
package com.busekylin.gracefulshutdown.web; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class WebController { @GetMapping("/test") public void test(){ try { Thread.sleep(1000 * 60); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("执行完成"); } }
package EntityManagers; import java.util.List; import Entities.Address; import Entities.Customer; public interface AddressManager { // Create public void persistAddress(Address input); // Read public List<Address> getAddressByCustomer(Customer input); // Update public void updateAddressLine1(int id, String input); public void updateAddressLine2(int id, String input); public void updateAddressTown(int id, String input); public void updateAddressPostcode(int id, String input); public void updateAddressCounty(int id, String input); // Delete public void deleteAddress(int id); }
package paket; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Kaynak { private Map<String, String> mapimiz; private List<String> listemiz; private String eposta; public Kaynak() { eposta = "java@yandex.ru"; mapimiz = new HashMap<String, String>(); mapimiz.put("Melih Kale", "melihkale@gmail.com"); mapimiz.put("Hüseyin Can", "hcan@gmail.com"); mapimiz.put("Ozan Aydın", "ozanaydin@gmail.com"); listemiz = new ArrayList<String>(); listemiz.add("Melih Kale"); listemiz.add("Hüseyin Can"); listemiz.add("Ozan Aydın"); } public String getEposta() { return eposta; } public void setEposta(String eposta) { this.eposta = eposta; } public Map<String, String> getMapimiz() { return mapimiz; } public void setMapimiz(Map<String, String> mapimiz) { this.mapimiz = mapimiz; } public List<?> getListemiz() { return listemiz; } public void setListemiz(List<String> listemiz) { this.listemiz = listemiz; } }
package com.richdapice.flowfinder.models; import com.google.auto.value.AutoValue; import com.squareup.moshi.JsonAdapter; import com.squareup.moshi.Moshi; @AutoValue public abstract class SiteCode { public abstract String value(); public abstract String network(); public abstract String agencyCode(); public static JsonAdapter<SiteCode> jsonAdapter(Moshi moshi){ return new AutoValue_SiteCode.MoshiJsonAdapter(moshi); } }
package controller; import model.MultiLayerImageProcessingModel; /** * The current command function object used in the command pattern for the controller. */ public class Current implements ImageProcessingCommands { private final String name; /** * Creates a current function object with the given name. * @param name the name */ public Current(String name) { this.name = name; } @Override public void run(MultiLayerImageProcessingModel m) { if (m == null) { throw new IllegalArgumentException("The model given was null."); } m.setCurrentLayer(name); } }
import java.awt.Graphics; import java.awt.Image; import java.awt.Rectangle; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.imageio.ImageIO; /** * TargetPlane class represents targets in enemy plane form that can shoot */ public class TargetPlane extends Target{ public static final int TARGETPLANE_SIZE = 200; private List<Shoot> shoots; //list of shoots of target plane //Constructor of target plane public TargetPlane(Image image, int health, int locationX, int locationY, int appearTime, ShootEnum shootEnum){ super(image, locationX, locationY, health, appearTime); setImage( image); shoots = new ArrayList<Shoot>(5); for( int i = 0; i < 5; i++ ){ Shoot shoot = new Shoot(shootEnum.damage(), locationX, locationY + 100, shootEnum.image()); shoots.add(shoot); } setScaledImage(TARGETPLANE_SIZE); } //Returns list of shoots public List<Shoot> getShoots() { return shoots; } //Updates the specified shoot from the list of shoots public void setShoot(int i, int locationX){ shoots.get(i).setPositionX(locationX); } //Removes a shoot form list of shoots public void removeShoot(int i) { shoots.remove(i); } }
package fm.jiecao.jcvideoplayer_lib; import android.app.Activity; import android.content.Context; import android.graphics.drawable.ColorDrawable; import android.media.AudioManager; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.Gravity; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.PopupWindow; import android.widget.ProgressBar; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import java.util.Map; import java.util.Timer; import java.util.TimerTask; public class PandaVedioPlayer extends JCVideoPlayer { public ImageView ivBack;//返回按钮 public TextView tvTitle;//顶部标题 public ImageView ivThumb;//全屏背景 public ProgressBar pbLoading;//加载视频进度条 public ImageButton btn_collect;//收藏按钮 public ImageButton btn_share;//分享按钮 public Button btn_clarity;//清晰度按钮 public ImageButton btn_volume;//清晰度按钮 public SeekBar seekbar_volume;//音量进度 public static final String TAG = "PandaVedioPlayer"; protected static Timer mDismissControlViewTimer;// 1.5秒的消失计时器 protected static JCBuriedPointStandard jc_BuriedPointStandard;//节操隐藏标准 private AudioManager systemService; private int currentVolume; private int maxVolume; private int lastVolume; private boolean isCollect = false; private static int currentPosition; public PandaVedioPlayer(Context context) { super(context); } public PandaVedioPlayer(Context context, AttributeSet attrs) { super(context, attrs); } @Override public int getLayoutId() { return R.layout.pandatv_pullscreen; } @Override protected void init(Context context) { super.init(context); systemService = ((AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE)); maxVolume = systemService.getStreamMaxVolume(AudioManager.STREAM_MUSIC); currentVolume = systemService.getStreamVolume(AudioManager.STREAM_MUSIC); ivBack = (ImageView) findViewById(R.id.back); tvTitle = (TextView) findViewById(R.id.title); ivThumb = (ImageView) findViewById(R.id.thumb); pbLoading = (ProgressBar) findViewById(R.id.loading); btn_collect = (ImageButton) findViewById(R.id.btn_collect); btn_share = (ImageButton) findViewById(R.id.btn_share); btn_clarity = (Button) findViewById(R.id.btn_clarity); btn_volume = (ImageButton) findViewById(R.id.btn_volume); seekbar_volume = (SeekBar) findViewById(R.id.seekbar_volume); ivBack.setOnClickListener(this); ivThumb.setOnClickListener(this); btn_collect.setOnClickListener(this); btn_share.setOnClickListener(this); btn_clarity.setOnClickListener(this); btn_volume.setOnClickListener(this); seekbar_volume.setMax(maxVolume);//设置拖动条最大值 seekbar_volume.setProgress(currentVolume);//设置现在的值 setVolumeImage(currentVolume);//设置现在的声音图标 lastVolume = currentVolume; //拖动条的监听 seekbar_volume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { currentVolume = progress; Log.d(TAG, "currentVolume:" + currentVolume); if (progress==0) { btn_volume.setBackgroundResource(R.drawable.volume_no); systemService.setStreamVolume(AudioManager.STREAM_MUSIC,progress,AudioManager.FLAG_PLAY_SOUND); }else { btn_volume.setBackgroundResource(R.drawable.volume_continue); systemService.setStreamVolume(AudioManager.STREAM_MUSIC,progress,AudioManager.FLAG_PLAY_SOUND); } } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { } }); } /** * 设置声音图片 * * @param currentVolume */ public void setVolumeImage(int currentVolume) { if (currentVolume == 0) { btn_volume.setBackgroundResource(R.drawable.volume_no); } else { btn_volume.setBackgroundResource(R.drawable.volume_continue); } } private Object object ; //开始准备 @Override public void setUrlAndObject(String url, Map<String, String> mapHeadData, Object... objects) { if (objects.length == 0) return; this.object = objects; //这里调用了父类的setUrlAndObject方法 super.setUrlAndObject(url, mapHeadData, objects); //设置标题 tvTitle.setText(objects[0].toString()); } @Override public void setStateAndUi(int state) { super.setStateAndUi(state); switch (CURRENT_STATE) { case CURRENT_STATE_NORMAL: //在正常状态时 changeUiToNormal(); startTimer(10000); break; case CURRENT_STATE_PREPAREING: //在准备状态时 changeUiToShowUiPrepareing(); break; case CURRENT_STATE_PLAYING: //在播放状态时 changeUiToShowUiPlaying(); startTimer(6000); break; case CURRENT_STATE_PAUSE: //在暂停状态时 changeUiToShowUiPause(); break; case CURRENT_STATE_ERROR: //在异常状态时 changeUiToError(); break; } } @Override public void onClick(View v) { super.onClick(v); int i = v.getId(); if (i == R.id.start) { if (TextUtils.isEmpty(url)) { Toast.makeText(getContext(), "No url", Toast.LENGTH_SHORT).show(); return; } if (CURRENT_STATE == CURRENT_STATE_NORMAL) { if (jc_BuriedPointStandard != null) { jc_BuriedPointStandard.onClickStartThumb(url, objects); } prepareVideo();//准备播放视频 startTimer(6000); } }else if (i == R.id.surface_container) { //当播放状态时可以点击最外层布局 startTimer(6000); }else if (i == R.id.thumb) { //当准备状态时只能点击背景 if (CURRENT_STATE == CURRENT_STATE_PREPAREING) { if (llBottomContainer.getVisibility() == View.VISIBLE) { llTopContainer.setVisibility(View.INVISIBLE); llBottomContainer.setVisibility(View.INVISIBLE); }else{ llTopContainer.setVisibility(View.VISIBLE); llBottomContainer.setVisibility(View.VISIBLE); startTimer(5000); } } } else if (i == R.id.back) { //返回按钮 backFullscreen(); } else if (i == R.id.btn_collect) { if (isCollect) { //已收藏,取消收藏 showToast("已取消收藏"); isCollect = false; btn_collect.setBackgroundResource(R.drawable.collect_no); //dosomething to not collect }else{ //未收藏,点击收藏 showToast("已添加,请到[我的收藏]中查看"); isCollect = true; btn_collect.setBackgroundResource(R.drawable.collect_yes); //dosomething to collect } } else if (i == R.id.btn_share) { //分享 Toast.makeText(getContext(), "点击了分享", Toast.LENGTH_SHORT).show(); } else if (i == R.id.btn_clarity) { CheckClarity(); } else if (i == R.id.btn_volume) { if (currentVolume == 0) { //如果是静音 btn_volume.setBackgroundResource(R.drawable.volume_continue); if (lastVolume ==0) { //代表第一次进入就是静音 seekbar_volume.setProgress(maxVolume); systemService.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolume, AudioManager.FLAG_PLAY_SOUND); }else { seekbar_volume.setProgress(lastVolume); systemService.setStreamVolume(AudioManager.STREAM_MUSIC, lastVolume, AudioManager.FLAG_PLAY_SOUND); } } else { //如果不是静音 lastVolume = currentVolume;//保存音量状态 btn_volume.setBackgroundResource(R.drawable.volume_no); systemService.setStreamVolume(AudioManager.STREAM_MUSIC, 0, AudioManager.FLAG_PLAY_SOUND); seekbar_volume.setProgress(0); } } } private void showToast(String text) { Toast toast = Toast.makeText(getContext(), "恭喜您收藏成功啦", Toast.LENGTH_SHORT); toast.setGravity(Gravity.CENTER, 0, 0); View inflate = View.inflate(getContext(), R.layout.item_toast, null); ((TextView) inflate.findViewById(R.id.tv_toast)).setText(text); toast.setView(inflate); toast.show(); } @Override public boolean onTouch(View v, MotionEvent event) { int id = v.getId(); if (id == R.id.surface_container) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: cancelTimer(); break; case MotionEvent.ACTION_UP: startTimer(6000); if (!changePosition && !changeVolume) { showAndHideUI(); } break; } } else if (id == R.id.progress) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: cancelTimer(); break; case MotionEvent.ACTION_UP: startTimer(6000); break; } } return super.onTouch(v, event); } private void showAndHideUI() { if (llBottomContainer.getVisibility() == View.VISIBLE) { changeUiToClear(); } else { changeUiToShowUiPlaying(); } } private void changeUiToNormal() { Log.d(TAG, "正常状态正常状态正常状态正常状态正常状态正常状态正常状态正常状态正常状态"); llTopContainer.setVisibility(View.VISIBLE);//顶部布局 llBottomContainer.setVisibility(View.VISIBLE);//底部布局 ivStart.setVisibility(View.VISIBLE);//播放按钮 pbLoading.setVisibility(View.INVISIBLE);//加载条 ivThumb.setVisibility(View.VISIBLE);//背景图 updateIvStartState(); } private void changeUiToShowUiPrepareing() { Log.d(TAG, "准备状态准备状态准备状态准备状态准备状态准备状态准备状态准备状态准备状态"); llTopContainer.setVisibility(View.VISIBLE); llBottomContainer.setVisibility(View.VISIBLE); ivStart.setVisibility(View.VISIBLE); pbLoading.setVisibility(View.VISIBLE); ivThumb.setVisibility(View.VISIBLE); } private void changeUiToShowUiPlaying() { Log.d(TAG, "播放状态播放状态播放状态播放状态播放状态播放状态播放状态播放状态播放状态"); llTopContainer.setVisibility(View.VISIBLE); llBottomContainer.setVisibility(View.VISIBLE); ivStart.setVisibility(View.VISIBLE); pbLoading.setVisibility(View.INVISIBLE); ivThumb.setVisibility(View.INVISIBLE); updateIvStartState(); } private void changeUiToShowUiPause() { Log.d(TAG, "暂停状态暂停状态暂停状态暂停状态暂停状态暂停状态暂停状态暂停状态暂停状态"); llTopContainer.setVisibility(View.VISIBLE); llBottomContainer.setVisibility(View.VISIBLE); ivStart.setVisibility(View.VISIBLE); pbLoading.setVisibility(View.INVISIBLE); ivThumb.setVisibility(View.INVISIBLE); updateIvStartState(); } private void changeUiToClear() { Log.d(TAG, "清理ui清理ui清理ui清理ui清理ui清理ui清理ui清理ui清理ui清理ui清理ui"); llTopContainer.setVisibility(View.INVISIBLE); llBottomContainer.setVisibility(View.INVISIBLE); ivStart.setVisibility(View.VISIBLE); pbLoading.setVisibility(View.INVISIBLE ); ivThumb.setVisibility(View.INVISIBLE); } private void changeUiToError() { Log.d(TAG, "异常状态异常状态异常状态异常状态异常状态异常状态异常状态异常状态异常状态"); llTopContainer.setVisibility(View.INVISIBLE); llBottomContainer.setVisibility(View.INVISIBLE); ivStart.setVisibility(View.INVISIBLE); pbLoading.setVisibility(View.INVISIBLE); ivThumb.setVisibility(View.INVISIBLE); updateIvStartState(); } //更新开始播放的按钮 private void updateIvStartState() { Log.d(TAG, "开始更新播放按钮状态updateIvStartState"); if (CURRENT_STATE == CURRENT_STATE_PLAYING) { ivStart.setBackgroundResource(R.drawable.pla_pause); } else if (CURRENT_STATE == CURRENT_STATE_ERROR) { ivStart.setBackgroundResource(R.drawable.pla_error); } else { ivStart.setBackgroundResource(R.drawable.pla_continue); } AudioManager systemService = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE); int streamVolume = systemService.getStreamVolume(AudioManager.STREAM_MUSIC); Log.d(TAG, "streamVolume:" + streamVolume); if (streamVolume == 0) { btn_volume.setBackgroundResource(R.drawable.volume_no); } else { btn_volume.setBackgroundResource(R.drawable.volume_continue); } } private void startTimer(int time) { cancelTimer(); mDismissControlViewTimer = new Timer(); mDismissControlViewTimer.schedule(new TimerTask() { @Override public void run() { if (getContext() != null && getContext() instanceof Activity) { ((Activity) getContext()).runOnUiThread(new Runnable() { @Override public void run() { if (CURRENT_STATE != CURRENT_STATE_NORMAL && CURRENT_STATE != CURRENT_STATE_ERROR) { //当前状态不在正常并且不在异常状态时 llBottomContainer.setVisibility(View.INVISIBLE); llTopContainer.setVisibility(View.INVISIBLE); } } }); } } }, time); } private void cancelTimer() { Log.d(TAG, "计时器结束"); if (mDismissControlViewTimer != null) { mDismissControlViewTimer.cancel(); mDismissControlViewTimer = null; } } public static void setJcBuriedPointStandard(JCBuriedPointStandard jcBuriedPointStandard) { jc_BuriedPointStandard = jcBuriedPointStandard; JCVideoPlayer.setJcBuriedPoint(jcBuriedPointStandard); } @Override public void onCompletion() { super.onCompletion(); cancelTimer(); } private TextView liuchang,gaoqing,biaoqing; private View liuchangLine; private static final byte QING_XI_JISHU = 1; private static final byte QING_XI_GAOQING = 2; private byte currentQingXiDu = QING_XI_GAOQING; private PopupWindow mPopupQingXiWindow; private void CheckClarity() { View view = View.inflate(getContext(), R.layout.popwindow_qingxidu, null); liuchang = (TextView) view .findViewById(R.id.app_video_qingxidu_liuchang); gaoqing = (TextView) view .findViewById(R.id.app_video_qingxidu_gaoqing); view.findViewById(R.id.app_video_qingxidu_gaoqing_underline) .setVisibility(View.GONE); if (currentQingXiDu == QING_XI_JISHU) { liuchang.setBackgroundColor(getResources() .getColor(R.color.media_qingxidu)); } else if (currentQingXiDu == QING_XI_GAOQING) { gaoqing.setBackgroundColor(getResources() .getColor(R.color.media_qingxidu)); } liuchang.setOnClickListener(popWindowListener); gaoqing.setOnClickListener(popWindowListener); int vieheight = findViewById(R.id.btn_clarity).getMeasuredHeight(); int vieWidth = findViewById(R.id.btn_clarity).getMeasuredWidth(); Log.d(TAG, "高为" + vieheight + "宽为" + vieWidth); mPopupQingXiWindow = new PopupWindow(view, vieWidth + vieWidth * 2 / 8, ViewGroup.LayoutParams.WRAP_CONTENT, true); mPopupQingXiWindow.setOutsideTouchable(true); mPopupQingXiWindow.setBackgroundDrawable(new ColorDrawable(0)); mPopupQingXiWindow.showAsDropDown( btn_clarity, 0 - vieWidth * 1 / 8, (int) (0 - vieheight * 2.5)); } public void setQHListener(QHlistener qhListener){ this.qHlistener = qhListener; } interface QHlistener{ void OnQH(); } private QHlistener qHlistener ; OnClickListener popWindowListener = new OnClickListener() { @Override public void onClick(View v) { if (v.getId() == R.id.app_video_qingxidu_liuchang) { //如果是流畅,也就是极速 if (currentQingXiDu == QING_XI_JISHU) { Log.d(TAG, "点击了流畅"); mPopupQingXiWindow.dismiss(); return; } //首先取消popwindow currentQingXiDu = QING_XI_JISHU; Toast.makeText(getContext(), "您已切换至流畅播放", Toast.LENGTH_SHORT).show(); liuchang.setBackgroundColor(getResources() .getColor(R.color.media_qingxidu)); gaoqing.setBackgroundColor(getResources().getColor(R.color.transparent_half_up)); btn_clarity.setText("流畅"); mPopupQingXiWindow.dismiss(); //切换线路 ChangeVideo(); }else if(v.getId() == R.id.app_video_qingxidu_gaoqing) { if (currentQingXiDu == QING_XI_GAOQING) { Log.d(TAG, "点击了高清"); mPopupQingXiWindow.dismiss(); return; } //首先取消popwindow currentQingXiDu = QING_XI_GAOQING; Toast.makeText(getContext(), "您已切换至高清播放", Toast.LENGTH_SHORT).show(); gaoqing.setBackgroundColor(getResources() .getColor(R.color.media_qingxidu)); liuchang.setBackgroundColor(getResources().getColor(R.color.transparent_half_up)); btn_clarity.setText("高清"); mPopupQingXiWindow.dismiss(); //切换线路 } } }; private void ChangeVideo() { currentPosition = JCMediaManager.mediaPlayer.getCurrentPosition(); JCVideoPlayer.releaseAllVideos(); qHlistener.OnQH(); } private String newurl = "http://2449.vod.myqcloud.com/2449_bfbbfa3cea8f11e5aac3db03cda99974.f20.mp4"; }
package de.tetet.fof7.denorm; import java.util.function.Consumer; import java.util.function.Predicate; import com.mongodb.BasicDBObject; import com.mongodb.BulkWriteOperation; import com.mongodb.DB; import com.mongodb.DBCursor; import com.mongodb.DBObject; import de.tetet.fof7.config.Config; import de.tetet.fof7.config.ConfigFactory; import de.tetet.mongodb.MongoDBConn; public class Combiner { private final String yearField = "sbYear"; private String base; private String result; private DB db; /** * Default constructor */ public Combiner() { initdb(); } private void initdb() { Config cfg = ConfigFactory.getConfig(); db = new MongoDBConn().connect(cfg.getDbname()); } /** * @param base * @return the object */ public Combiner base(String base) { this.base = base; return this; } /** * @param result * @return the object */ public Combiner result(String result) { this.result = result; return this; } /** * */ public void combine() { Predicate<String> isSeasons = new Predicate<String>() { @Override public boolean test(String t) { return t.startsWith(base); } }; Consumer<String> combine = new Consumer<String>() { @Override public void accept(String t) { combine(t); } }; // db.getCollection(result).drop(); db.getCollectionNames().stream().filter(isSeasons).forEach(combine); } /** * @param collection is stored in result */ private void combine(String collection) { String year = getYear(collection); DBObject update = new BasicDBObject("$set", new BasicDBObject(yearField, year)); DBObject query = new BasicDBObject(); db.getCollection(collection).update(query, update, false, true); BulkWriteOperation builder = db.getCollection(result).initializeUnorderedBulkOperation(); DBCursor cursor = db.getCollection(collection).find(); while (cursor.hasNext()) { DBObject o = cursor.next(); builder.insert(o); } builder.execute(); db.getCollection(collection).drop(); } /** * @param collection * @return the year for the collection */ private String getYear(String collection) { return collection.replace(base, ""); } }
package com.design.pattern.singleton; /** * @Author: 98050 * @Time: 2019-01-09 23:04 * @Feature: 静态内部类实现 */ public class Singleton5 { private Singleton5(){ System.out.println("运行"); } private static class Singleton5Holder{ private static final Singleton5 uniqueInstance = new Singleton5(); } public static Singleton5 getUniqueInstance() { return Singleton5Holder.uniqueInstance; } }
package com.getkhaki.api.bff.persistence.models.views; import com.getkhaki.api.bff.web.models.PersonDto; import org.hibernate.annotations.Type; import javax.persistence.Column; import javax.persistence.Lob; import java.time.Instant; import java.util.List; public interface CalendarEventsWithAttendeesView { byte[] getId(); String getGoogleCalendarId(); String getSummary(); Instant getCreated(); Instant getStart(); Instant getEnd(); String getOrganizerEmail(); String getOrganizerFirstName(); String getOrganizerLastName(); Integer getNumberInternalAttendees(); Integer getNumberTotalAttendees(); Integer getTotalSeconds(); }
package Dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; /** * 用于数据库备份与恢复的Dao * @author computer * */ public class SecureDao { private final static String dbUrl = "jdbc:sqlserver://localhost:1433;DatabaseName=master"; //使用master数据库进行备份与恢复 private final static String dbUserName = "sa"; private final static String dbPassword = "123456"; private final static String jdbcDriver = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; //类加载时自动执行static静态代码块 static{ try { Class.forName(jdbcDriver); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public static Connection getConnection() throws SQLException { return DriverManager.getConnection(dbUrl,dbUserName,dbPassword); } public static void close(Connection conn) { if (conn!=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } //备份 public void backup(){ Connection conn = null; try { conn = getConnection(); String sql = "backup database db_costume to disk='C:\\EclipseWorkSpace\\CostumeManageSystem\\save\\db_costume.bak' with init"; PreparedStatement ps = conn.prepareStatement(sql); ps.execute(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { close(conn); } } public void restore(){ Connection conn = null; try { conn = getConnection(); String sql = "restore database db_costume from disk='C:\\EclipseWorkSpace\\CostumeManageSystem\\save\\db_costume.bak' with replace"; PreparedStatement ps = conn.prepareStatement(sql); ps.execute(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { close(conn); } } }
/* * 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 servlet.register; import java.io.IOException; 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 static common.Config.*; import common.ResouceDynamicMapping; import data.dao.UserDao; import java.sql.SQLException; import java.util.HashMap; import java.util.logging.Level; import java.util.logging.Logger; import javax.servlet.ServletContext; import servlet.common.sessionmodel.UserSessionModel; /** * * @author dangminhtien */ public class ConfirmVerifyCodeServlet extends HttpServlet { protected void processRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String errorMessage = null; ServletContext context = req.getServletContext(); ResouceDynamicMapping resourceMapping = (ResouceDynamicMapping) context.getAttribute(ResouceDynamicMapping.KEY); String url = resourceMapping.getDefaultUrl(); HashMap<String, String> roadMap = resourceMapping.getRoadMap(); try { HttpSession session = req.getSession(); UserSessionModel user = (UserSessionModel) session.getAttribute(UserSessionModel.SESSION_KEY); String code = (String) session.getAttribute("VERIFIEDMAILCODE"); String txtInputCode = req.getParameter("txtInputCode"); // Nếu như mà code bằng null có nghĩa là sự cố gì đã xảy ra rồi => trở về mh chính if (code != null) { // nếu như code không null mà không khớp thì cho nhập lại if (txtInputCode == null || !txtInputCode.equals(code)) { errorMessage = "Verified code is incorrect"; url = roadMap.get(VERIFY_EMAIL_PAGE); } else { UserDao dao = new UserDao(); dao.updateMailVerifiedState(user.getEmail(), true); url = resourceMapping.getDefaultUrl(); // nếu code trùng khớp => login (có nghĩa là trở về dispatchercontroller nó sẽ tự đăng nhập } } } catch (ClassNotFoundException ex) { log("ConfirmVerifyCodeServlet error due to: " + ex.getMessage()); } catch (SQLException ex) { log("ConfirmVerifyCodeServlet error due to: " + ex.getMessage()); } finally { if (errorMessage != null) { req.setAttribute("UERROR", errorMessage); req.getRequestDispatcher(url).forward(req, resp); } else { resp.sendRedirect(url); } } } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Handles the HTTP <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
package it.bibliotecaweb.servlet.libro; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import it.bibliotecaweb.model.Autore; import it.bibliotecaweb.model.Libro; import it.bibliotecaweb.service.MyServiceFactory; /** * Servlet implementation class ExecuteUpdateLibroServlet */ @WebServlet("/ExecuteUpdateLibroServlet") public class ExecuteUpdateLibroServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public ExecuteUpdateLibroServlet() { 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 { String id = request.getParameter("id"); String titolo = request.getParameter("titolo"); String genere = request.getParameter("genere"); String trama = request.getParameter("trama"); String idAutore = request.getParameter("autore"); if(id != null && !id.equals("") && titolo != null && !titolo.equals("") && genere != null && !genere.equals("") && trama != null && !trama.equals("") && idAutore != null && !idAutore.equals("")) { try { Autore autore = MyServiceFactory.getAutoreServiceInstance().findById(Integer.parseInt(idAutore)); Libro libro = MyServiceFactory.getLibroServiceInstance().findById(Integer.parseInt(id)); libro.setTitolo(titolo); libro.setGenere(genere); libro.setTrama(trama); libro.setAutore(autore); for (Libro l : MyServiceFactory.getLibroServiceInstance().list()) { if(l.equals(libro)) { request.setAttribute("errore", "Attenzione, nessuna modifica effettuata!"); request.setAttribute("idParametro", id); request.getRequestDispatcher("PrepareUpdateLibroServlet").forward(request, response); return; } } MyServiceFactory.getLibroServiceInstance().update(libro); request.setAttribute("effettuato", "Operazione effettuata con successo!"); request.getRequestDispatcher("ListaLibriServlet").forward(request, response); } catch (Exception e) { e.printStackTrace(); } }else { request.setAttribute("errore", "Attenzione, inserire tutti i campi!"); request.setAttribute("idParametro", id); request.getRequestDispatcher("PrepareUpdateLibroServlet").forward(request, response); } } }
import org.hibernate.Criteria; import org.hibernate.PropertyAccessException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.Metadata; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; /** Подключите в вашем проекте Hibernate и напишите код, выводящий информацию о каком-нибудь курсе. **/ public class Main { public static void main(String[] args) { String url = "jdbc:mysql://localhost:3306/skillbox"; String user = "root"; String password = "testtest"; int count = 0; try { Connection connection = DriverManager.getConnection(url, user, password); Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery("select * from courses"); while (resultSet.next()) { count = resultSet.getInt("id"); } resultSet.close(); statement.close(); connection.close(); } catch (Exception ex) { ex.printStackTrace(); } StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build(); Metadata metadata = new MetadataSources(registry).getMetadataBuilder().build(); SessionFactory sessionFactory = metadata.getSessionFactoryBuilder().build(); Session session = sessionFactory.openSession(); for (int i = 1; i <= count; i++ ) { int courseId = i; Course course = session.get(Course.class, courseId); int teacherId = course.getId(); Teacher teacher = session.get(Teacher.class, teacherId); System.out.println(courseId + ". " + course.getName() + " - " + teacher.getName()); } // Criteria criteria = session.createCriteria(Course.class); // List<Course> courses = criteria.list(); // courses.forEach(System.out::println); // // Criteria criteria1 = session.createCriteria(Teacher.class); // List<Teacher> teachers = criteria1.list(); // teachers.forEach(System.out::println); sessionFactory.close(); } }
package com.iesvirgendelcarmen.POO.ejercicios; /** * Managed class for right triangle * @author beni * @version 1.0 */ public class Triangle { private double side1; private double side2; /** * Contructor * @param side1 first cateto * @param side2 second cateto */ public Triangle(double side1, double side2) { this.side1 = side1; this.side2 = side2; } /** * * @return hypotenuse value of figth triangle, type double */ public double getHypotenuse() { return Math.pow(side1, 2) + Math.pow(side2, 2); } /** * * @return area value of figth triangle, type double */ public double getArea() { return side1 * side2 / 2.0; } /** * * @return perimeter value of figth triangle, type double */ public double getPerimeter() { return side1 + side2 + getHypotenuse(); } @Override public String toString() { return "Triangle [side1=" + side1 + ", side2=" + side2 + ", Hypotenuse=" + (Math.round(getHypotenuse()*100) / 100) + "]"; } }
package gov.nih.mipav.view; import gov.nih.mipav.model.provenance.ProvenanceRecorder; import gov.nih.mipav.model.scripting.*; import gov.nih.mipav.model.scripting.actions.*; import gov.nih.mipav.model.structures.*; import java.awt.*; import java.awt.event.*; import java.io.*; import java.util.*; import javax.swing.*; import javax.swing.border.*; import javax.swing.event.*; /** * Contains a seperatly running thread which checks the list of registered images. The list is updated at a rate which * is user-specified. The frame will allow the user to adjust how frequently the list will be updated. For efficiency, * no updating will occur if the frame has been minimized. * * <p>The registered images frame provides direct user access to the function Runtime.getRuntime.gc() via a "Garbage * Collector" button.</p> * * <p>There are a number of possible supported uses. There is an unimplemented button to remove un-framed images from * the ViewUserInterface image hashtable and there is a button to bring framed-images to the front.</p> * * <p>This class has a number of inside classes:</p> * * <ul> * <li>ImageRegistryMonitor (a type of Thread) to update the list of images registered with the ViewUserInterface</li> * <li>MouseClickAdapter (a type of MouseAdapter) to attempt to bring the selected image's frame to the front</li> * <li>ImageCellRenderer (a type of JLabel) to present both the image-name and a helpful icon depicting whether or not * the associated image is in a frame or not</li> * </ul> * * @version 15 April 2002 * @author Lynne M. Pusanik * @author Matthew J. McAuliffe, Ph.D. * @author David A. Parsons */ public class ViewJFrameRegisteredImages extends JFrame implements ActionListener, ListSelectionListener, ChangeListener { //~ Static fields/initializers ------------------------------------------------------------------------------------- /** Use serialVersionUID for interoperability. */ private static final long serialVersionUID = -4417297294466318211L; //~ Instance fields ------------------------------------------------------------------------------------------------ /** Buttons for dealing with image deletions */ private JButton callImageDeleteButton, callImageDeleteAllButton; /** Button for dealing with garbage collection */ private JButton callGCButton; /** Button for bringing frame to front */ private JButton callFrameToFrontButton; /** Buttons for dealing with frame deletion. */ private JButton callFrameDeleteButton, callFrameDeleteAllButton; /** The list of images and frames */ private JList imageList; /** Button for pausing updating of currently registered images */ private JButton pauseButton; /** Whether currently registered images list is updating */ private boolean paused = false; // don't update list when true /** The rate at which to update imageList */ private JTextField sampleRate; // user control over update period /** The scroll pane containing the image list */ private JScrollPane scrollPane; /** thread to watch image registry. */ private ImageRegistryMonitor surf; /** The current user interface */ private ViewUserInterface UI; //~ Constructors --------------------------------------------------------------------------------------------------- /** * Constructor. */ public ViewJFrameRegisteredImages() { super(); UI = ViewUserInterface.getReference(); setTitle("Image Registry Monitor"); try { setIconImage(MipavUtil.getIconImage(Preferences.getIconName())); } catch (FileNotFoundException error) { Preferences.debug("Exception ocurred while getting <" + error.getMessage() + ">. Check that this file is available.\n"); System.err.println("Exception ocurred while getting <" + error.getMessage() + ">. Check that this file is available.\n"); } this.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent we) { surf.stop(); dispose(); } public void windowIconified(WindowEvent we) { paused = false; pauseButton.doClick(); } public void windowDeiconified(WindowEvent we) { paused = true; pauseButton.doClick(); } }); this.getContentPane().setLayout(new BorderLayout()); TitledBorder border; JPanel userPanel = new JPanel(new BorderLayout()); // panel is titled & etched JPanel setupPanel = new JPanel(new BorderLayout()); border = new TitledBorder("Sampling"); border.setTitleColor(Color.black); border.setTitleFont(MipavUtil.font12B); border.setBorder(new EtchedBorder()); setupPanel.setBorder(border); pauseButton = new JButton("Pause"); pauseButton.setFont(MipavUtil.font12B); pauseButton.addActionListener(this); setupPanel.add(pauseButton, BorderLayout.NORTH); JPanel samplePanel = new JPanel(); JLabel labelSampleRate = new JLabel("Update Rate"); // add name for user input labelSampleRate.setFont(MipavUtil.font12); labelSampleRate.setForeground(Color.black); samplePanel.add(labelSampleRate); samplePanel.add(Box.createHorizontalStrut(10)); // add spacing sampleRate = new JTextField("5000"); // add user input field makeNumericsOnly(sampleRate); sampleRate.setColumns(5); sampleRate.setHorizontalAlignment(JTextField.RIGHT); sampleRate.addActionListener(this); samplePanel.add(sampleRate); JLabel ms = new JLabel("ms"); // add sample rate unit ms.setFont(MipavUtil.font12); ms.setForeground(Color.black); samplePanel.add(ms); setupPanel.add(samplePanel, BorderLayout.SOUTH); userPanel.add(setupPanel, BorderLayout.NORTH); // get the current registered images @SuppressWarnings("unchecked") Vector<?> names = new Vector(); // put the list together imageList = new JList(names); imageList.setToolTipText("Double-click to bring framed-images to front"); imageList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); imageList.addListSelectionListener(this); imageList.addMouseListener(new MouseClickAdapter()); imageList.setCellRenderer(new ImageCellRenderer()); JPanel pan = new JPanel(new GridLayout(1, 1)); border = new TitledBorder("Currently Registered Images"); border.setTitleColor(Color.black); border.setTitleFont(MipavUtil.font12B); border.setBorder(new EtchedBorder()); pan.setBorder(border); scrollPane = new JScrollPane(imageList); pan.add(scrollPane); userPanel.add(pan, BorderLayout.CENTER); this.getContentPane().add(userPanel, BorderLayout.CENTER); // The constructor below will work if the Delete button is added...: // JPanel buttonPan = new JPanel(new GridLayout(3,1)); // ...other wise, use the following constructor: JPanel buttonPan = buildButtonPanel(); this.getContentPane().add(buttonPan, BorderLayout.SOUTH); surf = new ImageRegistryMonitor(); surf.addImageRegistryChangeListener(this); sampleRate.addFocusListener(surf); // start the registry checker surf.start(); setVisible(true); setSize(330, 380); validate(); } private JPanel buildButtonPanel() { JPanel buttonPanel = new JPanel(new GridBagLayout()); GridLayout frameLayout = new GridLayout(3, 1); JPanel framePanel = new JPanel(frameLayout); framePanel.setBorder(MipavUtil.buildTitledBorder("Framed Image Actions")); frameLayout.setVgap(14); //make buttons for frame panel callFrameDeleteButton = new JButton("Delete Frame"); callFrameDeleteButton.setToolTipText("Delete the selected frame"); callFrameDeleteButton.setFont(MipavUtil.font12B); callFrameDeleteButton.addActionListener(this); callFrameDeleteAllButton = new JButton("Delete All Frames"); callFrameDeleteAllButton.setToolTipText("Delete all listed frames"); callFrameDeleteAllButton.setFont(MipavUtil.font12B); callFrameDeleteAllButton.addActionListener(this); callFrameToFrontButton = new JButton("Bring Frame to Front"); callFrameToFrontButton.setToolTipText("Brings the selected frame to the front"); callFrameToFrontButton.setFont(MipavUtil.font12B); callFrameToFrontButton.addActionListener(this); framePanel.add(callFrameDeleteButton); framePanel.add(callFrameDeleteAllButton); framePanel.add(callFrameToFrontButton); GridBagConstraints gbc = new GridBagConstraints(); gbc.gridx = 0; gbc.gridy = 0; gbc.gridheight = 2; gbc.fill = GridBagConstraints.VERTICAL; buttonPanel.add(framePanel, gbc); JPanel imagePanel = new JPanel(new BorderLayout()); imagePanel.setBorder(MipavUtil.buildTitledBorder("Image Actions")); // make buttons for image panel callImageDeleteButton = new JButton("Delete Image"); callImageDeleteButton.setToolTipText("Delete the selected image not in a frame"); callImageDeleteButton.setFont(MipavUtil.font12B); callImageDeleteButton.addActionListener(this); callImageDeleteAllButton = new JButton("Delete All Images"); callImageDeleteAllButton.setToolTipText("Delete all images that are not in frames"); callImageDeleteAllButton.setFont(MipavUtil.font12B); callImageDeleteAllButton.addActionListener(this); imagePanel.add(callImageDeleteButton, BorderLayout.NORTH); imagePanel.add(callImageDeleteAllButton, BorderLayout.CENTER); gbc.gridx = 1; gbc.gridy = 0; gbc.gridheight = 1; buttonPanel.add(imagePanel, gbc); JPanel memoryPanel = new JPanel(new GridBagLayout()); memoryPanel.setBorder(MipavUtil.buildTitledBorder("Memory Actions")); GridBagConstraints gbcInner = new GridBagConstraints(); //make buttons for memory panel callGCButton = new JButton("Free memory"); callGCButton.setFont(MipavUtil.font12B); callGCButton.addActionListener(this); gbcInner.gridx = 0; gbcInner.gridy = 0; gbcInner.weightx = 1; gbcInner.fill = GridBagConstraints.HORIZONTAL; memoryPanel.add(callGCButton, gbcInner); gbc.gridx = 1; gbc.gridy = 1; gbc.fill = GridBagConstraints.HORIZONTAL; buttonPanel.add(memoryPanel, gbc); return buttonPanel; } //~ Methods -------------------------------------------------------------------------------------------------------- // ************************************************************************ // **************************** Action Events ***************************** // ************************************************************************ /** * Calls various methods based on the user's actions. * * @param event event that triggered function */ public void actionPerformed(ActionEvent event) { Object source = event.getSource(); if (source.equals(pauseButton)) { if (paused) { // if already paused.... change the sample rate, and unpause surf.start(); paused = false; pauseButton.setText("Pause"); } else { // not paused? stop checking the memory, doing updates and tell user surf.stop(); paused = true; pauseButton.setText("Resume"); } } else if (source.equals(callGCButton)) { // call the garbage collector Runtime.getRuntime().gc(); Runtime.getRuntime().runFinalization(); if (paused) { surf.stop(); // should update the display & memory values } ScriptRecorder.getReference().addLine(new ActionCollectGarbage()); ProvenanceRecorder.getReference().addLine(new ActionCollectGarbage()); } else if (source.equals(callImageDeleteButton)) { // selectedName = get selected item from the list String selectedName = (String) imageList.getSelectedValue(); deleteItem(selectedName, false); } else if(source.equals(callFrameDeleteButton)) { // selectedName = get selected item from the list String selectedName = (String) imageList.getSelectedValue(); deleteItem(selectedName, true); } else if(source.equals(callImageDeleteAllButton) || source.equals(callFrameDeleteAllButton)) { boolean doFrames = source.equals(callFrameDeleteAllButton); ListModel imageModel = imageList.getModel(); for(int i=0; i<imageModel.getSize(); i++) { String name = (String)imageModel.getElementAt(i); deleteItem(name, doFrames); } } else if (source.equals(callFrameToFrontButton)) { // bring image to front String selectedName = (String) imageList.getSelectedValue(); if (selectedName == null) { return; } try { imageToFront(selectedName); } catch (NullPointerException npe) { MipavUtil.displayError("There is no associated image-frame!\n" + "Can't bring " + selectedName + " to front"); Preferences.debug("Image " + selectedName + " was not associated " + "with an image frame. Either the image is " + "still in use, or it was not deleted in " + "error.\n"); // log. } catch (IllegalArgumentException iae) { Preferences.debug("Illegal Argument Exception in " + "ViewJFrameRegisteredImages when clicking on ToFront. " + "Somehow the Image list sent an incorrect name to " + "the image image hashtable. \n", 2); System.out.println("Bad argument."); } } } /** * Deletes the item specified by name. If false, only the model image is deleted * @param name the object to delete * @param deleteFrame whether the frame should be deleted along with the image */ private void deleteItem(String name, boolean deleteFrame) { // System.out.println("selected name = " + selectedName); if (name == null) { return; // log nothing. } try { ModelImage image = UI.getRegisteredImageByName(name); ViewJFrameImage frame = UI.getFrameContainingImage(image); // An image that has a frame is only deleted when deleteFrame == true if (image != null && ((deleteFrame && frame != null) || (!deleteFrame && frame == null))) { image.disposeLocal(); if(deleteFrame && frame != null) { frame.close(); } } Runtime.getRuntime().gc(); Runtime.getRuntime().runFinalization(); } catch (IllegalArgumentException iae) { // MipavUtil.displayError("There was a problem with the " + // "supplied name.\n" ); Preferences.debug("Illegal Argument Exception in " + "ViewJFrameRegisteredImages when clicking on Delete. " + "Somehow the Image list sent an incorrect name to " + "the image image hashtable. \n" + iae.getMessage() + "\n", 1); // System.out.println("Bad argument."); } } /** * Shows the frame with the memory. * * @param flag DOCUMENT ME! */ public synchronized void setVisible(boolean flag) { setLocation(50, 50); super.setVisible(flag); } // ************************************************************************ // **************************** Change Events ***************************** // ************************************************************************ /** * Calls various methods based on the changes in the memory panel. * * @param event event that triggered function */ public void stateChanged(ChangeEvent event) { Object source = event.getSource(); ImageRegistryMonitor mon = (ImageRegistryMonitor) source; // update the list in the window Vector<String> names = mon.getRegisteredNames(); int selected = -1; if(imageList.getModel().getSize() > 0) { selected = imageList.getSelectedIndex(); if(selected != -1) { Object selectedObj = imageList.getSelectedValue(); if(selectedObj != null) { selected = names.indexOf(selectedObj); } } } imageList.setListData(names); if(selected != -1) { imageList.setSelectedIndex(selected); } repaint(); } // *********************************************************************** // *********************** ListSelectionEvents**************************** // *********************************************************************** /** * Whenever the list changes, the valueChanged is called. * * <p>calls <code>callToFrontbutton#doClick()</code> when the list has been double-clicked, to bring the selected * image (and associated frame) to the front.</p> * * @param event DOCUMENT ME! */ public void valueChanged(ListSelectionEvent event) { // if (event.getValueIsAdjusting()) { System.out.println("...is adjusting...."); return; } // JList list = (JList)event.getSource(); System.out.println("value changed."); if // (list.isSelectionEmpty()) { return; } String selectedName = (String) // list.getSelectedValue(); imageToFront(selectedName); System.out.println("ValueChanged"); } /** * Takes a txt field, and forces the textfield to accept numbers, backspace and delete-key entries. * * <p>also tells the pauseButton to click.</p> * * @param txt DOCUMENT ME! */ protected void makeNumericsOnly(JTextField txt) { txt.addKeyListener(new KeyAdapter() { // make the field public void keyTyped(KeyEvent evt) { // not accept letters // JTextField t = (JTextField) evt.getComponent(); char ch = evt.getKeyChar(); if (((ch < '0') || (ch > '9')) && ((ch != KeyEvent.VK_DELETE) && (ch != KeyEvent.VK_BACK_SPACE))) { // if is the case that ch is outside the bounds of a number // AND it is the case that ch is neither a BS or a DE, then // key is not a digit or a deletion char evt.consume(); } else { paused = false; pauseButton.doClick(); } } }); } /** * Using the supplied name as the image name, this method finds the frame associated with the image and brings it to * the front. Does nothing when selectedName is <CODE>null</CODE>. * * @param selectedName DOCUMENT ME! * * @throws NullPointerException when the <CODE>selectedName</CODE> is in the image list, but not associated * with any frame. * @throws IllegalArgumentException if the <CODE>selectedName</CODE> cannot be found in the image list */ private void imageToFront(String selectedName) throws NullPointerException, IllegalArgumentException { if (imageList.isSelectionEmpty()) { return; // no selected name. fail quietly. } try { UI.getFrameContainingImage(UI.getRegisteredImageByName(selectedName)).toFront(); } catch (IllegalArgumentException iae) { // MipavUtil.displayError("There was a problem with the supplied name.\n" ); Preferences.debug("Illegal Argument Exception in " + "ViewJFrameRegisteredImages.imageToFront() " + "Somehow the Image list sent an incorrect name to " + "the image image hashtable. " + "\n", 1); System.out.println("Bad argument."); } } //~ Inner Classes -------------------------------------------------------------------------------------------------- /** * Identifies components that can be used as "rubber stamps" to paint the cells in a JList. * * <p>Images which are shown to have an associated frame (only Image A) will show the "frame.gif" icon. All others * will show the "rect.gif" icon.</p> * * @see ViewUserInterface#getFrameContainingImage() */ // if this class becomes public and is no longer "inner", // then there will need to be more arguments in the constructor... private class ImageCellRenderer extends JLabel implements ListCellRenderer { /** Use serialVersionUID for interoperability. */ private static final long serialVersionUID = -5908802887298772112L; /** DOCUMENT ME! */ private ImageIcon floating = MipavUtil.getIcon("rect.gif"); /** DOCUMENT ME! */ private ImageIcon frame = MipavUtil.getIcon("frame.gif"); /** * Identifies components that can be used as "rubber stamps" to paint the cells in a JList. Preset the label to * "opaque" true. */ // if this class becomes public and is no longer "inner", // then there will need to be more arguments in the constructor... public ImageCellRenderer() { setOpaque(true); } /** * Return a component that has been configured to display the specified value. That component's <code> * paint</code> method is then called to "render" the cell. If it is necessary to compute the dimensions of a * list because the list cells do not have a fixed size, this method is called to generate a component on which * <code>getPreferredSize</code> can be invoked. * * <p>Images which are shown to have an associated frame (only Image A) will show the "frame.gif" icon. All * others will show the "rect.gif" icon.</p> * * @param list The JList we're painting. * @param value The value returned by list.getModel().getElementAt(index). * @param index The cells index. * @param isSelected True if the specified cell was selected. * @param cellHasFocus True if the specified cell has the focus. * * @return A component whose paint() method will render the specified value. * * @see ViewUserInterface#getFrameContainingImage() * @see JList * @see ListSelectionModel * @see ListModel */ public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { String name = value.toString(); setText(name); ModelImage img = null; try { img = UI.getRegisteredImageByName(name); } catch (IllegalArgumentException iae) { Preferences.debug("Requested an image from registry monitor that is not registered: " + name); return this; } // if there is no associated frame with the name, use the "floating" // icon, else, we'll show it as having a "Frame" icon. // note: IMAGE B is not found to have an associated frame! if (UI.getFrameContainingImage(img) == null) { setIcon(floating); } else { setIcon(frame); } // choose coloration if (isSelected) { setBackground(list.getSelectionBackground()); setForeground(list.getSelectionForeground()); } else { setBackground(list.getBackground()); setForeground(list.getForeground()); } setEnabled(list.isEnabled()); setFont(list.getFont()); setOpaque(true); return this; } } // end ImageCellRenderer /** * As an extension of MouseAdapter, this class merely responds on clicked list events. In particular, the * double-clicked item is brought to the front if the image is associated with an image frame. * * @see ViewJFrameRegisteredImages#bringToFront(String) */ private class MouseClickAdapter extends MouseAdapter { /** * Responds only on double-clicked events from the JList. The double-clicked list item brings to the front the * frame of the associated image. * * <p>Ignores ClassCastExceptions, and will present to the user the error messages if there are * NullPointerExceptions.</p> * * @see ViewJFrameRegisteredImages#bringToFront(String) */ public void mouseClicked(MouseEvent event) { if (event.getClickCount() == 2) { String selectedName = "''"; try { JList list = (JList) event.getSource(); if (list.isSelectionEmpty()) { return; } selectedName = (String) list.getSelectedValue(); imageToFront(selectedName); } catch (ClassCastException cce) { Preferences.debug("ViewJFrameRegisteredImages." + "MouseClickAdapter tried to handle " + "something that wasn't a " + "javax.swing.JList.\n", 4); } catch (NullPointerException npe) { MipavUtil.displayError("There is no associated " + "image-frame!\n" + "Can't bring " + selectedName + " to front"); Preferences.debug("Image " + selectedName + " was not " + "associated with an image frame. " + "Either the image is still in use, " + "or it was not deleted in " + "error.\n"); // log. } catch (IllegalArgumentException iae) { Preferences.debug("Illegal Argument Exception in " + "ViewJFrameRegisteredImages when clicking on " + "ToFront. Somehow the Image list sent " + "an incorrect name to the image image hashtable." + "\n", 2); } } } } // end class MouseClickAdapter } // end class ViewJFrameRegisteredImages
/* * 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 agh.musicapplication.mappdao.interfaces; import agh.musicapplication.mappdao.Crudable; import agh.musicapplication.mappmodel.MPermission; import agh.musicapplication.mappmodel.MReview; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; /** * * @author ag */ @Repository @Transactional public interface MPermissionRepositoryInterface extends Crudable<MPermission>{ public MPermission findPermissionByName(String name); }
package org.exoplatform.management.ecmadmin.operations.queries; import java.util.Set; import org.exoplatform.services.cms.queries.QueryService; import org.gatein.management.api.exceptions.OperationException; import org.gatein.management.api.operation.OperationContext; import org.gatein.management.api.operation.OperationHandler; import org.gatein.management.api.operation.ResultHandler; import org.gatein.management.api.operation.model.ReadResourceModel; /** * @author <a href="mailto:thomas.delhomenie@exoplatform.com">Thomas * Delhoménie</a> * @version $Revision$ */ public class QueriesReadResource implements OperationHandler { @Override public void execute(OperationContext operationContext, ResultHandler resultHandler) throws OperationException { QueryService queryService = operationContext.getRuntimeContext().getRuntimeComponent(QueryService.class); Set<String> allConfiguredQueries = queryService.getAllConfiguredQueries(); resultHandler.completed(new ReadResourceModel("Available queries.", allConfiguredQueries)); } }
package net.baade; import java.math.BigDecimal; public class Cliente { private String Nomecliente; /*int clienteID; public int getClienteID() { return clienteID; //} //public void setClienteID(int clienteID) { this.clienteID = clienteID; //} */ public String getNomecliente() { return Nomecliente; } public void setNomecliente(String nomecliente) { Nomecliente = nomecliente; } public BigDecimal getAnimais() { // TODO Auto-generated method stub return null; } }
package com.aidigame.hisun.imengstar.http.json; import com.aidigame.hisun.imengstar.http.json.LoginJson.Data; /** * {"state":0, * "errorCode":0, * "errorMessage":"", * "version":"1.0", * "confVersion":"1.0", * "data":{"isSuccess":true}, * "currentTime":1401949319 * } * @author admin * */ public class RegisterJson { public int state; public int errorCode; public String errorMessage; public String version; public String confVersion; public long currentTime; public Data data; public static class Data{ public boolean isSuccess; } }
package com.bcq.oklib; import com.bcq.oklib.net.domain.DefauParser; import com.bcq.oklib.net.Processor; import com.bcq.oklib.net.Parser; import java.io.File; public class OKHelper { private static Parser parser; private static Processor processor; private static String ROOT_NAME = Constant.ROOT_NAME; public static void setBasePath(String rootName) { ROOT_NAME = rootName; } public static String getBasePath(){ return Constant.ROOT + ROOT_NAME + File.separator; } /** * 设置默认Json解析器 * @param defaultParser */ public static void setDefaultParser(Parser defaultParser) { OKHelper.parser = defaultParser; } public static Parser getParser() { if (null == parser) {//使用默认解析器 parser = new DefauParser(); } return parser; } /** * 设置错误处理器 * @param processor */ public static void setProcessor(Processor processor) { OKHelper.processor = processor; } public static Processor getProcessor() { return processor; } }
//designpatterns.command.SystemExitClass.java package designpatterns.command; public class SystemExitClass { public void exit() { System.out.println("Í˳öϵͳ£¡"); } }
package com.zxt.framework.dictionary.action; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONArray; import net.sf.json.JSONObject; import org.apache.struts2.ServletActionContext; import com.zxt.compplatform.formengine.entity.view.TreeData; import com.zxt.compplatform.formengine.util.TreeUtil; import com.zxt.framework.common.util.RandomGUID; import com.zxt.framework.dictionary.entity.DataDictionary; import com.zxt.framework.dictionary.entity.DictionaryGroup; import com.zxt.framework.dictionary.service.IDataDictionaryService; public class DictionaryGroupAction { private IDataDictionaryService dataDictionaryService; private DictionaryGroup dictionaryGroup; /** * 列表入口 * @return */ public String toList(){ return "list"; } /** * 列表 * GUOWEIXIN 和下方方法list功能一样。只不过此处返回Tree */ public String listTree(){ HttpServletResponse res = ServletActionContext.getResponse(); HttpServletRequest req = ServletActionContext.getRequest(); int page = 1; if(req.getParameter("page") != null && !req.getParameter("page").equals("")){ page = Integer.parseInt(req.getParameter("page")); } int rows = 0; if(req.getParameter("rows") != null && !req.getParameter("rows").equals("")){ rows = Integer.parseInt(req.getParameter("rows")); } int totalRows = dataDictionaryService.findDictGroupTotalRows(); List dictionaryGroupList = dataDictionaryService.findAllDictGroupByPage(page,20); //加上树 List<TreeData> listTree=new ArrayList<TreeData>(); TreeData treeRoot=new TreeData(); treeRoot.setId("1"); treeRoot.setText("字典分组/查看所有"); listTree.add(treeRoot); for (int i = 0; i < dictionaryGroupList.size(); i++) { TreeData treeData = new TreeData(); DictionaryGroup dictionaryGroup=(DictionaryGroup)dictionaryGroupList.get(i); try{ treeData.setId(dictionaryGroup.getId()); treeData.setText(dictionaryGroup.getName()); treeData.setParentID("1"); //treeData.setFlag(dictionaryGroup.getId()); //此处用于存入其ID listTree.add(treeData); }catch(Exception e){ e.printStackTrace(); } } List list = new ArrayList(); list = TreeUtil.treeAlgorithmForTreeData(listTree, "1"); JSONArray jsonarray = JSONArray.fromObject(list); try { String jsonStr=jsonarray.toString(); res.getWriter().write(jsonarray.toString()); } catch (IOException e) { e.printStackTrace(); } return null; } /** * 列表 * @return */ public String list(){ HttpServletResponse res = ServletActionContext.getResponse(); HttpServletRequest req = ServletActionContext.getRequest(); int page = 1; if(req.getParameter("page") != null && !req.getParameter("page").equals("")){ page = Integer.parseInt(req.getParameter("page")); } int rows = 0; if(req.getParameter("rows") != null && !req.getParameter("rows").equals("")){ rows = Integer.parseInt(req.getParameter("rows")); } int totalRows = dataDictionaryService.findDictGroupTotalRows(); List dictionaryGroupList = dataDictionaryService.findAllDictGroupByPage(page,rows); Map map = new HashMap(); if(dictionaryGroupList != null){ map.put("rows", dictionaryGroupList); map.put("total", new Integer(totalRows)); } String dataJson = JSONObject.fromObject(map).toString(); try { res.getWriter().write(dataJson); } catch (IOException e) { e.printStackTrace(); } return null; } /** * 跳转添加页面 * @return */ public String toAdd(){ return "toadd"; } /** * 添加 * @return */ public String add(){ HttpServletResponse res = ServletActionContext.getResponse(); if(dictionaryGroup.getId() == null || dictionaryGroup.getId().equals("")){ dictionaryGroup.setId(RandomGUID.geneGuid()); } try { if(dataDictionaryService.findDictGroupById(dictionaryGroup.getId()) != null){ res.getWriter().write("exist"); } else if(dataDictionaryService.findGroupByName(dictionaryGroup.getName())!=null){ res.getWriter().write("groupExist"); } else{ dataDictionaryService.insertDictGroup(dictionaryGroup); res.getWriter().write("success"); } } catch (IOException e) { e.printStackTrace(); } return null; } /** * 跳转修改页面 * @return */ public String toUpdate(){ HttpServletRequest req = ServletActionContext.getRequest(); String dictionaryGroupId = req.getParameter("dictionaryGroupId"); if(dictionaryGroupId!= null && !dictionaryGroupId.equals("")){ dictionaryGroup = dataDictionaryService.findDictGroupById(dictionaryGroupId); } return "toupdate"; } /** * 修改 * @return */ public String update(){ HttpServletResponse res = ServletActionContext.getResponse(); try { String groupId = dictionaryGroup.getId(); String groupName = dictionaryGroup.getName(); boolean flag = dataDictionaryService.isDicGroupExistUpdate(groupId, groupName); if(flag){ res.getWriter().write("failure"); } else{ dataDictionaryService.updateDictGroup(dictionaryGroup); res.getWriter().write("success"); } } catch (IOException e) { e.printStackTrace(); } return null; } /** * 删除 * @return */ public String delete(){ HttpServletRequest req = ServletActionContext.getRequest(); HttpServletResponse res = ServletActionContext.getResponse(); String dictionarygGroupId = req.getParameter("dictionaryGroupId"); String dictionaryGroupIds = req.getParameter("dictionaryGroupIds"); try { /** * 数据对象分组ID */ if(dictionarygGroupId!= null && !dictionarygGroupId.equals("")){ List dictionaryList = dataDictionaryService.findByDictGroupId(dictionarygGroupId); if(dictionaryList != null && dictionaryList.size()>0){ res.getWriter().write("error"); }else{ dataDictionaryService.deleteDictGroupById(dictionarygGroupId); res.getWriter().write("success"); } } /** * 数据对象分组id */ if(dictionaryGroupIds!= null && !dictionaryGroupIds.equals("")){ List dictionaryList = dataDictionaryService.findAllByGroupIds(dictionaryGroupIds); if(dictionaryList != null && dictionaryList.size()>0){ res.getWriter().write("error"); }else{ dataDictionaryService.deleteAllDictGroup(dataDictionaryService.findAllDictGroupByIds(dictionaryGroupIds)); res.getWriter().write("success"); } } } catch (IOException e) { e.printStackTrace(); } return null; } /** * 获取全部数据对象分组 * @return */ public String getAllItem(){ HttpServletResponse res = ServletActionContext.getResponse(); try{ /** * 数据对象分组 */ List list = dataDictionaryService.findAllDictGroup(); DictionaryGroup dictionaryGroup = new DictionaryGroup(); dictionaryGroup.setId("-1"); dictionaryGroup.setName("请选择"); dictionaryGroup.setSortNo(new Integer(-1)); list.add(0,dictionaryGroup); /** * 设置数据对象根节点 */ String dataJson = JSONArray.fromObject(list).toString(); res.getWriter().write(dataJson); } catch (IOException e) { e.printStackTrace(); }catch(Exception ex){ ex.printStackTrace(); } return null; } public String nameExist() { HttpServletRequest req = ServletActionContext.getRequest(); HttpServletResponse resp = ServletActionContext.getResponse(); resp.setContentType("text/plain;charset=UTF-8 "); String name = req.getParameter("name"); DictionaryGroup dataObjGroup = dataDictionaryService.findGroupByName(name); try { if (dataObjGroup != null) { resp.getWriter().write("exist"); } else { resp.getWriter().write("unexist"); } } catch (IOException e) { e.printStackTrace(); } return null; } public void setDataDictionaryService( IDataDictionaryService dataDictionaryService) { this.dataDictionaryService = dataDictionaryService; } public DictionaryGroup getDictionaryGroup() { return dictionaryGroup; } public void setDictionaryGroup(DictionaryGroup dictionaryGroup) { this.dictionaryGroup = dictionaryGroup; } }
package com.robin.springbootlearn; import org.springframework.boot.Banner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.EnableAspectJAutoProxy; @SpringBootApplication // 表明是 spring boot 应用 @EnableAspectJAutoProxy(proxyTargetClass = true) @ComponentScan(basePackages = {"com.robin"}) public class Application { public static void main(String[] args) { // SpringApplication.run(Application.class, args); // 关闭热部署;或在 .yml 文件中配置 spring.devtools.restart.enabled: false // System.setProperty("spring.devtools.restart.enabled","false"); SpringApplication app = new SpringApplication(Application.class); // 关闭 banner;或在 .yml 文件中配置 spring.main.banner-mode = off app.setBannerMode(Banner.Mode.OFF); app.run(args); } }
package com.xin.bob.fibonacci; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.xin.bob.fibonacci.utils.Fibonacci; /** * 传统的ndk-build命令 编译出so文件 然后再Java代码中引入编译出的so文件 * jni 文件夹中放置C的源码 Android.mk 和 Application.mk 使用ndk-build编译成so文件后调用 * Android模式下 需要右键link一下Android.mk的文件路径 这样Android就可以正确识别native的方法了 不会报红了 * 但是cmake方式没有使用ndk-build命令编译so包的过程 直接运行 直接打包进apk 直接就可以运行了 * <p> * 调用ndk-build命令 需要再jni目录的上一级目录打开cmd窗口 执行ndk-build 生成so包 * 生成出两个文件夹 libs和obj 将libs名称改为jniLibs即可 然后就在JAVA代码中引用库就可以了 */ public class MainActivity extends AppCompatActivity { static { System.loadLibrary("calculator"); } private static final int param = 99999999; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); TextView tv = (TextView) findViewById(R.id.sample_text); TextView tv2 = (TextView) findViewById(R.id.sample_text2); // Clang calculate long start = System.currentTimeMillis(); int result = calculate(param); long usedTime = System.currentTimeMillis() - start; tv.setText(result + " in " + usedTime + "ms"); // Java calculate long start2 = System.currentTimeMillis(); int result2 = Fibonacci.fibonacciNormal(param); long usedTime2 = System.currentTimeMillis() - start2; tv2.setText(result2 + " in " + usedTime2 + "ms"); } public native int calculate(int param); }
package com.zjut.bluetoothle; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class TimeHelper { static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); static SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMddHHmmss"); private static Date baseData = new Date(100, 0, 1, 0, 0, 0); private static Date targetData = null; public static String getDatetime() { return sdf2.format(new Date()); } public static String secondToDate(long second) { //baseData=sdf.parse(baseDateString); //System.out.println(baseData); targetData = new Date(baseData.getTime() + second * 1000); //System.out.println(targetData); return sdf.format(targetData); } public static String secondToDate(String secondString) { long second = Long.parseLong(secondString); return secondToDate(second); } public static String dateToSecond(String dateString) { Date date = new Date(); long second = 0; try { date = sdf.parse(dateString); second = (date.getTime() - baseData.getTime()) / 1000; //baseData=sdf.parse(baseDateString); } catch (ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return String.valueOf(second); } public static String dateToSecond(Date date) { long second = 0; second = (date.getTime() - baseData.getTime()) / 1000; return String.valueOf(second); } public static String dateToSecond() { long second = 0; //System.out.println(baseData.getTime()/1000); second = (new Date().getTime() - baseData.getTime()) / 1000; return String.valueOf(second); } public static int compareTime(int deviceTime) { long compare = 0; compare = deviceTime - (new Date().getTime() - baseData.getTime()) / 1000; return (int) compare; } public static String compareString(int deviceTime) { String string = null; int compare = compareTime(deviceTime); if (Math.abs(compare) > 5) { string = "未同步"; } else { string = "已同步"; } return string; } public static String minuteToDate(String minuteString) { Long minute = Long.parseLong(minuteString); return secondToDate(minute * 60); } public static String getMobileTime() { return sdf.format(new Date()); } }
package assignment4; import java.util.Scanner; public class Question31 { public static void main(String[] args) { Question31 obj = new Question31(); Scanner sc = new Scanner(System.in); System.out.println("\nPrinting pattern\n"); System.out.print("Enter the number: "); int number = sc.nextInt(); obj.printPattern(number); sc.close(); } public void printPattern(int a) { System.out.println("\n"); for(int i=1; i<= a; i++) { System.out.print("\t"); for (int j=1; j<=i ; j++) System.out.print(" " + j); System.out.println(); } } }
package org.jctools.queues.atomic; import java.util.ArrayList; import java.util.Collection; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.jctools.queues.MessagePassingQueue; import org.jctools.queues.MpqSanityTestMpscChunked; import org.jctools.queues.MpscChunkedArrayQueue; import org.jctools.queues.spec.ConcurrentQueueSpec; import org.jctools.queues.spec.Ordering; @RunWith(Parameterized.class) public class AtomicMpqSanityTestMpscChunked extends MpqSanityTestMpscChunked { public AtomicMpqSanityTestMpscChunked(ConcurrentQueueSpec spec, MessagePassingQueue<Integer> queue) { super(spec, queue); } @Parameterized.Parameters public static Collection<Object[]> parameters() { ArrayList<Object[]> list = new ArrayList<Object[]>(); list.add(makeAtomic(0, 1, 4, Ordering.FIFO, new MpscChunkedArrayQueue<>(2, 4)));// MPSC size 1 list.add(makeAtomic(0, 1, SIZE, Ordering.FIFO, new MpscChunkedArrayQueue<>(8, SIZE)));// MPSC size SIZE return list; } }
package com.itcia.itgoo; import java.security.Principal; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.access.annotation.Secured; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; 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 org.springframework.web.multipart.MultipartFile; import org.springframework.web.servlet.ModelAndView; import com.itcia.itgoo.dto.Member; import com.itcia.itgoo.service.ActivityManagement; import com.itcia.itgoo.service.AuctionManagement; import com.itcia.itgoo.service.ClientManagement; @RestController public class RestClientController { @Autowired private ClientManagement cm; @Autowired private AuctionManagement am; @Autowired private ActivityManagement acm; ModelAndView mav = new ModelAndView(); @Secured("ROLE_USER") @PostMapping(value = "/adoptlistdetail", produces="plain/text;charset=utf-8") public String adoptlistdetail(String dogid) { System.out.println("==============================controller=============================\ndogid:"+dogid); String dogpics = cm.adoptlistdetail(dogid); return dogpics; } @Secured("ROLE_USER") @PostMapping(value = "/myadoptlistdetail", produces="plain/text;charset=utf-8") public String myadoptlistdetail(String dogid,Principal p) { System.out.println("==============================controller=============================\ndogid:"+dogid); String dogpics = cm.myAdoptlistdetail(dogid,p); return dogpics; } @Secured("ROLE_USER") @GetMapping(value = "/updateusername", produces="plain/text;charset=utf-8") public String updateusername(Principal p,Member mb) { System.out.println("==============================controller=============================\n:"+p.getName()); mav = cm.updateusername(p,mb); return "{\"a\":\"성공했습니다.\"}"; } @Secured("ROLE_USER") @GetMapping(value = "/updateuseremail", produces="plain/text;charset=utf-8") public String updateuseremail(Principal p,Member mb) { System.out.println("==============================controller=============================\n:"+p.getName()); mav = cm.updateuseremail(p,mb); return "{\"a\":\"성공했습니다.\"}"; } @Secured("ROLE_USER") @GetMapping(value = "/updateuserphone", produces="plain/text;charset=utf-8") public String updateuserphone(Principal p,Member mb) { System.out.println("==============================controller=============================\n:"+p.getName()); mav = cm.updateuserphone(p,mb); return "{\"a\":\"성공했습니다.\"}"; } @Secured("ROLE_USER") @GetMapping(value = "/updateuserbirth", produces="plain/text;charset=utf-8") public String updateuserbirth(Principal p,Member mb) { System.out.println("==============================controller=============================\n:"+p.getName()); mav = cm.updateuserbirth(p,mb); return "{\"a\":\"성공했습니다.\"}"; } @Secured("ROLE_USER") @GetMapping(value = "/updateuseraddress", produces="plain/text;charset=utf-8") public String updateuseraddress(Principal p,Member mb) { System.out.println("==============================controller=============================\n:"+p.getName()); mav = cm.updateuseraddress(p,mb); return "{\"a\":\"성공했습니다.\"}"; } //ck에디터 이미지 업로드 @PostMapping("/ck/upload") public String ckUpload(@RequestParam(value="upload", required = false) MultipartFile file) { System.out.println("===================ckupload===================="); System.out.println(file.getOriginalFilename()); return am.ckUpload(file); } @RequestMapping(value = "/activitylistdetail" , method = RequestMethod.GET) public ModelAndView activityListDetail(Integer activitynum,int dogid) { //null 값도 받으려고 System.out.println("여기 있어요"); ModelAndView mav= new ModelAndView(); mav= acm.activityListDetail(activitynum,dogid); return mav; } }
package com.innova.timetable; import android.app.Application; import androidx.lifecycle.LiveData; import com.innova.timetable.dao.LessonDao; import com.innova.timetable.dao.TaskDao; import com.innova.timetable.models.Lesson; import com.innova.timetable.models.Task; import java.util.List; public class DataRepository { public static final String TAG = "DataRepository"; private final LiveData<List<Lesson>> mLessons; private final LiveData<List<Task>> mTasks; Application mApplication; private final LessonDao mLessonDao; private final TaskDao mTaskDao; public DataRepository(Application application) { AppRoomDatabase db = AppRoomDatabase.getDatabase(application); mApplication = application; mLessonDao = db.LessonDao(); mTaskDao = db.TaskDao(); mLessons = mLessonDao.getLessonsOfDay("mon"); mTasks = mTaskDao.getAllTasks(); } public LiveData<List<Lesson>> getAllLessons() { return mLessons; } public long insertLesson(Lesson lesson) { return mLessonDao.insertLesson(lesson); } }
package com.company.lesson09; public class Robot { private String name; private int hp; private int power; }
package com.cpro.rxjavaretrofit.entity; /** * Created by lx on 2016/6/16. */ public class PubClassInfoListEntity { private Long pubclassId; private String pubclassCode; private String subject; private String pubclassName; private String teacherName; private String brief; private Long classTime; private Integer howlong; private String site; private String status; private Long endTime; private String imageId; private String adminMemberRoleId; private String createUserid; private Long createTime; private String updateUserid; private Long updateTime; private String isValid; public Long getPubclassId() { return pubclassId; } public void setPubclassId(Long pubclassId) { this.pubclassId = pubclassId; } public String getPubclassCode() { return pubclassCode; } public void setPubclassCode(String pubclassCode) { this.pubclassCode = pubclassCode; } public String getSubject() { return subject; } public void setSubject(String subject) { this.subject = subject; } public String getPubclassName() { return pubclassName; } public void setPubclassName(String pubclassName) { this.pubclassName = pubclassName; } public String getTeacherName() { return teacherName; } public void setTeacherName(String teacherName) { this.teacherName = teacherName; } public String getBrief() { return brief; } public void setBrief(String brief) { this.brief = brief; } public Long getClassTime() { return classTime; } public void setClassTime(Long classTime) { this.classTime = classTime; } public Integer getHowlong() { return howlong; } public void setHowlong(Integer howlong) { this.howlong = howlong; } public String getSite() { return site; } public void setSite(String site) { this.site = site; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Long getEndTime() { return endTime; } public void setEndTime(Long endTime) { this.endTime = endTime; } public String getImageId() { return imageId; } public void setImageId(String imageId) { this.imageId = imageId; } public String getAdminMemberRoleId() { return adminMemberRoleId; } public void setAdminMemberRoleId(String adminMemberRoleId) { this.adminMemberRoleId = adminMemberRoleId; } public String getCreateUserid() { return createUserid; } public void setCreateUserid(String createUserid) { this.createUserid = createUserid; } public Long getCreateTime() { return createTime; } public void setCreateTime(Long createTime) { this.createTime = createTime; } public String getUpdateUserid() { return updateUserid; } public void setUpdateUserid(String updateUserid) { this.updateUserid = updateUserid; } public Long getUpdateTime() { return updateTime; } public void setUpdateTime(Long updateTime) { this.updateTime = updateTime; } public String getIsValid() { return isValid; } public void setIsValid(String isValid) { this.isValid = isValid; } }
package network.warzone.tgm.util; import com.google.common.collect.Sets; import org.bukkit.Material; import java.util.Set; public class Blocks { private static String[] visualChoices = {"WOOL", "CARPET", "TERRACOTTA", "STAINED_GLASS", "STAINED_GLASS_PANE"}; public static boolean isVisualMaterial(Material material) { String name = material.name(); for(String visualChoice : visualChoices) if(name.contains(visualChoice)) return true; return false; } public static String whichVisualMaterial(Material material) { for(String visualChoice : visualChoices) if(material.name().contains(visualChoice)) return visualChoice; return "NONE"; } }
package com.maxmind.geoip2.model; import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.stubFor; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; import static com.maxmind.geoip2.json.File.readJsonFile; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import com.github.tomakehurst.wiremock.junit.WireMockRule; import com.maxmind.geoip2.WebServiceClient; import com.maxmind.geoip2.exception.GeoIp2Exception; import com.maxmind.geoip2.record.Location; import com.maxmind.geoip2.record.MaxMind; import com.maxmind.geoip2.record.Postal; import com.maxmind.geoip2.record.Subdivision; import com.maxmind.geoip2.record.Traits; import java.io.IOException; import java.net.InetAddress; import java.net.URISyntaxException; import java.util.List; import org.junit.Before; import org.junit.Rule; import org.junit.Test; public class InsightsResponseTest { @Rule public final WireMockRule wireMockRule = new WireMockRule(0); private InsightsResponse insights; @Before public void createClient() throws IOException, GeoIp2Exception, URISyntaxException { stubFor(get(urlEqualTo("/geoip/v2.1/insights/1.1.1.1")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/vnd.maxmind.com-insights+json; charset=UTF-8; version=2.1") .withBody(readJsonFile("insights0")))); stubFor(get(urlEqualTo("/geoip/v2.1/insights/1.1.1.2")) .willReturn(aResponse() .withStatus(200) .withHeader("Content-Type", "application/vnd.maxmind.com-insights+json; charset=UTF-8; version=2.1") .withBody(readJsonFile("insights1")))); WebServiceClient client = new WebServiceClient.Builder(6, "0123456789") .host("localhost") .port(this.wireMockRule.port()) .disableHttps() .build(); this.insights = client.insights(InetAddress.getByName("1.1.1.1")); } @Test public void testSubdivisionsList() { List<Subdivision> subdivisionsList = this.insights.getSubdivisions(); assertNotNull("city.getSubdivisionsList returns null", subdivisionsList); if (subdivisionsList.isEmpty()) { fail("subdivisionsList is empty"); } Subdivision subdivision = subdivisionsList.get(0); assertEquals("subdivision.getConfidence() does not return 88", Integer.valueOf(88), subdivision.getConfidence()); assertEquals("subdivision.getGeoNameId() does not return 574635", 574635, subdivision.getGeoNameId().intValue()); assertEquals("subdivision.getCode() does not return MN", "MN", subdivision.getIsoCode()); } @Test public void mostSpecificSubdivision() { assertEquals("Most specific subdivision returns last subdivision", "TT", this.insights.getMostSpecificSubdivision().getIsoCode()); } @Test public void leastSpecificSubdivision() { assertEquals("Most specific subdivision returns first subdivision", "MN", this.insights.getLeastSpecificSubdivision().getIsoCode()); } @Test public void testTraits() { Traits traits = this.insights.getTraits(); assertNotNull("city.getTraits() returns null", traits); assertEquals("traits.getAutonomousSystemNumber() does not return 1234", Long.valueOf(1234), traits.getAutonomousSystemNumber()); assertEquals( "traits.getAutonomousSystemOrganization() does not return AS Organization", "AS Organization", traits.getAutonomousSystemOrganization()); assertEquals( "traits.getAutonomousSystemOrganization() does not return example.com", "example.com", traits.getDomain()); assertEquals("traits.getIpAddress() does not return 1.2.3.4", "1.2.3.4", traits.getIpAddress()); assertTrue("traits.isAnonymous() returns true", traits.isAnonymous()); assertTrue("traits.isAnonymousProxy() returns true", traits.isAnonymousProxy()); assertTrue("traits.isAnonymousVpn() returns true", traits.isAnonymousVpn()); assertTrue("traits.isHostingProvider() returns true", traits.isHostingProvider()); assertTrue("traits.isPublicProxy() returns true", traits.isPublicProxy()); assertTrue("traits.isResidentialProxy() returns true", traits.isResidentialProxy()); assertTrue("traits.isSatelliteProvider() returns true", traits.isSatelliteProvider()); assertTrue("traits.isTorExitNode() returns true", traits.isTorExitNode()); assertEquals("traits.getIsp() does not return Comcast", "Comcast", traits.getIsp()); assertEquals("traits.getOrganization() does not return Blorg", "Blorg", traits.getOrganization()); assertEquals("traits.getUserType() does not return userType", "college", traits.getUserType()); assertEquals("traits.getStaticIpScore() does not return 1.3", Double.valueOf(1.3), traits.getStaticIpScore()); assertEquals("traits.getUserCount() does not return 2", Integer.valueOf(2), traits.getUserCount()); } @Test public void testLocation() { Location location = this.insights.getLocation(); assertNotNull("city.getLocation() returns null", location); assertEquals("location.getAverageIncome() does not return 24626,", Integer.valueOf(24626), location.getAverageIncome()); assertEquals("location.getAccuracyRadius() does not return 1500", Integer.valueOf(1500), location.getAccuracyRadius()); double latitude = location.getLatitude(); assertEquals("location.getLatitude() does not return 44.98", 44.98, latitude, 0.1); double longitude = location.getLongitude(); assertEquals("location.getLongitude() does not return 93.2636", 93.2636, longitude, 0.1); assertEquals("location.getMetroCode() does not return 765", Integer.valueOf(765), location.getMetroCode()); assertEquals("location.getPopulationDensity() does not return 1341,", Integer.valueOf(1341), location.getPopulationDensity()); assertEquals("location.getTimeZone() does not return America/Chicago", "America/Chicago", location.getTimeZone()); } @Test public void testMaxMind() { MaxMind maxmind = this.insights.getMaxMind(); assertEquals("Correct number of queries remaining", 11, maxmind .getQueriesRemaining().intValue()); } @Test public void testPostal() { Postal postal = this.insights.getPostal(); assertEquals("postal.getCode() does not return 55401", "55401", postal.getCode()); assertEquals("postal.getConfidence() does not return 33", Integer.valueOf( 33), postal.getConfidence()); } @Test public void testRepresentedCountry() { assertNotNull("city.getRepresentedCountry() returns null", this.insights.getRepresentedCountry()); assertEquals( "city.getRepresentedCountry().getType() does not return C<military>", "C<military>", this.insights.getRepresentedCountry().getType()); assertTrue( "city.getRepresentedCountry().isInEuropeanUnion() does not return true", this.insights.getRepresentedCountry().isInEuropeanUnion()); } @Test public void testIsInEuropeanUnion() throws IOException, GeoIp2Exception { // This uses an alternate fixture where we have the // is_in_european_union flag set in locations not set in the other // fixture. WebServiceClient client = new WebServiceClient.Builder(6, "0123456789") .host("localhost") .port(this.wireMockRule.port()) .disableHttps() .build(); InsightsResponse insights = client.insights( InetAddress.getByName("1.1.1.2")); assertTrue("getCountry().isInEuropeanUnion() does not return true", insights.getCountry().isInEuropeanUnion()); assertTrue( "getRegisteredCountry().() isInEuropeanUnion = does not return true", insights.getRegisteredCountry().isInEuropeanUnion()); } }
package com.tech42.callrecorder.views; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import com.github.mikephil.charting.charts.PieChart; import com.github.mikephil.charting.data.Entry; import com.github.mikephil.charting.data.PieData; import com.github.mikephil.charting.data.PieDataSet; import com.github.mikephil.charting.formatter.PercentFormatter; import com.github.mikephil.charting.utils.ColorTemplate; import com.tech42.callrecorder.R; import java.util.ArrayList; public class StorageActivity extends AppCompatActivity { PieChart storagePieChart; public static final int[] MY_COLORS = { Color.rgb(153,255,153), Color.rgb(255,204,153) }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_storage); storagePieChart = (PieChart) findViewById(R.id.piechart); storagePieChart.setUsePercentValues(true); createDataSet(); } private void createDataSet(){ ArrayList<Entry> yvalues = new ArrayList<Entry>(); yvalues.add(new Entry(60f, 0)); yvalues.add(new Entry(40f, 1)); PieDataSet dataSet = new PieDataSet(yvalues, ""); ArrayList<String> xVals = new ArrayList<String>(); xVals.add("Cloud Storage"); xVals.add("Local Storage"); PieData data = new PieData(xVals, dataSet); data.setValueFormatter(new PercentFormatter()); storagePieChart.setData(data); data.setValueTextSize(15f); data.setValueTextColor(Color.DKGRAY); storagePieChart.setDrawHoleEnabled(true); storagePieChart.setTransparentCircleRadius(40f); storagePieChart.setHoleRadius(40f); // adding colors ArrayList<Integer> colors = new ArrayList<Integer>(); // Added My Own colors for (int c : MY_COLORS) colors.add(c); dataSet.setColors(colors); dataSet.setColors(ColorTemplate.VORDIPLOM_COLORS); } }
package com.example.ecoleenligne; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.app.Dialog; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Build; import android.os.Bundle; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageView; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonArrayRequest; import com.android.volley.toolbox.JsonObjectRequest; import com.android.volley.toolbox.Volley; import com.example.ecoleenligne.model.CourseContent; import com.example.ecoleenligne.util.CourseContentListAdapter; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; import java.util.Objects; public class MySpaceActivity extends AppCompatActivity { final Context context = this; private SharedPreferences sharedpreferences; private CourseContentListAdapter courseContentListAdapter; ListView listview; List<CourseContent> myDocuements = new ArrayList<CourseContent>(); Dialog dialog; ImageView closePoppupNegativeImg; TextView negative_title, negative_content; Button negative_button; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my_space); //Actionbar config getSupportActionBar().setDisplayHomeAsUpEnabled(true); getSupportActionBar().setTitle(R.string.navigation_menu_myspace); getSupportActionBar().setBackgroundDrawable( new ColorDrawable( getResources().getColor(R.color.colorRedGo))); //Transparent statusbar if (Build.VERSION.SDK_INT >= 21) { Window window = getWindow(); window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS); window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS); } this.courseContentListAdapter = new CourseContentListAdapter(this, myDocuements); ListView studentsListView = findViewById(R.id.list_students); studentsListView.setAdapter(courseContentListAdapter); sharedpreferences = getSharedPreferences(MainActivity.MyPREFERENCES, Context.MODE_PRIVATE); String user_connected_id = sharedpreferences.getString(MainActivity.Id, null); /*-------------- check if there is connection--------------*/ if(MainActivity.MODE.equals("ONLINE")) { /*------------------ get profile from server -----------------*/ String url = MainActivity.IP + "/api/profile/" + user_connected_id; RequestQueue queue = Volley.newRequestQueue(context); JSONObject jsonObject = new JSONObject(); JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, jsonObject, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { try { String user_exist = response.getString("email"); if (user_exist.equals("not found")) { Toast.makeText(context, "User not exist", Toast.LENGTH_LONG).show(); } else { //String fullname_data = response.getString("firstName")+" "+response.getString("lastName"); //String birthday_data = response.getString("date_birth"); myDocuements = new ArrayList<>(response.getJSONArray("desktopDocuments").length()); for (int i = 0; i < response.getJSONArray("desktopDocuments").length(); i++) { JSONObject item = response.getJSONArray("desktopDocuments").getJSONObject(i); // String id = item.getString("_id"); String id = item.getString("id"); String title = item.getString("name"); String path = MainActivity.IP_myspace +"/TER.git/public/"+ item.getString("file"); String string = item.getString("file"); String[] parts = string.split("\\."); String extension = parts[1]; String type = ""; if(extension.equals("pdf")) type = ""+1; else if(extension.equals("jpg") || extension.equals("jpeg") || extension.equals("gif") || extension.equals("png")) type = ""+3; myDocuements.add(new CourseContent(Integer.parseInt(id), title, path, type)); } courseContentListAdapter.setcourseContents(myDocuements); } } catch (JSONException e) { e.printStackTrace(); new AlertDialog.Builder(context) .setTitle("Error") .setMessage(e.toString()) .show(); } } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { new AlertDialog.Builder(context) .setTitle("Error") .setMessage(R.string.server_restful_error) .show(); } }); queue.add(request); } else { } } public void backStep(View view) { finish(); } private void actionNegative() { dialog.setContentView(R.layout.popup_negative); closePoppupNegativeImg = dialog.findViewById(R.id.negative_close); closePoppupNegativeImg.setOnClickListener(v -> dialog.dismiss()); Objects.requireNonNull(dialog.getWindow()).setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); dialog.show(); } }
package app.com.example.android.identity; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.view.View; public class voterid extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_voterid); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); } public void register_now(View view){ Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://eci.nic.in/")); startActivity(browserIntent); } }
package com.outfitterandroid.unittests; import com.outfitterandroid.User; import com.parse.ParseException; import com.parse.ParseUser; import junit.framework.TestCase; public class UserTest extends TestCase { /** * Tests priority submission setting */ public void testPrioritySubmission() throws ParseException { ParseUser user = ParseUser.logIn("old_user", "old_user"); boolean isPriority = User.hasSubmittedPrioritySubmissionToday(user); assertFalse(isPriority); } }
package repositoryDAO; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import entidades.Loja; public class LojaDAO { private Connection connection; public LojaDAO(){ this.connection = new ConnectionFactory().getConnection(); } public void adiciona(Loja loja){ String sql = "insert into loja (nome,endereco,cnpj, imagem)" + "values(?,?,?,?)"; try { PreparedStatement stmt = connection.prepareStatement(sql); stmt.setString(1, loja.getNome()); stmt.setString(2, loja.getEndereco()); stmt.setString(3, loja.getCnpj()); stmt.setString(4, loja.getImagem()); stmt.execute(); stmt.close(); } catch (SQLException e) { throw new RuntimeException(e); } } }
package com.hr.personnel.service; import com.hr.login.model.LoginModel; public interface UpdatePasswordService { boolean updateNewPassword(LoginModel loginModel, String newPassword); LoginModel findNewLoginModel(LoginModel loginModel); }
package com.imooc.service; import com.imooc.pojo.*; import com.imooc.pojo.vo.CommentCountsVO; import com.imooc.pojo.vo.ShopCartVO; import com.imooc.utils.PagedGridResult; import java.util.List; /** * 商品详情页相关接口 */ public interface ItemService { /** * 根据商品id查询商品 * @return */ Items getItemsById(String itemId); /** * 根据商品id查询商品图片 * @param itemId * @return */ List<ItemsImg> getItemImgList(String itemId); /** * 根据商品id查询商品规格信息 * @param itemId * @return */ List<ItemsSpec> getItemSpecList(String itemId); /** * 根据商品id查询商品参数 * @param itemId * @return */ ItemsParam getItemParam(String itemId); /** * 根据商品id查询商品评价数 * @param itemId */ CommentCountsVO getCommentCounts(String itemId); /** * 根据商品id和评价等级查询商品评价(分页) * @param itemId * @param level * @return */ PagedGridResult getItemComments(String itemId, Integer level, Integer page, Integer pageSize); /** * 搜索商品(分页) * @param keywords * @param sort * @param page * @param pageSize * @return */ PagedGridResult searchItems(String keywords, String sort, Integer page, Integer pageSize); /** * 三级分类下搜索商品(分页) * @param catId * @param sort * @param page * @param pageSize * @return */ PagedGridResult searchItemsByThirdCat(Integer catId, String sort, Integer page, Integer pageSize); /** * 购物车商品刷新 * @param specIds * @return */ List<ShopCartVO> getItemsBySpecIds(String specIds); /** * 根据商品规格ID获取商品规格对象具体信息 * @param itemSpecId * @return */ ItemsSpec getItemByItemSpecId(String itemSpecId); /** * 根据商品ID获取商品主图 * @param itemId * @return */ String getItemMainImgById(String itemId); /** * 库存商品数量扣除 * @param specId * @param buyCounts */ void reduceItemStock(String specId,int buyCounts); }
package com.axibase.tsd.api.method.extended; import com.axibase.tsd.api.Checker; import com.axibase.tsd.api.method.BaseMethod; import com.axibase.tsd.api.method.checks.AbstractCheck; import com.axibase.tsd.api.model.command.PlainCommand; import com.axibase.tsd.api.model.extended.CommandSendingResult; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.util.Arrays; import java.util.List; public class CommandMethod extends BaseMethod { private static final String METHOD_PATH = "command"; private static final WebTarget METHOD_RESOURCE = httpApiResource.path(METHOD_PATH); public static Response sendResponse(String payload) { Response response = METHOD_RESOURCE.request().post(Entity.entity(payload, MediaType.TEXT_PLAIN)); response.bufferEntity(); return response; } public static CommandSendingResult send(String payload) { return sendResponse(payload).readEntity(CommandSendingResult.class); } public static CommandSendingResult send(PlainCommand command) { return send(command.compose()); } public static CommandSendingResult send(List<PlainCommand> commandList) { return send(buildPayload(commandList)); } private static String buildPayload(List<PlainCommand> commandList) { StringBuilder queryBuilder = new StringBuilder(); for (PlainCommand command : commandList) { queryBuilder .append(String.format("%s%n", command.compose())); } return queryBuilder.toString(); } public static void sendChecked(AbstractCheck check, List<PlainCommand> commandList) { CommandSendingResult result = send(commandList); if (result.getSuccess() != commandList.size()) { String errorMessage = String.format( "Failed to send following commands: %n %s", buildPayload(commandList) ); throw new IllegalStateException(errorMessage); } else { Checker.check(check); } } public static void sendChecked(AbstractCheck check, PlainCommand... commands) { sendChecked(check, Arrays.asList(commands)); } }
package com.project.universitystudentassistant.adapters; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ImageButton; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; import androidx.recyclerview.widget.RecyclerView.ViewHolder; import com.project.universitystudentassistant.R; import com.project.universitystudentassistant.models.Subject; import com.project.universitystudentassistant.models.SubjectSchedule; import com.project.universitystudentassistant.models.SubjectTime; import java.time.DayOfWeek; import java.time.format.TextStyle; import java.util.List; import java.util.Locale; public class WeekPickerAdapter extends RecyclerView.Adapter<WeekPickerAdapter.WeekPickerViewHolder> { private OnWeekPickerClickListener listener; List<SubjectTime> weekList; public WeekPickerAdapter(OnWeekPickerClickListener listener, List<SubjectTime> weekList) { this.listener = listener; this.weekList = weekList; } public void updateData(List<SubjectTime> data) { weekList.clear(); weekList.addAll(data); notifyDataSetChanged(); } @NonNull @Override public WeekPickerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.week_day_picker, parent, false); return new WeekPickerViewHolder(view, listener); } @Override public void onBindViewHolder(@NonNull WeekPickerViewHolder holder, int position) { SubjectTime subjectTime = weekList.get(position); holder.weekDay.setText(subjectTime.getDayOfWeek().getDisplayName(TextStyle.SHORT, Locale.US)); holder.weekDay.setChecked(subjectTime.isActive()); holder.start.setText(subjectTime.getStartHour().toString()); holder.end.setText(subjectTime.getEndHour().toString()); // holder.setViews(subjectTime.isActive()); holder.setSubjectTime(subjectTime); } @Override public int getItemCount() { return weekList.size(); } public class WeekPickerViewHolder extends ViewHolder { private TextView start, end; private CheckBox weekDay; private SubjectTime subjectTime = new SubjectTime(); private boolean isChecked; public WeekPickerViewHolder(@NonNull View itemView, OnWeekPickerClickListener listener) { super(itemView); weekDay = itemView.findViewById(R.id.checkbox_week_day); start = itemView.findViewById(R.id.txt_from_picker); end = itemView.findViewById(R.id.txt_to_picker); // setViews(false); weekDay.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { listener.onWeekDayChecked(subjectTime, true); } }); start.setOnClickListener(v -> listener.onHourClicked(subjectTime, true)); end.setOnClickListener(v -> listener.onHourClicked(subjectTime, false)); } public void setSubjectTime(SubjectTime subjectTime) { this.subjectTime = subjectTime; } public void setViews(boolean checked) { if (checked) { weekDay.setChecked(true); start.setEnabled(true); end.setEnabled(true); } else { weekDay.setChecked(false); start.setEnabled(false); end.setEnabled(false); } } public void setChecked(boolean checked) { isChecked = checked; } } public interface OnWeekPickerClickListener { void onWeekDayChecked(SubjectTime subjectTime, boolean checked); void onHourClicked(SubjectTime subjectTime, boolean startHour); } }
package com.egova.eagleyes.repository; import com.egova.baselibrary.model.Lcee; import com.egova.eagleyes.model.request.TFLoginRequest; import com.egova.baselibrary.model.BaseResponse; import com.egova.eagleyes.model.respose.LoginResponse; import androidx.lifecycle.LiveData; public interface LoginRepository { //TF卡登陆 LiveData<Lcee<BaseResponse<LoginResponse>>> tfLogin(TFLoginRequest loginRequest); }
package dao; import java.util.HashMap; import java.util.Map; import org.mybatis.spring.SqlSessionTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import dao.mapper.FileMapper; import logic.SNSFile; @Repository public class fileDao { @Autowired private SqlSessionTemplate template; private Map <String, Object> param = new HashMap <String, Object> (); public SNSFile maxfno() { return template.getMapper(FileMapper.class).maxfno(); } public void insert_file(SNSFile f) { template.getMapper(FileMapper.class).insert_file(f); } }
/* * 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 mandelbrot.gui; import java.awt.Color; import java.awt.Component; import java.awt.Dimension; import java.awt.Graphics; import java.awt.event.ComponentEvent; import java.awt.event.ComponentListener; import java.util.ArrayList; import javax.swing.JFrame; import javax.swing.JPanel; /** * @author Raphaël **/ public class GodlikePanel extends JPanel implements ComponentListener { protected ArrayList<ConstrainedComponent> components; protected ArrayList<Constraint> constraints; protected ArrayList<Constraint> constraintsToSatisfy; protected String errorLog; protected ArrayList<Constraint> overConstraints; protected boolean debugMode; public enum Border { LEFT("left"), RIGHT("right"), TOP("top"), BOTTOM("bottom"); String name; Border(String name) { this.name = name; } public boolean isHorizontal() { return this == LEFT || this == RIGHT; } public boolean isVertical() { return this == TOP || this == BOTTOM; } public Border opposite() { switch(this) { case LEFT : return RIGHT; case RIGHT : return LEFT; case TOP : return BOTTOM; default : return TOP; } } public int direction() { switch(this) { case LEFT : case TOP : return -1; case RIGHT : default : return 1; } } @Override public String toString() { return name+" border"; } } public GodlikePanel(boolean doubleBuffered) { super(null, doubleBuffered); ConstrainedComponent mainComp = new ConstrainedComponent(this); mainComp.horizontalResizable = false; mainComp.verticalResizable = false; mainComp.leftFixed = true; mainComp.rightFixed = true; mainComp.topFixed = true; mainComp.bottomFixed = true; components = new ArrayList(); components.add(mainComp); constraints = new ArrayList(); constraintsToSatisfy = new ArrayList(); overConstraints = new ArrayList(); debugMode = false; addComponentListener(this); } public GodlikePanel() { this(false); } public boolean isDebugMode() { return debugMode; } public void setDebugMode(boolean debugMode) { if(debugMode) { for(ConstrainedComponent constComp : components) { if(constComp.component.getName() == null) { if(constComp.component == this) { throw new IllegalStateException("All components need a name for debug mode, even the parent component."); } else { throw new IllegalStateException("All children components need a name for debug mode."); } } } } this.debugMode = debugMode; } public void addComponent(Component comp) { try { ConstrainedComponent constComp = getConstrainedComponent(comp); } catch(NullPointerException e) { add(comp); components.add(new ConstrainedComponent(comp)); } } public void addConstraint(Component comp1, Component comp2, Border border1, Border border2, int distance) { if(comp1 == null) throw new NullPointerException("Parameter comp1 mustn't be null."); if(comp2 == null) throw new NullPointerException("Parameter comp2 mustn't be null."); if(comp1 == comp2) throw new IllegalArgumentException("A constraint can only be added between two different components."); if(border1.isHorizontal() && border2.isVertical() || border1.isVertical() && border2.isHorizontal()) {throw new IllegalArgumentException("Borders are not compatible.");} ConstrainedComponent constComp1 = getConstrainedComponent(comp1), constComp2 = getConstrainedComponent(comp2); Constraint c = new Constraint(constComp1, constComp2, border1, border2, distance); constraints.add(c); constComp1.constraints.add(c); constComp2.constraints.add(c); } public void addConstraint(Component comp1, Component comp2, Border border1, Border border2) { addConstraint(comp1, comp2, border1, border2, 0); } protected ConstrainedComponent getConstrainedComponent(Component comp) throws NullPointerException { if(comp == null) throw new NullPointerException("Parameter comp mustn't be null."); for(ConstrainedComponent constComp : components) { if(constComp.component == comp) { return constComp; } } throw new NullPointerException("Component not added to the GodlikePanel."); } public final void setHorizontalResizable(Component comp) { getConstrainedComponent(comp).horizontalResizable = true; } public final void setVerticalResizable(Component comp) { getConstrainedComponent(comp).verticalResizable = true; } public void setFixedWidth(Component comp, int width) { ConstrainedComponent constComp = getConstrainedComponent(comp); if(comp == this) throw new IllegalArgumentException("You can't fix the main component's size."); constComp.horizontalResizable = false; comp.setSize(width, (int)comp.getSize().getHeight()); } public void setFixedHeight(Component comp, int height) { ConstrainedComponent constComp = getConstrainedComponent(comp); if(comp == this) throw new IllegalArgumentException("You can't fix the main component's size."); constComp.verticalResizable = false; comp.setSize((int)comp.getSize().getWidth(), height); } public void addUnsatisfiedConstraints(ArrayList<Constraint> source, ArrayList<Constraint> destination) { for(Constraint constraint : source) { if(!constraint.satisfied && !destination.contains(constraint)) { destination.add(constraint); if(debugMode) System.out.println("add "+constraint); } } } protected void layoutComponents() { errorLog = ""; overConstraints.clear(); ConstrainedComponent mainComp = components.get(0); mainComp.left = 0; mainComp.right = getWidth(); mainComp.top = 0; mainComp.bottom = getHeight(); for(int i = 1; i < components.size(); i++) { ConstrainedComponent constComp = components.get(i); constComp.leftFixed = false; constComp.rightFixed = false; constComp.topFixed = false; constComp.bottomFixed = false; } for(Constraint constraint : constraints) { constraint.satisfied = false; } constraintsToSatisfy.clear(); if(debugMode) System.out.println("\nGodlikePanel - debug mode\n" + " - \"add\" means that the constraint is added to the list of constraints to satisfy.\n" + " The constraints are satisfied according to their order in the list.\n" + " - \"fix\" means that the component's border is calculated from a fixed border of the other component\n"); for(Constraint constraint : mainComp.constraints) { constraintsToSatisfy.add(constraint); if(debugMode) System.out.println("add "+constraint); } if(debugMode) System.out.println(); while(constraintsToSatisfy.size() > 0) { if(debugMode) System.out.println("satifying "+constraintsToSatisfy.get(0)); addUnsatisfiedConstraints(constraintsToSatisfy.get(0).satisfy(), constraintsToSatisfy); if(debugMode) System.out.println("constraint satisfied\n"); constraintsToSatisfy.remove(0); } for(int i = 1; i < components.size(); i++) { ConstrainedComponent constComp = components.get(i); Component comp = constComp.component; comp.setLocation(constComp.left, constComp.top); if(constComp.horizontalResizable) { comp.setSize(constComp.right-constComp.left, (int)comp.getSize().getHeight()); } if(constComp.verticalResizable) { comp.setSize((int)comp.getSize().getWidth(), constComp.bottom-constComp.top); } } if(debugMode) { System.out.println("layout finished :"); for(ConstrainedComponent constComp : components) { Component comp = constComp.component; System.out.println(comp.getName()+" : location : "+comp.getLocation() + ", size : "+comp.getSize()); } if(overConstraints.size() > 0) { errorLog += "\n-> "+overConstraints.size() + (overConstraints.size() > 1 ? " constraints are" : " constraint is") + " overconstraining the set :\n"; for(Constraint constraint : overConstraints) { errorLog += constraint+"\n"; } } ArrayList<Constraint> unreachableConstraints = new ArrayList(); for(Constraint constraint : constraints) { if(!constraint.satisfied) { unreachableConstraints.add(constraint); } } if(unreachableConstraints.size() > 0) { errorLog += "\n-> "+unreachableConstraints.size() +" constraint"+(unreachableConstraints.size() > 1 ? "s are" : " is") +" unreachable by propagation from the parent component :\n"; for(Constraint constraint : unreachableConstraints) { errorLog += constraint+"\n"; } } String unconstrainedComp = ""; int unconstrainedCompNbr = 0; for(ConstrainedComponent constComp : components) { if(!constComp.leftFixed || !constComp.rightFixed || !constComp.topFixed || !constComp.bottomFixed) { unconstrainedComp += constComp.component.getName()+" :\n" + (constComp.leftFixed ? "" : Border.LEFT+" not constrained\n") + (constComp.rightFixed ? "" : Border.RIGHT+" not constrained\n") + (constComp.topFixed ? "" : Border.TOP+" not constrained\n") + (constComp.bottomFixed ? "" : Border.BOTTOM+" not constrained\n"); unconstrainedCompNbr++; } } if(unconstrainedCompNbr > 0) { errorLog += "\n-> "+unconstrainedCompNbr+" component"+ (unconstrainedCompNbr > 1 ? "s are" : " is") +" not fully constrained :\n"+unconstrainedComp; } System.out.println("\nError log :\n" + (errorLog.isEmpty() ? "\nno error\n" : errorLog)); } } protected class ConstrainedComponent { public Component component; public ArrayList<Constraint> constraints; public boolean horizontalResizable, verticalResizable; public int left, right, top, bottom; public boolean leftFixed, rightFixed, topFixed, bottomFixed; public ConstrainedComponent(Component comp) { component = comp; constraints = new ArrayList(); horizontalResizable = true; verticalResizable = true; } public boolean isFixed(Border border) { switch(border) { case LEFT : return leftFixed; case RIGHT : return rightFixed; case TOP : return topFixed; default : return bottomFixed; } } public void fix(Border border) { switch(border) { case LEFT : leftFixed = true; break; case RIGHT : rightFixed = true; break; case TOP : topFixed = true; break; default : bottomFixed = true; break; } } public boolean isResizable(boolean horizontally) { return horizontally ? horizontalResizable : verticalResizable; } public int getSize(boolean horizontally) { return horizontally ? (int)component.getSize().getWidth() : (int)component.getSize().getHeight(); } public int getValue(Border border) { switch(border) { case LEFT : return left; case RIGHT : return right; case TOP : return top; default : return bottom; } } public void setValue(Border border, int value) { switch(border) { case LEFT : left = value; break; case RIGHT : right = value; break; case TOP : top = value; break; default : bottom = value; break; } } public ArrayList<Constraint> getAssociatedConstraints(Border fixedBorder) { ArrayList<Constraint> assocConstraints = new ArrayList(); for(Constraint constraint : constraints) { if(constraint.comp1 == this && constraint.border1 == fixedBorder || constraint.comp2 == this && constraint.border2 == fixedBorder) { assocConstraints.add(constraint); } } return assocConstraints; } } protected class Constraint { ConstrainedComponent comp1, comp2; Border border1, border2; int distance; boolean satisfied; public Constraint(ConstrainedComponent comp1, ConstrainedComponent comp2, Border border1, Border border2, int distance) { this.comp1 = comp1; this.comp2 = comp2; this.border1 = border1; this.border2 = border2; this.distance = distance; satisfied = false; } public ArrayList<Constraint> satisfy() { ArrayList<Constraint> nextConstraints = new ArrayList(); ConstrainedComponent refComp, compToFix; Border refBorder, borderToFix; if(comp1.isFixed(border1) && comp2.isFixed(border2)) { refComp = comp1; compToFix = comp2; refBorder = border1; borderToFix = border2; if(debugMode) overConstraints.add(this); } else if(comp1.isFixed(border1)) { refComp = comp1; compToFix = comp2; refBorder = border1; borderToFix = border2; } else { refComp = comp2; compToFix = comp1; refBorder = border2; borderToFix = border1; } // According to the propagation algorithm, there is always at least one already fixed border. compToFix.setValue(borderToFix, refComp.getValue(border1) + distance); compToFix.fix(borderToFix); if(debugMode) System.out.println("fix "+compToFix.component.getName()+"'s "+borderToFix+" at "+(refComp.getValue(refBorder) + distance)); nextConstraints.addAll(compToFix.getAssociatedConstraints(borderToFix)); if(!compToFix.isResizable(borderToFix.isHorizontal())) { compToFix.setValue(borderToFix.opposite(), compToFix.getValue(borderToFix) + borderToFix.opposite().direction()*compToFix.getSize(borderToFix.isHorizontal())); compToFix.fix(borderToFix.opposite()); if(debugMode) System.out.println("fix "+compToFix.component.getName()+"'s "+borderToFix.opposite()+" at "+(compToFix.getValue(borderToFix) + borderToFix.opposite().direction()*compToFix.getSize(borderToFix.isHorizontal()))+" ("+(borderToFix.isHorizontal() ? "width " : "height ")+compToFix.getSize(borderToFix.isHorizontal())+")"); nextConstraints.addAll(compToFix.getAssociatedConstraints(borderToFix.opposite())); } satisfied = true; return nextConstraints; } @Override public String toString() { return "constraint between "+comp1.component.getName()+"'s "+border1+" and "+comp2.component.getName()+"'s "+border2+", distance "+distance; } } @Override public void paintComponent(Graphics g) { super.paintComponent(g); paintComponents(g); } @Override public void componentResized(ComponentEvent e) { layoutComponents(); } @Override public void componentMoved(ComponentEvent e) { } @Override public void componentShown(ComponentEvent e) { } @Override public void componentHidden(ComponentEvent e) { } public static void main(String[] args) { JFrame f = new JFrame("Test Layout"); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); GodlikePanel p = new GodlikePanel(); p.setName("p"); p.setPreferredSize(new Dimension(300, 300)); JPanel p1 = new JPanel(); p1.setName("p1"); p1.setBackground(Color.RED); JPanel p2 = new JPanel(); p2.setName("p2"); p2.setBackground(Color.BLUE); JPanel p3 = new JPanel(); p3.setName("p3"); p3.setBackground(Color.CYAN); JPanel p4 = new JPanel(); p4.setName("p4"); p4.setBackground(Color.GREEN); p.addComponent(p1); p.addConstraint(p, p1, Border.LEFT, Border.LEFT, 20); p.addConstraint(p1, p, Border.RIGHT, Border.RIGHT, 40); p.addConstraint(p, p1, Border.TOP, Border.TOP, 60); p.addConstraint(p1, p, Border.BOTTOM, Border.BOTTOM, 200); p.addComponent(p2); p.addConstraint(p1, p2, Border.BOTTOM, Border.TOP); p.addConstraint(p2, p, Border.BOTTOM, Border.BOTTOM, 10); p.addConstraint(p1, p2, Border.LEFT, Border.LEFT, 10); p.addConstraint(p2, p1, Border.RIGHT, Border.RIGHT, 100); p.addComponent(p3); p.setFixedWidth(p3, 50); p.setFixedHeight(p3, 50); p.addConstraint(p2, p3, Border.RIGHT, Border.LEFT, 15); p.addConstraint(p1, p3, Border.BOTTOM, Border.TOP, 15); p.addComponent(p4); p.addConstraint(p3, p4, Border.RIGHT, Border.LEFT, 5); p.addConstraint(p4, p, Border.RIGHT, Border.RIGHT, 5); p.addConstraint(p3, p4, Border.TOP, Border.TOP, 5); p.addConstraint(p3, p4, Border.BOTTOM, Border.BOTTOM, 0); p.setDebugMode(true); f.setContentPane(p); f.pack(); f.setVisible(true); } }
package ru.avokin.uidiff.diff.folderdiff.model; import ru.avokin.uidiff.diff.common.model.DiffSideModel; /** * User: Andrey Vokin * Date: 01.10.2010 */ public class FolderDiffSideModel extends DiffSideModel { private final DiffTreeModel treeModel; private DiffFileTreeNode selectedNode; public FolderDiffSideModel(DiffTreeModel treeModel, String fileName, String filePath) { super(fileName, filePath); this.treeModel = treeModel; } public DiffTreeModel getTreeModel() { return treeModel; } public DiffFileTreeNode getSelectedNode() { return selectedNode; } void setSelectedNode(DiffFileTreeNode selectedNode) { this.selectedNode = selectedNode; } }
import convert.ConvertBase; import convert.impl.ConvertBaseImpl; /** * Main class. */ public final class Main { private Main() { } /** * Main point for start programm. * * @param args arguments for programm. */ public static void main(final String[] args) { ConvertBase convertBase = new ConvertBaseImpl(); convertBase.start(); } }
package com.crmiguez.aixinainventory.repository; import com.crmiguez.aixinainventory.entities.Brand; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository("brandRepository") public interface BrandRepository extends CrudRepository<Brand, String> { Brand findByBrandId(String brandId); }
package com.github.binarywang.wxpay.testbase; import com.github.binarywang.wxpay.config.WxPayConfig; import com.thoughtworks.xstream.annotations.XStreamAlias; @XStreamAlias("xml") public class XmlWxPayConfig extends WxPayConfig { private String openid; public String getOpenid() { return openid; } public void setOpenid(String openid) { this.openid = openid; } @Override public boolean isUseSandboxEnv() { //沙箱环境不成熟,有问题无法使用,暂时屏蔽掉 //return true; return false; } }
package com.hdy.myhxc.mapper; import com.hdy.myhxc.model.Role; import com.hdy.myhxc.model.RoleExample; import java.util.List; import org.apache.ibatis.annotations.*; import org.apache.ibatis.type.JdbcType; import org.springframework.stereotype.Repository; @Mapper @Repository public interface RoleMapper { /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_role * * @mbg.generated Mon Aug 26 14:48:07 CST 2019 */ @SelectProvider(type=RoleSqlProvider.class, method="countByExample") long countByExample(RoleExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_role * * @mbg.generated Mon Aug 26 14:48:07 CST 2019 */ @DeleteProvider(type=RoleSqlProvider.class, method="deleteByExample") int deleteByExample(RoleExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_role * * @mbg.generated Mon Aug 26 14:48:07 CST 2019 */ @Delete({ "delete from m_role", "where UUID = #{uuid,jdbcType=VARCHAR}" }) int deleteByPrimaryKey(String uuid); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_role * * @mbg.generated Mon Aug 26 14:48:07 CST 2019 */ @Insert({ "insert into m_role (UUID, Role_Name, ", "Create_User, Create_Date, ", "Update_User, Update_Date, ", "DelFg, Beizhu)", "values (#{uuid,jdbcType=VARCHAR}, #{roleName,jdbcType=VARCHAR}, ", "#{createUser,jdbcType=VARCHAR}, #{createDate,jdbcType=TIMESTAMP}, ", "#{updateUser,jdbcType=VARCHAR}, #{updateDate,jdbcType=TIMESTAMP}, ", "#{delfg,jdbcType=VARCHAR}, #{beizhu,jdbcType=VARCHAR})" }) int insert(Role record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_role * * @mbg.generated Mon Aug 26 14:48:07 CST 2019 */ @InsertProvider(type=RoleSqlProvider.class, method="insertSelective") int insertSelective(Role record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_role * * @mbg.generated Mon Aug 26 14:48:07 CST 2019 */ @SelectProvider(type=RoleSqlProvider.class, method="selectByExample") @Results({ @Result(column="UUID", property="uuid", jdbcType=JdbcType.VARCHAR, id=true), @Result(column="Role_Name", property="roleName", jdbcType=JdbcType.VARCHAR), @Result(column="Create_User", property="createUser", jdbcType=JdbcType.VARCHAR), @Result(column="Create_Date", property="createDate", jdbcType=JdbcType.TIMESTAMP), @Result(column="Update_User", property="updateUser", jdbcType=JdbcType.VARCHAR), @Result(column="Update_Date", property="updateDate", jdbcType=JdbcType.TIMESTAMP), @Result(column="DelFg", property="delfg", jdbcType=JdbcType.VARCHAR), @Result(column="Beizhu", property="beizhu", jdbcType=JdbcType.VARCHAR) }) List<Role> selectByExample(RoleExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_role * * @mbg.generated Mon Aug 26 14:48:07 CST 2019 */ @Select({ "select", "UUID, Role_Name, Create_User, Create_Date, Update_User, Update_Date, DelFg, ", "Beizhu", "from m_role", "where UUID = #{uuid,jdbcType=VARCHAR}" }) @Results({ @Result(column="UUID", property="uuid", jdbcType=JdbcType.VARCHAR, id=true), @Result(column="Role_Name", property="roleName", jdbcType=JdbcType.VARCHAR), @Result(column="Create_User", property="createUser", jdbcType=JdbcType.VARCHAR), @Result(column="Create_Date", property="createDate", jdbcType=JdbcType.TIMESTAMP), @Result(column="Update_User", property="updateUser", jdbcType=JdbcType.VARCHAR), @Result(column="Update_Date", property="updateDate", jdbcType=JdbcType.TIMESTAMP), @Result(column="DelFg", property="delfg", jdbcType=JdbcType.VARCHAR), @Result(column="Beizhu", property="beizhu", jdbcType=JdbcType.VARCHAR) }) Role selectByPrimaryKey(String uuid); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_role * * @mbg.generated Mon Aug 26 14:48:07 CST 2019 */ @UpdateProvider(type=RoleSqlProvider.class, method="updateByExampleSelective") int updateByExampleSelective(@Param("record") Role record, @Param("example") RoleExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_role * * @mbg.generated Mon Aug 26 14:48:07 CST 2019 */ @UpdateProvider(type=RoleSqlProvider.class, method="updateByExample") int updateByExample(@Param("record") Role record, @Param("example") RoleExample example); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_role * * @mbg.generated Mon Aug 26 14:48:07 CST 2019 */ @UpdateProvider(type=RoleSqlProvider.class, method="updateByPrimaryKeySelective") int updateByPrimaryKeySelective(Role record); /** * This method was generated by MyBatis Generator. * This method corresponds to the database table m_role * * @mbg.generated Mon Aug 26 14:48:07 CST 2019 */ @Update({ "update m_role", "set Role_Name = #{roleName,jdbcType=VARCHAR},", "Create_User = #{createUser,jdbcType=VARCHAR},", "Create_Date = #{createDate,jdbcType=TIMESTAMP},", "Update_User = #{updateUser,jdbcType=VARCHAR},", "Update_Date = #{updateDate,jdbcType=TIMESTAMP},", "DelFg = #{delfg,jdbcType=VARCHAR},", "Beizhu = #{beizhu,jdbcType=VARCHAR}", "where UUID = #{uuid,jdbcType=VARCHAR}" }) int updateByPrimaryKey(Role record); }
import java.util.*; /** * Write a description of class Test here. * * @colinbowen * @0.1 */ public class Test { private Card playingCard; /** * Constructor for objects of class Test */ public Test() { } public void createCards() { playingCard = new Card(Suit.HEARTS, Value.SIX); } public void printCards() { for(;;) { } } }
package com.example.choonhee.hack2hired_21.activity.book; import java.io.Serializable; /** * Created by calvinlow on 22/04/2017. */ public class Book implements Serializable { private String name; private String ISBN; private String desc; private String author; private String imageUrl; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getISBN() { return ISBN; } public void setISBN(String ISBN) { this.ISBN = ISBN; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } @Override public String toString() { return "Book{" + "name='" + name + '\'' + ", ISBN='" + ISBN + '\'' + ", desc='" + desc + '\'' + ", author='" + author + '\'' + ", imageUrl='" + imageUrl + '\'' + '}'; } }
package com.hznu.fa2login.modules.sys.service; import com.baomidou.mybatisplus.service.IService; import com.hznu.fa2login.modules.sys.entity.Ccode; /** * @Author: TateBrown * @date: 2018/11/28 19:28 * @param: * @return: */ public interface CcodeService extends IService<Ccode> { }
package com.mc.library.base; import android.support.v4.app.Fragment; /** * Created by dinghui on 2016/11/4. * Fragment基类 */ public class BaseFragment extends Fragment { }
package Graphs; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; class UndirectedGraphNode { int label; List<UndirectedGraphNode> neighbors; UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); } }; public class CloneGraph { public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) { if(node==null) return null; boolean [] visited = new boolean[10]; for(int i = 0; i < 10;i++){ visited[i] = false; } UndirectedGraphNode root= cloneGraphUtil( node,visited); return root; } public UndirectedGraphNode cloneGraphUtil(UndirectedGraphNode v, boolean [] visited){ visited[v.label] = true; UndirectedGraphNode root = new UndirectedGraphNode(v.label); Iterator<UndirectedGraphNode> itr = v.neighbors.listIterator(); while(itr.hasNext()){ UndirectedGraphNode n = itr.next(); if(!visited[n.label]){ visited[n.label] = true; root.neighbors.add(cloneGraphUtil(n, visited)); } } return root; } public void BFS(UndirectedGraphNode v){ if(v==null) return ; boolean [] visited = new boolean[10]; LinkedList<UndirectedGraphNode> queue = new LinkedList<UndirectedGraphNode>(); visited[v.label] = true; queue.add(v); while(!queue.isEmpty()){ UndirectedGraphNode n = queue.poll(); System.out.print(n.label + " "); Iterator<UndirectedGraphNode> itr = n.neighbors.listIterator(); while(itr.hasNext()){ UndirectedGraphNode m = itr.next(); if(!visited[m.label]){ visited[m.label] = true; queue.add(m); } } } } public static void main(String[] args) { // TODO Auto-generated method stub UndirectedGraphNode node1 = new UndirectedGraphNode(1); UndirectedGraphNode node2 = new UndirectedGraphNode(2); UndirectedGraphNode node3 = new UndirectedGraphNode(3); UndirectedGraphNode node4 = new UndirectedGraphNode(4); node1.neighbors.add(node2); node1.neighbors.add(node4); node2.neighbors.add(node1); node2.neighbors.add(node3); node3.neighbors.add(node2); node3.neighbors.add(node4); node4.neighbors.add(node1); node4.neighbors.add(node3); CloneGraph cg = new CloneGraph(); System.out.println("Original graph"); cg.BFS(node1); System.out.println(); UndirectedGraphNode result = cg.cloneGraph(node1); System.out.println("Cloned graph"); cg.BFS(result); } }
package com.pichincha.prueba.exceptions; import java.util.Locale; import com.pichincha.prueba.util.MensajesUtil; import com.sun.istack.NotNull; public class BOException extends Exception { private static final long serialVersionUID = 1L; private static final Locale localeDefault = new Locale("es", "EC"); private String codeMessage; private Object[] messageParametersValues; private Object data; public BOException() { super(); } public BOException(String codeMessage, Throwable cause) { super(MensajesUtil.getMensaje(codeMessage, localeDefault), cause); this.codeMessage = codeMessage; } public BOException(String codeMessage) { super(MensajesUtil.getMensaje(codeMessage, localeDefault)); this.codeMessage = codeMessage; } public BOException(Throwable cause) { super(cause); } public BOException(String codeMessage, @NotNull Object data) { super(MensajesUtil.getMensaje(codeMessage, localeDefault)); this.codeMessage = codeMessage; this.data = data; } public BOException(String codeMessage, @NotNull Object[] messageParametersValues, Throwable cause) { super(MensajesUtil.getMensaje(codeMessage, messageParametersValues, localeDefault), cause); this.codeMessage = codeMessage; this.messageParametersValues = messageParametersValues; } public BOException(String codeMessage, @NotNull Object[] messageParametersValues) { super(MensajesUtil.getMensaje(codeMessage, messageParametersValues, localeDefault)); this.codeMessage = codeMessage; this.messageParametersValues = messageParametersValues; } public BOException(String codeMessage, @NotNull Object[] messageParametersValues, @NotNull Object data) { super(MensajesUtil.getMensaje(codeMessage, messageParametersValues, localeDefault)); this.codeMessage = codeMessage; this.messageParametersValues = messageParametersValues; this.data = data; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } public String getTranslatedMessage(String strLanguage) { Locale locale = MensajesUtil.validateSupportedLocale(strLanguage); return getTranslatedMessage(locale); } public String getTranslatedMessage(Locale locale) { if (localeDefault.equals(locale)) { return super.getMessage(); } else { if (messageParametersValues != null && messageParametersValues.length > 0) return MensajesUtil.getMensaje(codeMessage, messageParametersValues, locale); else return MensajesUtil.getMensaje(codeMessage, locale); } } public String getCodeMessage() { return codeMessage; } public Object[] getMessageParametersValues() { return messageParametersValues; } }
/****************************************************************************** * __ * * <-----/@@\-----> * * <-< < \\// > >-> * * <-<-\ __ /->-> * * 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.reporting.transformers; import java.io.BufferedOutputStream; import java.io.File; import java.io.IOException; import java.util.List; import net.datacrow.core.migration.itemexport.IItemExporterClient; import net.datacrow.core.migration.itemexport.ItemExporter; import net.datacrow.core.migration.itemexport.ItemExporterSettings; import net.datacrow.core.migration.itemexport.ItemExporters; import net.datacrow.core.modules.DcModules; import net.datacrow.core.resources.DcResources; import net.datacrow.reporting.templates.ReportTemplate; import org.apache.log4j.Logger; public abstract class XmlTransformer { private static Logger logger = Logger.getLogger(XmlTransformer.class.getName()); protected File source; protected File target; protected File template; protected List<String> items; protected IItemExporterClient client; protected BufferedOutputStream bos; private Transformer rt; private ItemExporterSettings settings; private ItemExporter exporter; protected boolean canceled = false; public XmlTransformer() {} public void transform(IItemExporterClient client, List<String> items, File target, ReportTemplate reportFile) { this.client = client; this.items = items; this.target = target; this.template = new File(reportFile.getFilename()); this.settings = reportFile.getProperties(); setSettings(settings); String s = target.toString(); s = s.substring(0, s.lastIndexOf(".")) + ".xml"; this.source = new File(s); if (rt != null) rt.cancel(); rt = new Transformer(); rt.start(); } public void cancel() { canceled = true; if (exporter != null) exporter.cancel(); if (rt != null) rt.cancel(); } public abstract int getType(); public abstract void transform() throws Exception ; public abstract String getFileType(); protected void setSettings(ItemExporterSettings properties) { properties.set(ItemExporterSettings._ALLOWRELATIVEIMAGEPATHS, Boolean.TRUE); } private class Transformer extends Thread { private ItemExporter exporter; public void cancel() { if (exporter != null) exporter.cancel(); } @Override public void run() { try { canceled = false; // export the items to an XML file exporter = ItemExporters.getInstance().getExporter("XML", DcModules.getCurrent().getIndex(), ItemExporter._MODE_NON_THREADED); exporter.setSettings(settings); exporter.setFile(source); exporter.setClient(client); exporter.setItems(items); exporter.start(); // create the report if (exporter.isSuccessfull() && !canceled) { client.notifyStarted(0); client.notifyMessage(DcResources.getText("msgTransformingOutput", getFileType())); transform(); client.notifyMessage(DcResources.getText("msgTransformationSuccessful", target.toString())); } } catch (Exception exp) { logger.error(DcResources.getText("msgErrorWhileCreatingReport", exp.toString()), exp); client.notifyMessage(DcResources.getText("msgErrorWhileCreatingReport", exp.toString())); } finally { if (client != null) client.notifyStopped(); try { source.delete(); String name = source.getName(); name = name.lastIndexOf(".") > -1 ? name.substring(0, name.lastIndexOf(".")) : name; new File(source.getParent(), name).delete(); new File(source.getParent(), name + ".xsd").delete(); } catch (Exception ignore) { logger.debug("Could not cleanup reporting files.", ignore); } source = null; template = null; items = null; target = null; client = null; settings = null; exporter = null; try { if (bos != null) bos.close(); } catch (IOException ignore) {} bos = null; } } } }
package com.java.practice.google; /** * https://leetcode.com/problems/circular-array-loop/ */ public class ArrayLoop { public static void main(String[] args) { int[] nums = {-2, 1, -1, -2, -2}; System.out.println(isCycle(nums)); } public static boolean isCycle(int[] nums) { if (nums.length <= 1) return false; for (int i = 0; i < nums.length; i++) { int slow = i; int fast = i; boolean isForward = nums[i] > 0; while (true) { slow = getNextIndex(nums, slow, isForward); if (slow == -1) break; fast = getNextIndex(nums, fast, isForward); if (fast == -1) break; fast = getNextIndex(nums, fast, isForward); if (fast == -1) break; if (slow == fast) return true; } } return false; } private static int getNextIndex(int[] nums, int index, boolean isForward) { boolean direction = nums[index] > 0; if (direction != isForward) return -1; int nextIndex = (index + nums[index]) % nums.length; if (nextIndex < 0) nextIndex += nums.length; if (nextIndex == index) return -1; return nextIndex; } }
/* * LcmsLesson.java 1.00 2011-10-11 * * Copyright (c) 2011 ???? Co. All Rights Reserved. * * This software is the confidential and proprietary information * of um2m. You shall not disclose such Confidential Information * and shall use it only in accordance with the terms of the license agreement * you entered into with um2m. */ package egovframework.adm.lcms.nct.domain; /** * <pre> * system : * menu : * source : LcmsLesson.java * description : * </pre> * @version * <pre> * 1.0 2011-10-11 created by ? * 1.1 * </pre> */ public class LcmsLesson { private String crsCode = ""; private String module = ""; private String lesson = ""; private String lessonName = ""; private String starting = ""; private long eduTime = 0; private String eduTimeYn = ""; private long pageCount = 0; private String inuserid = ""; private String indate = ""; private String luserid = ""; private String ldate = ""; private int lessonCnt = 0; public String getCrsCode() { return crsCode; } public String getModule() { return module; } public String getLesson() { return lesson; } public String getLessonName() { return lessonName; } public String getStarting() { return starting; } public long getEduTime() { return eduTime; } public String getEduTimeYn() { return eduTimeYn; } public long getPageCount() { return pageCount; } public String getInuserid() { return inuserid; } public String getIndate() { return indate; } public String getLuserid() { return luserid; } public String getLdate() { return ldate; } public void setCrsCode( String crsCode) { this.crsCode = crsCode; } public void setModule( String module) { this.module = module; } public void setLesson( String lesson) { this.lesson = lesson; } public void setLessonName( String lessonName) { this.lessonName = lessonName; } public void setStarting( String starting) { this.starting = starting; } public void setEduTime( long eduTime) { this.eduTime = eduTime; } public void setEduTimeYn( String eduTimeYn) { this.eduTimeYn = eduTimeYn; } public void setPageCount( long pageCount) { this.pageCount = pageCount; } public void setInuserid( String inuserid) { this.inuserid = inuserid; } public void setIndate( String indate) { this.indate = indate; } public void setLuserid( String luserid) { this.luserid = luserid; } public void setLdate( String ldate) { this.ldate = ldate; } public int getLessonCnt() { return lessonCnt; } public void setLessonCnt(int lessonCnt) { this.lessonCnt = lessonCnt; } }
package com.example.pagination_task.Fragments; import android.content.Context; import android.databinding.DataBindingUtil; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.support.v7.widget.DefaultItemAnimator; import android.support.v7.widget.LinearLayoutManager; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.example.pagination_task.Adapter.MovieAdapter; import com.example.pagination_task.EndlessRecyclerOnScrollListener; import com.example.pagination_task.MainActivity; import com.example.pagination_task.R; import com.example.pagination_task.Result; import com.example.pagination_task.RetrofitApi; import com.example.pagination_task.RetrofitIns; import com.example.pagination_task.TopRatedMovies; import com.example.pagination_task.databinding.FragmentMovieListBinding; import java.util.List; import java.util.Objects; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class Movie_List_Fragment extends Fragment implements MovieAdapter.RecyclerViewClickListener { public static final String TAG = "Movie_List_Fragment"; FragmentMovieListBinding binding; private List<Result> list; EndlessRecyclerOnScrollListener endlessRecyclerOnScrollListener; OnMovieListListener mListener; private boolean isRequest = true; MovieAdapter adapter; RetrofitApi retrofitApi; public Movie_List_Fragment() { // Required empty public constructor } public static Movie_List_Fragment newInstance() { Movie_List_Fragment fragment = new Movie_List_Fragment(); Bundle args = new Bundle(); fragment.setArguments(args); return fragment; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); if (savedInstanceState != null) { mListener = (MainActivity) getActivity(); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { binding = DataBindingUtil.inflate(inflater, R.layout.fragment_movie__list_, container, false); MainActivity activity = (MainActivity) getActivity(); Objects.requireNonNull(activity).setSupportActionBar(binding.toolbar); ; initRecyclerView(); return binding.getRoot(); } private void initRecyclerView() { LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity()); retrofitApi = RetrofitIns.getRetrofit().create(RetrofitApi.class); endlessRecyclerOnScrollListener = new EndlessRecyclerOnScrollListener(linearLayoutManager) { @Override public void onLoadMore(int currentPage) { if (isRequest) { list.add(null); adapter.notifyItemInserted(list.size() - 1); sendReq(currentPage); isRequest = false; } } }; binding.recyclerView.addOnScrollListener(endlessRecyclerOnScrollListener); sendReq(1); binding.recyclerView.setLayoutManager(linearLayoutManager); binding.recyclerView.setHasFixedSize(true); binding.recyclerView.setItemAnimator(new DefaultItemAnimator()); } private void sendReq(int currentPage) { loadNextPage(currentPage); } private void removeItemProgress() { if (adapter != null) { isRequest = true; list.remove(list.size() - 1); adapter.notifyItemRemoved(list.size() - 1); } } private void loadNextPage(int currentPage) { callTopRatedMovies(currentPage).enqueue(new Callback<TopRatedMovies>() { @Override public void onResponse(@NonNull Call<TopRatedMovies> call, @NonNull Response<TopRatedMovies> response) { removeItemProgress(); binding.movieProgressBar.setVisibility(View.GONE); if (adapter == null) { list = Objects.requireNonNull(response.body()).getResults(); if (list != null && list.size() > 0) { adapter = new MovieAdapter(list, getActivity(), Movie_List_Fragment.this); binding.recyclerView.setAdapter(adapter); } } else { if (list != null && list.size() != 0 && binding.recyclerView.getAdapter() != null) { list.addAll(Objects.requireNonNull(response.body()).getResults()); Log.d(TAG, "onResponsdddddde: " + list); adapter.notifyItemInserted(adapter.getItemCount() - 1); } else { adapter.notifyDataSetChanged(); } } } @Override public void onFailure(@NonNull Call<TopRatedMovies> call, @NonNull Throwable t) { removeItemProgress(); binding.movieProgressBar.setVisibility(View.GONE); Log.d(TAG, "onFailure: " + t.getMessage()); } }); } private Call<TopRatedMovies> callTopRatedMovies(int currentPage) { return retrofitApi.getTopRatedMovies(getString(R.string.my_api_key), "en_US", currentPage); } @Override public void onAttach(Context context) { super.onAttach(context); if (context instanceof OnMovieListListener) { mListener = (OnMovieListListener) context; } else { throw new RuntimeException(context.toString() + " must implement OnMovieListListener"); } } @Override public void onDetach() { super.onDetach(); mListener = null; } @Override public void onRecyclerItemClicked(View v, int position) { Result result = list.get(position); mListener.onMovieItemClicked(result); Log.d(TAG, "onRecyclerItemClicked: " + result.getTitle()); } public interface OnMovieListListener { void onMovieItemClicked(Result result); } }
package com.ai.platform.agent.web.util; public class ResultCodeConstants { public static final String OK = "0"; public static final String OK_MSG = "操作成功"; public static final String FAIL = "1"; public static final String FAIL_MSG = "操作失败"; public static final String DOING = "2"; public static final String DOING_MSG = "操作进行中"; }
package org.test.ht; import java.math.BigDecimal; public class RoundKSqrt { public String roundKSqrt(double x, int k) { String current = ""; for (int i = 0; i <= k; i++) { int low, high; if (i == 0) { low = 0; high = (int) x; } else { low = 0; high = 9; } String tmp; while (low < high - 1) { int middle = low + (high - low) / 2; tmp = current + middle; if (Double.valueOf(tmp) * Double.valueOf(tmp) < x) { low = middle; } else if (Double.valueOf(tmp) * Double.valueOf(tmp) == x){ return tmp; } else { high = middle; } } tmp = current + high; if (Double.valueOf(tmp) * Double.valueOf(tmp) == x) { return tmp; } current += low; if (i==0) { current += "."; } } return current; } public static void main(String args[]) { RoundKSqrt roundKSqrt = new RoundKSqrt(); System.out.println(roundKSqrt.roundKSqrt(0.0081, 4)); } }
package com.testyantra.empspringmvc.jaxb.beans; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.Table; @SuppressWarnings("serial") @Entity @Table(name = "EMPLOYEE_ADDRESSINFO") public class EmployeeAddressInfoBean implements Serializable { @EmbeddedId protected EmployeeAddressPKBean addressPKBean; @Column(name = "ADDRESS1") protected String address1; @Column(name = "ADDRESS2") protected String address2; @Column(name = "LANDMARK") protected String landmark; @Column(name = "CITY") protected String city; @Column(name = "STATE") protected String state; @Column(name = "COUNTRY") protected String country; @Column(name = "PINCODE") protected int pincode; public EmployeeAddressPKBean getAddressPKBean() { return addressPKBean; } public void setAddressPKBean(EmployeeAddressPKBean value) { this.addressPKBean = value; } public String getAddress1() { return address1; } public void setAddress1(String value) { this.address1 = value; } public String getAddress2() { return address2; } public void setAddress2(String value) { this.address2 = value; } public String getLandmark() { return landmark; } public void setLandmark(String value) { this.landmark = value; } public String getCity() { return city; } public void setCity(String value) { this.city = value; } public String getState() { return state; } public void setState(String value) { this.state = value; } public String getCountry() { return country; } public void setCountry(String value) { this.country = value; } public int getPincode() { return pincode; } public void setPincode(int value) { this.pincode = value; } }
package com.karya.service; import java.util.List; import com.karya.model.MaterialReqnotCreate001MB; import com.karya.model.PuItemHistory001MB; import com.karya.model.ReqItemOrdBuy001MB; import com.karya.model.RequestedItemBuy001MB; public interface IBuyingReportsService { public void addmatreqnotcreate(MaterialReqnotCreate001MB materialreqnotcreate001MB); public List<MaterialReqnotCreate001MB> listmatreqnotcreate(); public MaterialReqnotCreate001MB getmatreqnotcreate(int mrsId); public void deletematreqnotcreate(int mrsId); //reqitem order buy public void addreqitemordbuy(ReqItemOrdBuy001MB reqitemordbuy001MB); public List<ReqItemOrdBuy001MB> listreqitemordbuy(); public ReqItemOrdBuy001MB getreqitemordbuy(int mrsId); public void deletereqitemordbuy(int mrsId); //req item buy public void addreqitembuy(RequestedItemBuy001MB requseteditembuy001MB); public List<RequestedItemBuy001MB> listreqitembuy(); public RequestedItemBuy001MB getreqitembuy(int riId); public void deletereqitembuy(int riId); //PuItem History public void addpuitemhistory(PuItemHistory001MB puitemhistory001MB); public List<PuItemHistory001MB> listpuitemhistory(); public PuItemHistory001MB getpuitemhistory(int histId); public void deletepuitemhistory(int histId); }
package com.example.randomlocks.listup.Adapter; import android.content.Context; import android.graphics.Paint; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CompoundButton; import com.example.randomlocks.listup.R; import java.util.List; /** * Created by randomlocks on 5/5/2016. */ public class CheckboxRecyclerAdapter extends RecyclerView.Adapter<CheckboxRecyclerAdapter.MyViewHolder> { List<String> checkList; List<Boolean> isCheckedList; Context context; public CheckboxRecyclerAdapter(List<String> checkList,List<Boolean> isCheckedList ,Context context){ this.checkList = checkList; this.isCheckedList = isCheckedList; this.context = context; } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.recycler_checkbox_layout,parent,false); return new MyViewHolder(v); } @Override public void onBindViewHolder(MyViewHolder holder, final int position) { String str = checkList.get(position); holder.checkBox.setText(checkList.get(position)); holder.checkBox.setChecked(isCheckedList.get(position)); holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if(isChecked){ isCheckedList.set(position,true); buttonView.setPaintFlags(buttonView.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG); }else { isCheckedList.set(position,false); buttonView.setPaintFlags(0); } } }); } @Override public int getItemCount() { return checkList.size(); } public class MyViewHolder extends RecyclerView.ViewHolder { CheckBox checkBox; public MyViewHolder(View itemView) { super(itemView); checkBox = (CheckBox) itemView.findViewById(R.id.checked_item); } } }
package org.celllife.stock.test; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.ImportResource; import org.springframework.test.context.transaction.TransactionConfiguration; @Configuration @ImportResource({ "classpath:/META-INF/spring/spring-application.xml", "classpath:/META-INF/spring/spring-cache.xml", "classpath:/META-INF/spring/spring-config.xml", "classpath:/META-INF/spring/spring-domain.xml", "classpath:/META-INF/spring/spring-integration-communicate.xml", "classpath:/META-INF/spring/spring-jdbc.xml", "classpath:/META-INF/spring/spring-mail.xml", "classpath:/META-INF/spring/spring-message.xml", "classpath:/META-INF/spring/spring-orm.xml", "classpath:/META-INF/spring/spring-tx.xml", "classpath:/META-INF/spring-data/spring-data-jpa.xml", "classpath:/META-INF/spring-integration/spring-integration-core.xml" }) @TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true) public class TestConfiguration { }
import java.util.Scanner; public class Q1 { public static void main(String[] args) { //create Scanner object Scanner input = new Scanner(System.in); //input the numbers System.out.println("Enter a, b, and c for the quadratic equation."); double aInput = input.nextDouble(); double bInput = input.nextDouble(); double cInput = input.nextDouble(); //discriminant double theDiscriminant = bInput * bInput - (4 * aInput * cInput); theDiscriminant = Math.sqrt(theDiscriminant); //roots double root1 = bInput * -1; double root2 = root1; //conditional if (theDiscriminant == 0) { root1 /= (2 * aInput); System.out.println("The root is " + root1); } else if (theDiscriminant > 0) { root1 += theDiscriminant; root1 /= (2 * aInput); System.out.println("One root is " + root1); root2 -= theDiscriminant; root2 /= (2 * aInput); System.out.println("The other root is " + root2); } else { System.out.println("There is no real root."); } } }
/****************************************************************************** * Copyright (c) 2012 GitHub Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Kevin Sawicki (GitHub Inc.) - initial API and implementation *****************************************************************************/ package com.github.mobile.tests.gist; import android.net.Uri; import android.test.AndroidTestCase; import com.github.mobile.core.gist.GistUriMatcher; import org.eclipse.egit.github.core.Gist; /** * Unit tests of {@link GistUriMatcher} */ public class GistUriMatcherTest extends AndroidTestCase { /** * Verify empty uri */ public void testEmptyUri() { assertNull(GistUriMatcher.getGist(Uri.parse(""))); } /** * Verify invalid Gist ids in URIs */ public void testNonGistId() { assertNull(GistUriMatcher.getGist(Uri .parse("https://gist.github.com/TEST"))); assertNull(GistUriMatcher.getGist(Uri .parse("https://gist.github.com/abc%20"))); assertNull(GistUriMatcher.getGist(Uri .parse("https://gist.github.com/abcdefg"))); } /** * Verify public Gist id */ public void testPublicGist() { Gist gist = GistUriMatcher.getGist(Uri .parse("https://gist.github.com/1234")); assertNotNull(gist); assertEquals("1234", gist.getId()); } /** * Verify public Gist id */ public void testPrivateGist() { Gist gist = GistUriMatcher.getGist(Uri .parse("https://gist.github.com/abcd1234abcd1234abcd")); assertNotNull(gist); assertEquals("abcd1234abcd1234abcd", gist.getId()); } }
package algorithms; import graph.*; import log.*; import java.util.*; import java.io.*; public class DepthFirstSearch { /** * */ private ArrayList<Vertex> vertexList; /** * */ private int orderIndex = 0; /** * */ private Stack<Vertex> stack; /** * */ private WriteLogFile log; /** * */ protected PrintWriter pw; /** * */ protected StringBuilder sb = new StringBuilder(); /** * [DFS description] * @param graph [description] * @return [description] * @throws IOException [description] */ public DepthFirstSearch (Graph graph) throws IOException { log = new WriteLogFile("output/" + graph.getId() + "/log_dfs.txt"); //graph.sortVertexByDegree(); vertexList = graph.getVertexList(); stack = new Stack<Vertex>(); pw = new PrintWriter(new File("output/" + graph.getId() + "/id_order.csv")); } /** * [getFirstNonVisitedVertex description] * @return [description] */ public Vertex getFirstNonVisitedVertex () { for (int i = 0; i < vertexList.size(); i++) if (!vertexList.get(i).isVisited()) return vertexList.get(i); return vertexList.get(0); } /** * [haveNonVisitedVertexes description] * @return [description] */ public boolean haveNonVisitedVertexes () { log.write("Check", "if the graph contains a non visited vertex", ""); for (int i = 0; i < vertexList.size(); i++) if (!vertexList.get(i).isVisited()) { log.writeln("Yes. Vertex " + (vertexList.get(i).getId()+1)); return true; } log.writeln("No"); return false; } /** * [setVisited description] * @param vertex [description] */ public void setVisited (Vertex vertex) { vertex.setVisited(); log.writef("Set","as visited vertex", Integer.toString(vertex.getId()+1)); setOrder(vertex); } /** * [getVisited description] * @param vertex [description] * @return [description] */ public boolean getVisited (Vertex vertex) { log.write("Check", "if has already visited vertex", Integer.toString(vertex.getId()+1)); if (vertex.isVisited()) { log.writeln("Yes"); return true; } else { log.writeln("No"); return false; } } /** * [setOrder description] * @param vertex [description] */ private void setOrder (Vertex vertex) { vertex.setOrder(++orderIndex); System.out.println((vertex.getId()+1) + " [" + orderIndex + "]"); log.writef("Set", "in " + orderIndex + " the order of vertex ", Integer.toString(vertex.getId()+1)); addToStack(vertex); } /** * [addToStack description] * @param vertex [description] */ private void addToStack (Vertex vertex) { stack.add(vertex); log.writef("Add","to the stack vertex", Integer.toString(vertex.getId()+1)); } /** * @return */ public Stack<Vertex> getStack () { return stack; } /** * [getTopStack description] * @return [description] */ public Vertex getTopStack () { Vertex vertex = stack.pop(); log.writef("Remove","from the stack vertex", Integer.toString(vertex.getId()+1)); return vertex; } /** * [getAllSucessors description] * @param vertex [description] * @return [description] */ public Iterator<Integer> getAllSucessors (Vertex vertex) { log.write("Get","the sucessors of vertex", Integer.toString(vertex.getId()+1)); ArrayList<Integer> temp1 = vertex.getSucessorList(); if (!(temp1.size() > 0)) log.write("Without sucessors"); else for (int i = 0; i < temp1.size(); i++) log.write(Integer.toString(vertexList.get(temp1.get(i)).getId()+1)); log.writeln(); return vertex.getSucessorList().listIterator(); } /** * [getNextSucessor description] * @param neighbors [description] * @return [description] */ public Vertex getNextSucessor (Iterator<Integer> neighbors) { Vertex n = vertexList.get(neighbors.next()); log.writef("Analyze", "vertex", Integer.toString(n.getId()+1)); return n; } /** * [haveNonVisitedPredecessors description] * @param vertex [description] * @return [description] */ public boolean haveNonVisitedPredecessors (Vertex vertex) { log.write("Get", "the predecessors of vertex", Integer.toString(vertex.getId()+1)); if (!(vertex.getPredecessorList().size() > 0)) log.write("Without predecessors"); else for (int i = 0; i < vertex.getPredecessorList().size(); i++) log.write(Integer.toString(vertexList.get(vertex.getPredecessorList().get(i)).getId()+1)); log.writeln(); for (int i = 0; i < vertex.getPredecessorList().size(); i++) { log.write("Check", "that vertex " + (vertexList.get(vertex.getPredecessorList().get(i)).getId()+1) + " is a non visited predecessor of vertex", Integer.toString(vertex.getId()+1)); if (!vertexList.get(vertex.getPredecessorList().get(i)).isVisited()) { log.writeln("Yes"); return true; } else log.writeln("No"); } return false; } public void finish () { sb.append("id,Order\n"); for (int p = 0; p < vertexList.size(); p++) sb.append((vertexList.get(p).getId()+1) + "," + (vertexList.get(p).getOrder()) + "\n"); pw.write(sb.toString()); pw.close(); log.close(); } }
package sign.com.common; import java.util.HashMap; import java.util.List; import java.util.Map; /** * 分页对象 * @author lulin * */ public class PageDto { private Integer pageSize = 10; // 每页条数 private Integer pageIndex = 1; // 第几页 private Long fullListSize; // 总记录数 Map<String,Object> params = new HashMap<String,Object>(); // 采集条件 private List list; // 结果集容器 private Integer startRowNum; public Integer getPageSize() { return pageSize; } public void setPageSize(Integer pageSize) { this.pageSize = pageSize; } public Integer getPageIndex() { return pageIndex; } public void setPageIndex(Integer pageIndex) { this.pageIndex = pageIndex; } public Long getFullListSize() { return fullListSize; } public void setFullListSize(Long fullListSize) { this.fullListSize = fullListSize; } public Map<String, Object> getParams() { return params; } public void paramsClear() { params = null; } public void putParam(String key,Object value) { this.params.put(key, value); } public List getList() { return list; } public void setList(List list) { this.list = list; } public void initStartRowNum() { if(pageIndex == 1){ startRowNum = 0; }else{ startRowNum = (pageIndex - 1) * pageSize; } params.put("pageSize", pageSize); params.put("startRowNum", startRowNum); } }
package com.pdd.pop.sdk.http.api.response; import com.pdd.pop.ext.fasterxml.jackson.annotation.JsonProperty; import com.pdd.pop.sdk.http.PopBaseHttpResponse; public class PddLogisticsOnlineSendResponse extends PopBaseHttpResponse{ /** * 发货通知响应对象 */ @JsonProperty("logistics_online_send_response") private LogisticsOnlineSendResponse logisticsOnlineSendResponse; public LogisticsOnlineSendResponse getLogisticsOnlineSendResponse() { return logisticsOnlineSendResponse; } public static class LogisticsOnlineSendResponse { /** * 是否成功,false-失败,true-成功 */ @JsonProperty("is_success") private Boolean isSuccess; public Boolean getIsSuccess() { return isSuccess; } } }
package cn.math.fibonacciSequence; import com.alibaba.fastjson.JSON; import lombok.extern.slf4j.Slf4j; /** * Created by xiaoni on 2019/8/17. * 斐波那契数列 * <p> * 又称黄金分割数列、因数学家列昂纳多·斐波那契(Leonardoda Fibonacci)以兔子繁殖为例子而引入,故又称为“兔子数列” */ @Slf4j public class FibonacciSequence { /** * 递归法求第n项 * * @param n * @return */ public static int f(int n) { if (n == 0) { return 0; } if (n == 1) { return 1; } if (n >= 2) { int c = f(n - 1) + f(n - 2); return c; } return -1; } /** * 输出n项 * * @param n * @return */ public static int[] fFor(int n) { int a = 0; int b = 1; int c = 1; int[] result =new int[n]; result[0] = a; result[1] = b; result[2] = c; for (int i = 3; i < n; i++) { a = b; b = c; c = a + b; result[i] = c; } log.info(JSON.toJSONString(result)); return result; } public static void main(String[] args) { for (int i = 0; i < 40; i++) { log.info("a{} = {}", i, FibonacciSequence.f(i)); } FibonacciSequence.fFor(40); } }
/** * Pg 825 Chapter 13 - Intro to Comparator * Show the difference between Comparable and Comparator in an array of some words * from the NATO phonetic alphabet codeWord list. (https://en.wikipedia.org/wiki/NATO_phonetic_alphabet) */ /* pg 826 Comparator Interface: * public interface Comparator<T> { * public int compare(T obj1,T obj2) * } * * Comparator Template: * public comparatorObjectName implements Comparator<Type> { * public int compare(Type obj1, Type obj2) * { * return obj1.SomeThing - obj2.SomeThing; * } * } * * */ /* OUPUT: * codeWords[0] "Foxtrot" compareTo codeWords[i] via regular String Comparable : Foxtrot.compareTo(Foxtrot) = 0 Foxtrot.compareTo(alpha) = -27 Foxtrot.compareTo(echo) = -31 Foxtrot.compareTo(golf) = -33 Foxtrot.compareTo(bravo) = -28 Foxtrot.compareTo(hotel) = -34 Foxtrot.compareTo(Charlie) = 3 Foxtrot.compareTo(DELTA) = 2 Pg 825 codeWords: [Foxtrot, alpha, echo, golf, bravo, hotel, Charlie, DELTA] Pg 826 Arrays.sort(codeWords): [Charlie, DELTA, Foxtrot, alpha, bravo, echo, golf, hotel] Pg 827 Arrays.sort(codeWords, String.CASE_INSENSITIVE_ORDER): [alpha, bravo, Charlie, DELTA, echo, Foxtrot, golf, hotel] Pg 827 Arrays.sort(codeWords, new LengthComparator()): [echo, golf, alpha, bravo, DELTA, hotel, Charlie, Foxtrot] MadeUp: Arrays.sort(codeWords, new LastCharacterOrderComparator()): [DELTA, alpha, Charlie, golf, hotel, echo, bravo, Foxtrot] * * */ package dev.liambloom.softwareEngineering.chapter13.introToComparator; import java.util.*; public class CLIENT { public static void main(String[] args) { // sort Strings using case-insensitive Comparator String codeWords[] = {"Foxtrot", "alpha", "echo", "golf", "bravo", "hotel", "Charlie", "DELTA"}; // codeWords[0] "Foxtrot" compareTo codeWords[i] via regular String Comparable System.out.println("codeWords[0] \"Foxtrot\" compareTo codeWords[i] via regular String Comparable : "); for (int i=0; i<codeWords.length; i++) System.out.println("\t"+codeWords[0]+".compareTo("+codeWords[i]+") = " + codeWords[0].compareTo(codeWords[i])); System.out.println(); // Pg 825 codeWords System.out.print(" Pg 825 codeWords: "); System.out.print("["); for (int i=0; i<codeWords.length-1; i++) System.out.print(codeWords[i] + ", "); System.out.println(codeWords[codeWords.length-1]+"]"); System.out.println(); // Pg 826: Arrays.sort(codeWords) System.out.print(" Pg 826 Arrays.sort(codeWords): "); Arrays.sort(codeWords); System.out.print("["); for (int i=0; i<codeWords.length-1; i++) System.out.print(codeWords[i] + ", "); System.out.println(codeWords[codeWords.length-1]+"]"); System.out.println(); // Pg 827: Arrays.sort(codeWords, String.CASE_INSENSITIVE_ORDER); System.out.print(" Pg 826 Arrays.sort(codeWords, String.CASE_INSENSITIVE_ORDER): "); Arrays.sort(codeWords,String.CASE_INSENSITIVE_ORDER); System.out.print("["); for (int i=0; i<codeWords.length-1; i++) System.out.print(codeWords[i] + ", "); System.out.println(codeWords[codeWords.length-1]+"]"); System.out.println(); // Pg 827: Arrays.sort(codeWords, new LengthComparator()) System.out.print(" Pg 826 Arrays.sort(codeWords, new LengthComparator()): "); Arrays.sort(codeWords, new LengthComparator()); System.out.print("["); for (int i=0; i<codeWords.length-1; i++) System.out.print(codeWords[i] + ", "); System.out.println(codeWords[codeWords.length-1]+"]"); System.out.println(); // Use LastCharacterOrderComparator: Arrays.sort(codeWords, new LastCharacterOrderComparator()) System.out.print(" Pg 826 Arrays.sort(codeWords, new LastCharacterOrderComparator()): "); Arrays.sort(codeWords, new LastCharacterOrderComparator()); System.out.print("["); for (int i=0; i<codeWords.length-1; i++) System.out.print(codeWords[i] + ", "); System.out.println(codeWords[codeWords.length-1]+"]"); System.out.println(); // >>> Make up your own Comparator: Arrays.sort(codeWords, new YOURComparator()) <<< System.out.print(" Pg 826 Arrays.sort(codeWords, new YOURComparator()): "); Arrays.sort(codeWords, new AlphabeticalOrderFromEnd()); System.out.print("["); for (int i=0; i<codeWords.length-1; i++) System.out.print(codeWords[i] + ", "); System.out.println(codeWords[codeWords.length-1]+"]"); System.out.println(); } // main } // IntroToComparatorclass CLIENT
package page_object; import command_providers.ActOn; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import seleniumAutomation.EbayPriceValidation; public class NavigationBar { private final Logger LOGGER= LogManager.getLogger(NavigationBar.class); private final By moseHover = By.xpath("//*[@id='mainContent']/div[1]/ul/li[3]/a[text()='Motors']"); private final By ClickOnCarsTruck=By.xpath("//*[@id='mainContent']/div//a[text()='Cars & Trucks']"); // private final By returnHomePage=By.id("gh-logo"); WebDriver driver; public NavigationBar(WebDriver driver) { this.driver = driver; } public NavigationBar mouseHover() { ActOn.element(driver, moseHover).mouseHover(); return this; } public MakeSelect clickLink() { ActOn.element(driver, ClickOnCarsTruck).click(); return new MakeSelect(driver); } // public Home clickLogo(){ // ActOn.element(driver,returnHomePage).click(); // return new Home(driver); // } }
package com.bridgelabz.employeePayroll; import org.junit.Assert; import org.junit.Test; import java.time.Duration; import java.time.Instant; import java.time.LocalDate; import java.util.Arrays; import java.util.List; import java.util.Map; import static com.bridgelabz.employeePayroll.EmployeePayrollServices.IOService.DB_IO; public class EmployeePayrollServiceTest { @Test public void givenEmployeePayrollInDB_whenRetrieved_ShouldMatchEmployeeCount() { EmployeePayrollServices employeePayrollServices = new EmployeePayrollServices(); List<EmployeePayrollData> employeePayrollData = employeePayrollServices.readEmployeeData(DB_IO); Assert.assertEquals(1, employeePayrollData.size()); } @Test public void givenNewSalaryForEmployee_whenUpdated_ShouldMatchWithDB() { EmployeePayrollServices employeePayrollServices = new EmployeePayrollServices(); int i = employeePayrollServices.updateEmployeeSalary("MARK", 50000.00, DB_IO); Assert.assertEquals(1, i); } @Test public void givenDateRange_whenRetrieved_ShouldSyncWithDB() { EmployeePayrollServices employeePayrollServices = new EmployeePayrollServices(); employeePayrollServices.readEmployeeData(DB_IO); LocalDate startDate = LocalDate.of(2018, 1, 1); LocalDate endDate = LocalDate.now(); List<EmployeePayrollData> employeePayrollDataList = employeePayrollServices.readEmployeeDataForDateRange(DB_IO, startDate, endDate); System.out.println(employeePayrollDataList.toString()); Assert.assertEquals(1, employeePayrollDataList.size()); } @Test public void givenPayrollData_whenAverageSalaryRetrievedByGender_shouldReturnProperValue() { EmployeePayrollServices employeePayrollServices = new EmployeePayrollServices(); Map<String, Double> averageSalaryByGender = employeePayrollServices.readAverageSalaryByGender(DB_IO); Assert.assertTrue(averageSalaryByGender.get("M").equals(50000.00) || averageSalaryByGender.get("F").equals(0.0)); } @Test public void givenNewEmployee_whenAdded_shouldSyncWithDB() { EmployeePayrollServices employeePayrollServices = new EmployeePayrollServices(); employeePayrollServices.addEmployeeToPayroll("Neeta", 50000.00, LocalDate.now(), "F"); boolean result = employeePayrollServices.checkEmployeeDataSyncWithDB("Neeta"); Assert.assertTrue(result); } @Test public void givenEmployeeDB_whenDeleteData_shouldSyncWithDB() { EmployeePayrollServices employeePayrollServices = new EmployeePayrollServices(); boolean is_active = employeePayrollServices.deleteEmployeeData("Neeta", DB_IO); Assert.assertFalse(is_active); } }
/* * Copyright 2002-2021 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.web.servlet.mvc.condition; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; import jakarta.servlet.http.HttpServletRequest; import org.springframework.lang.Nullable; import org.springframework.util.ObjectUtils; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.util.WebUtils; /** * A logical conjunction ({@code ' && '}) request condition that matches a request against * a set parameter expressions with syntax defined in {@link RequestMapping#params()}. * * @author Arjen Poutsma * @author Rossen Stoyanchev * @since 3.1 */ public final class ParamsRequestCondition extends AbstractRequestCondition<ParamsRequestCondition> { private final Set<ParamExpression> expressions; /** * Create a new instance from the given param expressions. * @param params expressions with syntax defined in {@link RequestMapping#params()}; * if 0, the condition will match to every request. */ public ParamsRequestCondition(String... params) { this.expressions = parseExpressions(params); } private static Set<ParamExpression> parseExpressions(String... params) { if (ObjectUtils.isEmpty(params)) { return Collections.emptySet(); } Set<ParamExpression> expressions = new LinkedHashSet<>(params.length); for (String param : params) { expressions.add(new ParamExpression(param)); } return expressions; } private ParamsRequestCondition(Set<ParamExpression> conditions) { this.expressions = conditions; } /** * Return the contained request parameter expressions. */ public Set<NameValueExpression<String>> getExpressions() { return new LinkedHashSet<>(this.expressions); } @Override protected Collection<ParamExpression> getContent() { return this.expressions; } @Override protected String getToStringInfix() { return " && "; } /** * Returns a new instance with the union of the param expressions * from "this" and the "other" instance. */ @Override public ParamsRequestCondition combine(ParamsRequestCondition other) { if (isEmpty() && other.isEmpty()) { return this; } else if (other.isEmpty()) { return this; } else if (isEmpty()) { return other; } Set<ParamExpression> set = new LinkedHashSet<>(this.expressions); set.addAll(other.expressions); return new ParamsRequestCondition(set); } /** * Returns "this" instance if the request matches all param expressions; * or {@code null} otherwise. */ @Override @Nullable public ParamsRequestCondition getMatchingCondition(HttpServletRequest request) { for (ParamExpression expression : this.expressions) { if (!expression.match(request)) { return null; } } return this; } /** * Compare to another condition based on parameter expressions. A condition * is considered to be a more specific match, if it has: * <ol> * <li>A greater number of expressions. * <li>A greater number of non-negated expressions with a concrete value. * </ol> * <p>It is assumed that both instances have been obtained via * {@link #getMatchingCondition(HttpServletRequest)} and each instance * contains the matching parameter expressions only or is otherwise empty. */ @Override public int compareTo(ParamsRequestCondition other, HttpServletRequest request) { int result = other.expressions.size() - this.expressions.size(); if (result != 0) { return result; } return (int) (getValueMatchCount(other.expressions) - getValueMatchCount(this.expressions)); } private long getValueMatchCount(Set<ParamExpression> expressions) { long count = 0; for (ParamExpression e : expressions) { if (e.getValue() != null && !e.isNegated()) { count++; } } return count; } /** * Parses and matches a single param expression to a request. */ static class ParamExpression extends AbstractNameValueExpression<String> { private final Set<String> namesToMatch = new HashSet<>(WebUtils.SUBMIT_IMAGE_SUFFIXES.length + 1); ParamExpression(String expression) { super(expression); this.namesToMatch.add(getName()); for (String suffix : WebUtils.SUBMIT_IMAGE_SUFFIXES) { this.namesToMatch.add(getName() + suffix); } } @Override protected boolean isCaseSensitiveName() { return true; } @Override protected String parseValue(String valueExpression) { return valueExpression; } @Override protected boolean matchName(HttpServletRequest request) { for (String current : this.namesToMatch) { if (request.getParameterMap().get(current) != null) { return true; } } return request.getParameterMap().containsKey(this.name); } @Override protected boolean matchValue(HttpServletRequest request) { return ObjectUtils.nullSafeEquals(this.value, request.getParameter(this.name)); } } }
package msip.go.kr.organ.entity; import java.io.Serializable; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Transient; import msip.go.kr.util.IPv4Util; @SuppressWarnings("serial") @Entity @Table(name="head_dprt_ip") public class HeadDprtIp implements Serializable { @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name="id", columnDefinition="NUMERIC(19,0)") private Long id; @Column(name="ip1", columnDefinition="BIGINT") private long ip1; @Column(name="ip2", columnDefinition="BIGINT") private long ip2; @Column(name="reg_id", columnDefinition="CHAR(20)") private String regId; @Column(name="reg_nm", columnDefinition="VARCHAR(2000)") private String regNm; @Column(name="reg_date", columnDefinition="DATETIME") private Date regDate; @Transient private String startIp; @Transient private String endIp; public HeadDprtIp() {} public HeadDprtIp(Long id) { this.setId(id); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public long getIp1() { return ip1; } public void setIp1(long ip1) { this.ip1 = ip1; } public long getIp2() { return ip2; } public void setIp2(long ip2) { this.ip2 = ip2; } public String getRegId() { return regId; } public void setRegId(String regId) { this.regId = regId; } public String getRegNm() { return regNm; } public void setRegNm(String regNm) { this.regNm = regNm; } public Date getRegDate() { return regDate; } public void setRegDate(Date regDate) { this.regDate = regDate; } public String getStartIp() { return IPv4Util.toString(this.ip1); } public void setStartIp(String startIp) { this.startIp = startIp; } public String getEndIp() { return IPv4Util.toString(this.ip2); } public void setEndIp(String endIp) { this.endIp = endIp; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package Controller; import Bean.Booking; import DAO.BookingDAO; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; /** * * @author mengqwang */ public class markSeat extends HttpServlet { /** * Processes requests for both HTTP * <code>GET</code> and * <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code."> /** * Handles the HTTP * <code>GET</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } /** * Handles the HTTP * <code>POST</code> method. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { HttpSession session=request.getSession(); int memberID=0; if(session.getAttribute("memberID")!=null) memberID=(Integer)session.getAttribute("memberID"); else if(session.getAttribute("managerID")!=null) memberID=1; else if(session.getAttribute("officerID")!=null) memberID=2; int sectionID=Integer.parseInt(request.getParameter("SectionID_m")); String seatNo=request.getParameter("seat_m"); String unmark=request.getParameter("unmark"); int nSeats=0; String[] indiSeats=seatNo.split(","); nSeats=indiSeats.length; int[] seatArr; seatArr=new int[nSeats]; for(int i=0;i<nSeats;i++) { seatArr[i]=Integer.parseInt(indiSeats[i]); } List<Booking> bkInfo=new ArrayList<Booking>(); for(int i=0;i<nSeats;i++) { Booking indibk=new Booking(); indibk.setSeat(seatArr[i]); indibk.setSectionID(sectionID); indibk.setMemberID(memberID); indibk.setStatus("P"); indibk.setPayment(-1); bkInfo.add(indibk); } for(Booking bk:bkInfo) { BookingDAO bkdao=new BookingDAO(); bkdao.addBkRecord(bk); } nSeats=0; String[] unmarkSeat=unmark.split(","); nSeats=unmarkSeat.length; int[] unMark; unMark=new int[nSeats]; for(int i=0;i<nSeats;i++) { unMark[i]=Integer.parseInt(unmarkSeat[i]); } bkInfo=new ArrayList<Booking>(); for(int i=0;i<nSeats;i++) { Booking indibk=new Booking(); indibk.setSeat(unMark[i]); indibk.setSectionID(sectionID); bkInfo.add(indibk); } for(Booking bk:bkInfo) { BookingDAO bkdao=new BookingDAO(); bkdao.deleteMarking(bk); } request.getRequestDispatcher("MovieDisplay?Action=MovieDisplay").forward(request, response); } finally { out.close(); } } /** * Returns a short description of the servlet. * * @return a String containing servlet description */ @Override public String getServletInfo() { return "Short description"; }// </editor-fold> }
class MergeSort { // Merges two subarrays of arr[]. // First subarray is arr[l..m] // Second subarray is arr[m+1..r] void merge(int arr[], int l, int m, int r) { int[] left = new int[m]; for (int i=0; i<m; i++) { left[i] = arr[i]; } int[] right = new int[arr.length - m]; for (int i=m; i<arr.length; i++) { right[i - m] = arr[i]; } int i=0; int j=0; int k=0; while (i < left.length && j<right.length) { if (left[i] <= right[i]) { arr[k++] = left[i++]; } else { arr[k++] = right[j++]; } } while (i<left.length) { arr[k++] = left[i++]; } while (j<right.length) { arr[k++] = right[j++]; } } // Main function that sorts arr[l..r] using // merge() void sort(int arr[], int l, int r) { //Write your code here //Call mergeSort from here if (arr.length < 2) { return; } if (r > l) { return; } int mid = arr.length / 2; sort(arr, l, mid); sort(arr, mid + 1, r); merge(arr, l, mid, r); } /* A utility function to print array of size n */ static void printArray(int arr[]) { int n = arr.length; for (int i=0; i<n; ++i) System.out.print(arr[i] + " "); System.out.println(); } // Driver method public static void main(String args[]) { int arr[] = {12, 11, 13, 5, 6, 7}; System.out.println("Given Array"); printArray(arr); MergeSort ob = new MergeSort(); ob.sort(arr, 0, arr.length-1); System.out.println("\nSorted array"); printArray(arr); } }
package language.thread.lock.juc; public class ReentrantLockAble { boolean isLocked = true; Thread lockedBy = null; int lockCount = 0; public synchronized void lock() throws InterruptedException { Thread thread = Thread.currentThread(); while (isLocked && lockedBy != thread) { wait(); } lockedBy = thread; isLocked = true; ++lockCount; } public synchronized void unlock() { Thread thread = Thread.currentThread(); if (thread == lockedBy) { --lockCount; if (lockCount == 0) { isLocked = false; notify(); } } } }
package com.lasform.core.business.exceptions; public class EmptyFieldException extends BusinessException { public EmptyFieldException(){ super("Empty Field Exception"); setBusinessExceptionCode(1003); } public EmptyFieldException( String message ){ super(message); setBusinessExceptionCode(1003); } }