text
stringlengths
10
2.72M
/* * 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 model; import java.sql.Timestamp; /** * * @author bynan */ public class AppointmentModel { private int id; private int medic_id; private int crenel_id; private int patient_folder_id; private String date; private Timestamp timestamp; private Timestamp updated_at; public Timestamp getUpdated_at() { return updated_at; } public void setUpdated_at(Timestamp updated_at) { this.updated_at = updated_at; } public AppointmentModel(int id, int medic_id, int crenel_id, int patient_folder_id, String date, Timestamp timestamp, Timestamp updated_at) { this.id = id; this.medic_id = medic_id; this.crenel_id = crenel_id; this.patient_folder_id = patient_folder_id; this.timestamp = timestamp; this.updated_at = updated_at; this.date = date; } public AppointmentModel(int id,int idpatientfolder, int idmedics, int idcreno, String date, Timestamp ts) { this.id = id; this.patient_folder_id = idpatientfolder; this.medic_id = idmedics; this.crenel_id = idcreno; this.date = date; this.timestamp = ts; } public AppointmentModel() { } public AppointmentModel(int idpatientfolder, int idmedics, int idcreno, String date, Timestamp ts) { this.patient_folder_id = idpatientfolder; this.medic_id = idmedics; this.crenel_id = idcreno; this.date = date; this.timestamp = ts; } @Override public String toString() { return "AppointmentModel{" + "medic_id=" + medic_id + ", crenel_id=" + crenel_id + ", patient_folder_id=" + patient_folder_id + ", timestamp=" + timestamp + ", date=" + date + '}'; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public int getMedic_id() { return medic_id; } public void setMedic_id(int medic_id) { this.medic_id = medic_id; } public int getCrenel_id() { return crenel_id; } public void setCrenel_id(int crenel_id) { this.crenel_id = crenel_id; } public int getPatient_folder_id() { return patient_folder_id; } public void setPatient_folder_id(int patient_folder_id) { this.patient_folder_id = patient_folder_id; } public Timestamp getTimestamp() { return timestamp; } public void setTimestamp(Timestamp timestamp) { this.timestamp = timestamp; } }
package tw.org.iii; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Dispatcher */ @WebServlet("/Dispatcher") public class Dispatcher extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); // 針對中文檔名處理, 必須在任何 request之前做的設定 request.setCharacterEncoding("UTF-8"); } }
package com.huawei.esdk.tp.professional.local.impl.autogen; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="confId" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="switchGate" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;element name="isSwitch" type="{http://www.w3.org/2001/XMLSchema}int"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "confId", "switchGate", "isSwitch" }) @XmlRootElement(name = "setAudioSwitchEx") public class SetAudioSwitchEx { @XmlElement(required = true) protected String confId; @XmlElement(type = String.class) @XmlJavaTypeAdapter(Adapter3 .class) @XmlSchemaType(name = "int") protected Integer switchGate; @XmlElement(required = true, type = String.class) @XmlJavaTypeAdapter(Adapter3 .class) @XmlSchemaType(name = "int") protected Integer isSwitch; /** * Gets the value of the confId property. * * @return * possible object is * {@link String } * */ public String getConfId() { return confId; } /** * Sets the value of the confId property. * * @param value * allowed object is * {@link String } * */ public void setConfId(String value) { this.confId = value; } /** * Gets the value of the switchGate property. * * @return * possible object is * {@link String } * */ public Integer getSwitchGate() { return switchGate; } /** * Sets the value of the switchGate property. * * @param value * allowed object is * {@link String } * */ public void setSwitchGate(Integer value) { this.switchGate = value; } /** * Gets the value of the isSwitch property. * * @return * possible object is * {@link String } * */ public Integer getIsSwitch() { return isSwitch; } /** * Sets the value of the isSwitch property. * * @param value * allowed object is * {@link String } * */ public void setIsSwitch(Integer value) { this.isSwitch = value; } }
package top.zeroyiq.master_help_me.fragments; import android.graphics.Color; import android.os.Bundle; import android.os.Handler; import android.support.annotation.Nullable; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v4.widget.SwipeRefreshLayout; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ListView; import android.widget.ProgressBar; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import top.zeroyiq.master_help_me.MyApplication; import top.zeroyiq.master_help_me.R; import top.zeroyiq.master_help_me.activities.DetailsActivity; import top.zeroyiq.master_help_me.adapter.QuestionsAdapter; import top.zeroyiq.master_help_me.apis.APISource; import top.zeroyiq.master_help_me.apis.QuestionsAPi; import top.zeroyiq.master_help_me.models.ErrorMessage; import top.zeroyiq.master_help_me.models.Questions; import top.zeroyiq.master_help_me.models.Resource; import top.zeroyiq.master_help_me.utils.ACache; /** * 问题碎片 * Created by ZeroyiQ on 2017/9/8. */ public class QuestionFragment extends Fragment { @BindView(R.id.progressBar_question) ProgressBar progressBarQuestion; @BindView(R.id.list_question) ListView listQuestion; @BindView(R.id.swipe_refresh) SwipeRefreshLayout swipeRefresh; private ACache aCache = ACache.get(MyApplication.getAppContext()); private View rootView; // fragment 的界面 private String fragmentName; // 每个 fragmentTab 的名字 // private int currentPage; // 当前页数 private List<Questions> queList; // 问题列表 private String category; // 对应科目 private QuestionsAdapter questionsAdapter; public static QuestionFragment newsInstance(String fragmentName, String categoryPath) { QuestionFragment questionsListFragment = new QuestionFragment(); Bundle bundle = new Bundle(); bundle.putString("fragmentName", fragmentName); bundle.putString("categoryPath", categoryPath); questionsListFragment.setArguments(bundle); return questionsListFragment; } @Override public void onPause() { super.onPause(); Resource<Questions> tempList = ((Resource<Questions>) aCache.getAsObject(fragmentName)); if (tempList == null) { /** * ---------调试段落----------- */ getQuestions(); // initData(); /** * ---------调试段落----------- */ } else { loadData(tempList.getResource()); } } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); init(); initRefresh(); Resource<Questions> tempList = ((Resource<Questions>) aCache.getAsObject(fragmentName)); if (tempList == null) { /** * ---------调试段落----------- */ getQuestions(); // initData(); /** * ---------调试段落----------- */ } else { loadData(tempList.getResource()); } } // private void initData() { // if (category.equals("gdsx")) { // for (int i = 0; i < 4; i++) { // queList.add(new Questions("-∫(0~2π)e^sint dcost=?\n" + // "为什么?", "原式化为(先当做不定积分化简)" + // "∫xe^xdx=∫xde^x=xe^x-∫e^xdx=xe^x-e^x=e^x(x-1)", "2017-6-8", "/111")); // queList.add(new Questions("第五题(X的上角标为2n),为什么会有间断点," + // "我觉得一般的间断点都是分母不能为0,这题为什么会有间断点1", "是这个样子的,你要看定义,f(x-) =f(x+)\n" + // "在1 的1+ 1- 两边,f(x)不相等,所以就是间断点\n" + // "简短点分两类,第一类可去和第二类无穷,这种属于第二类", "2017-5-14", "/111")); // } // } else if (category.equals("dxwl")) { // queList.clear(); // for (int i = 0; i < 5; i++) { // queList.add(new Questions("在XOY平面内,有一运动的质点,其运动方程为r=2cos5t i +2sin5t j," + // "则t时刻其切向加速的大小为? 这个切向加速度不是只有坐曲线运动中,与法向加速度共同存在的吗?", "=dr/dt=-10sin5t i+10cos5t j\n" + // "切向加速度=dV/dt=-50sin5t i-50cos5t j\n" + // "ax=-50sin5t\n" + // "ay=-50cos5t\n" + // "切向加速度的大小为\n" + // "a=根号[(ax)^2+(ay)^2]=50", "2017-7-15", "/111")); // queList.add(new Questions("非保守内力,就是小球与滑块间的弹力做功和为什么为零?\n" + // " 质量为M半径为R的1/4圆周的光滑弧形滑块,静止在光滑桌面上,今有质量为m的物体", "弹力对滑块做正功,对小球做负功,两者之和为零。因为两者受到的弹力为一对相互作用力,但是位移方向一致,故两者和为零。\n" + // "应用动量守恒和能量守恒。", "2014-02-15", "/111")); // } // } // } @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { rootView = inflater.inflate(R.layout.fragment_questions_list, container, false); ButterKnife.bind(this, rootView); return rootView; } private void initRefresh() { swipeRefresh.setColorSchemeColors(Color.RED, Color.BLUE); swipeRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { new Handler().postDelayed(new Runnable() { @Override public void run() { queList.clear(); // currentPage = 0; /** * -----------------调试段----------------- */ getQuestions(); swipeRefresh.setRefreshing(false); /** * -----------------调试段----------------- */ Snackbar.make(rootView, "刷新完成", Snackbar.LENGTH_LONG).show(); } }, 1000); } } ); } /** * 得到问题 */ private void getQuestions() { QuestionsAPi queApi = APISource.getInstance().getAPIObject(QuestionsAPi.class); Call<Resource<Questions>> call = queApi.getQuestions(category); call.enqueue(new Callback<Resource<Questions>>() { @Override public void onResponse(Call<Resource<Questions>> call, Response<Resource<Questions>> response) { swipeRefresh.setRefreshing(false); // 下拉菜单收起 if (response.isSuccessful()) { Resource<Questions> tempList = response.body(); if (tempList != null) { aCache.put(fragmentName, tempList); // 缓存数据 loadData(tempList.getResource()); } } else { ErrorMessage e = APISource.getErrorMessage(response); onFailure(call, e.toException()); } } @Override public void onFailure(Call<Resource<Questions>> call, Throwable t) { swipeRefresh.setRefreshing(false); Snackbar.make(rootView, "获取失败:" + t.getMessage(), Snackbar.LENGTH_LONG).show(); Log.d("Debug", "onFailure: " + t.getMessage()); } } ); } /** * 加载数据 * * @param tempList */ private void loadData(List<Questions> tempList) { queList.addAll(tempList); progressBarQuestion.setVisibility(View.GONE); // questionsAdapter.addItem(queList); // if (currentPage == 0) { listQuestion.setAdapter(questionsAdapter); // } else { // questionsAdapter.notifyDataSetChanged();// 强制刷新 // } // currentPage++; } /** * 初始化数据 */ private void init() { Bundle bundle = getArguments(); fragmentName = bundle.getString("fragmentName"); // currentPage = 0; queList = new ArrayList<>(); category = bundle.getString("categoryPath"); questionsAdapter = new QuestionsAdapter(QuestionFragment.this.getActivity(), R.layout.item_question, queList); listQuestion.setAdapter(questionsAdapter); listQuestion.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // queLink = queList.get(position).getUser(); DetailsActivity.actionStart(getContext(), fragmentName, category,queList.get(position)); } }); } // @Override // public void onDestroyView() { // super.onDestroyView(); // unbinder.unbind(); // } }
package edu.neu.coe.info6205.symbolTable; import java.util.Random; public class Main { public static void main(String[] args){ System.out.println("--------------------------- Tree with 100 nodes----------------------"); BSTSimple<Integer, Integer> bst = new BSTSimple<Integer, Integer>(); Random random = new Random(); for(int i=0; i<100; i++){ int key = random.nextInt(); int value = random.nextInt(); bst.put(key,value); } int size = bst.size(); System.out.println("-------------------Below are the parameter measures for 100 node tree------------------"); System.out.println("Size --> "+size); int depthOfTree = bst.depth(); System.out.println("Depth--> : "+depthOfTree); System.out.println("log N -->"+size+" O(ln N) = "+Math.log(size)); System.out.println(" O(SquareRoot(N)) = "+Math.sqrt(size)); int N= 100; for (int i=0;i<30;i++){ N = N+ 10000; //----------------------------------------------- Random r2 = new Random(); System.out.println("----------------- Tree metrics "+N+" after randomized input -----------------"); for (int i1=0; i1<N; i1++){ int choose = random.nextInt(3); Integer key1 = (Integer)random.nextInt(200); int value = r2.nextInt(); if(choose == 0){ bst.put(key1,value); } else if (choose == 1){ bst.delete(key1); } else if (choose == 2){ bst.get(bst.getRoot(),key1); } } int sizeAfterOperations = bst.size(); System.out.println("Size of the tree--> "+sizeAfterOperations); int heightAfterOperations = bst.depth(); System.out.println("Depth -->"+heightAfterOperations); System.out.println("log(N)--> "+(Math.log(sizeAfterOperations)/Math.log(2))); System.out.println("O(sqaure root of N)--> "+Math.sqrt(sizeAfterOperations)); //------------------------------------------------ } } }
package com.magit.logic.system.objects; import com.magit.logic.exceptions.IllegalPathException; import com.magit.logic.utils.digest.Sha1; import com.magit.logic.utils.file.FileHandler; import java.io.File; import java.io.IOException; import java.nio.file.FileAlreadyExistsException; import java.nio.file.InvalidPathException; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Objects; public class Branch { private final String mBranchName; private Sha1 mPointedCommitSha1; private String mTrackingAfter = null; private Boolean mIsRemote = false; private Boolean mTracking = false; Branch(String mBranchName) { this.mBranchName = mBranchName; final String EMPTY = ""; mPointedCommitSha1 = new Sha1(EMPTY, true); } public Branch(String branchName, String textToSha1) { this.mBranchName = branchName; mPointedCommitSha1 = new Sha1(textToSha1, true); } public void setIsRemote(boolean mIsRemote) { this.mIsRemote = mIsRemote; } public void setTrackingAfter(String mTrackingAfter) { this.mTrackingAfter = mTrackingAfter; } public void setIsTracking(Boolean mTracking) { this.mTracking = mTracking; } public String getTrackingAfter() { return mTrackingAfter; } public Boolean getIsRemote() { return mIsRemote; } public Boolean getIsTracking() { return mTracking; } public Branch(String branchName, String textToSha1, String trackingAfter, boolean isRemote, boolean tracking) { this.mBranchName = branchName; mPointedCommitSha1 = new Sha1(textToSha1, true); mTrackingAfter = trackingAfter; mIsRemote = isRemote; mTracking = tracking; } public Sha1 getPointedCommitSha1() { return mPointedCommitSha1; } void setPointedCommitSha1(Sha1 mPointedCommitSha1) { this.mPointedCommitSha1 = mPointedCommitSha1; } void create(String path) throws IllegalPathException, IOException { try { Path filePath = Paths.get(path, ".magit", "branches", mBranchName); File branch = new File(filePath.toString()); boolean newFile = !branch.exists(); if (!newFile) { //System.out.println("file exists"); TODO(REMOVE WHEN SUBMITTING) throw new FileAlreadyExistsException(".magit already exists"); } else { FileHandler.appendFileWithContentAndLine(filePath.toString(), mPointedCommitSha1.toString()); FileHandler.appendFileWithContentAndLine(filePath.toString(),mIsRemote.toString()); FileHandler.appendFileWithContentAndLine(filePath.toString(),mTracking.toString()); FileHandler.appendFileWithContentAndLine(filePath.toString(),mTrackingAfter); //System.out.println("file created"); TODO(REMOVE WHEN SUBMITTING) } } catch (InvalidPathException e) { throw new IllegalPathException(path + " is not a valid path."); } } public String getBranchName() { return mBranchName; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Branch branch = (Branch) o; return Objects.equals(mBranchName, branch.mBranchName) && Objects.equals(mPointedCommitSha1, branch.mPointedCommitSha1); } @Override public int hashCode() { return Objects.hash(mBranchName, mPointedCommitSha1); } }
package com.twitter.challenge; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.twitter.challenge.presenter.MainPresenter; public class MainActivity extends AppCompatActivity implements ViewPresenterContract.BaseView { private MainPresenter mainPresenter; private String deviation; private Double temperature; private String windSpeed; private boolean isCloudy; private TextView temperatureView; private TextView windSpeedView; private TextView deviationView; private ImageView cloudView; private Button deviationButton; private ProgressBar progressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); temperatureView = (TextView) findViewById(R.id.temperature); windSpeedView = (TextView) findViewById(R.id.speed); deviationView = (TextView) findViewById(R.id.deviation); cloudView = (ImageView) findViewById(R.id.cloudness); deviationButton = (Button) findViewById(R.id.deviationButton); progressBar = (ProgressBar) findViewById(R.id.progress_bar); mainPresenter = new MainPresenter(this); if (savedInstanceState == null) { mainPresenter.loadCurrentWeather(); } else { if (savedInstanceState.getString("windSpeed") != null) { showCurrentWeather(savedInstanceState.getDouble("temperature"), savedInstanceState.getString("windSpeed"), savedInstanceState.getBoolean("isCloudy")); } if (savedInstanceState.getString("deviation") != null) { showNextFiveDaysDeviation(savedInstanceState.getString("deviation")); } } deviationButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { if (progressBar.getVisibility() == View.GONE){ mainPresenter.loadNextFiveDaysWeather(); } } }); } @Override public void showProgressBar() { progressBar.setVisibility(View.VISIBLE); } @Override public void hideProgressBar() { progressBar.setVisibility(View.GONE); } @Override public void showCurrentWeather(Double temperature,String windSpeed, boolean isCloudy) { this.temperature = temperature; this.windSpeed = windSpeed; this.isCloudy = isCloudy; temperatureView.setText(getString(R.string.temperature, temperature, TemperatureConverter.celsiusToFahrenheit(temperature.floatValue()))); windSpeedView.setText(windSpeed); cloudView.setVisibility(isCloudy ? View.VISIBLE : View.GONE); } @Override public void showNextFiveDaysDeviation(String deviation) { this.deviation = deviation; deviationView.setText("Deviation: " + deviation); } @Override public void showError(String error) { Toast.makeText(this, error, Toast.LENGTH_LONG).show(); } @Override protected void onSaveInstanceState(Bundle outState) { if (windSpeed != null) { outState.putString("windSpeed", windSpeed); outState.putDouble("temperature", temperature); outState.putBoolean("isCloudy", isCloudy); } if (deviation != null) { outState.putString("deviation", deviation); } super.onSaveInstanceState(outState); } @Override protected void onDestroy() { if (mainPresenter != null) { mainPresenter.detachView(); mainPresenter = null; } super.onDestroy(); } }
package com.ibeiliao.pay.account.api.dto.response; import com.ibeiliao.pay.account.api.dto.BankAccountVO; import com.ibeiliao.pay.api.ApiResultBase; /** * * 获取银行账号信息返回响应类型 * Created by jingyesi on 16/7/18. */ public class GetAccountResponse extends ApiResultBase{ /** * */ private static final long serialVersionUID = -183938894238164572L; /** * 银行账号 */ private BankAccountVO account; public BankAccountVO getAccount() { return account; } public void setAccount(BankAccountVO account) { this.account = account; } }
package 笔试代码.实战; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Map; //https://m.isolves.com/it/cxkf/cxy/2020-08-06/27248.html //阿里面试代码题目 实现有向无环图dag的 deep copy public class 实现dag的深拷贝 { static class Node{ private int val; private Collection<Node>neighbors; public Node(int val,Collection<Node>neighbors){ this.val=val; this.neighbors=neighbors; } public Collection<Node> getNeighbor(){ return this.neighbors; } public int getVal(){ return this.val; } } public static Collection<Node> DeepCopy(Collection<Node> nodes){ Collection<Node> newNodes=new ArrayList<>(); Map<Node,Node> copyMap=new HashMap<>(); for(Node node:nodes){ newNodes.add(copyNode(node,copyMap)); } return newNodes; } private static Node copyNode(Node node,Map<Node,Node>copyMap){ if(copyMap.containsKey(node)){ return copyMap.get(node); } //新节点需要原节点的值以及邻居 //对邻居的每个节点复制构成新节点的邻居集合 Collection<Node> newNeighbors=new ArrayList<>(); for(Node neighNode:node.getNeighbor()){ newNeighbors.add(copyNode(neighNode,copyMap)); } //构造新节点 Node newNode=new Node(node.getVal(),newNeighbors); //放在map缓存 copyMap.put(node,newNode); return newNode; } }
package Networking; public interface MyServer extends java.rmi.Remote { Point movePoint(Point aPoint) throws java.rmi.RemoteException; int getX() throws java.rmi.RemoteException; int getY() throws java.rmi.RemoteException; }
/* * 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 connecttodb; /** * * @author Dmitry */ public class Run { public static void main(String[] args) { String name = "getFromDB"; String varFind = "ID"; String [] strs = {"var1", "var_2", "var3"}; Strings s = new Strings(); System.out.println(s.getSubName(name, varFind) + s.getInitVars(strs) + s.getConnectionString() + s.getConnection("R190409", strs, "IDs", varFind) + s.getSubEnd()); } }
package events; public abstract class Scrollable { public abstract void actionOnScoll(double direction); }
package com.app.arrays; import java.util.Arrays; public class SecondLargest { public static int getLarestNumber(int a[], int total) { Arrays.sort(a); return a[total-2]; //return a[total-3] third largest } public static void main(String[] args) { int a[] = {54,75,85,62,25,98}; System.out.println("Second largest is: "+getLarestNumber(a, 6)); } }
package com.service; import java.util.List; import java.util.Map; import com.model.Room; public interface RoomService { List<Room> selectVirtualRoom(Map<String,Object> map); List<Room> selectAllRoom(Room room); List<String> selectAllId(); Room selectScreenByRoom(Room room); int insertSelective(Room room); Room selectByPrimaryKey(Room room); int updateByPrimaryKeySelective(Room room); int deleteByPrimaryKey(Room room); }
package net.sourceforge.vrapper.keymap; import static net.sourceforge.vrapper.keymap.StateUtils.transitionUnion; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; public class HashMapState<T> implements State<T> { protected Map<KeyStroke, Transition<T>> map; public HashMapState(Collection<KeyBinding<T>> bindings) { this.map = new HashMap<KeyStroke, Transition<T>>(bindings.size()); for (KeyBinding<T> binding: bindings) { if (!map.containsKey(binding.getKeyPress())) { map.put(binding.getKeyPress(), binding.getTransition()); } } } protected HashMapState() { this.map = new HashMap<KeyStroke, Transition<T>>(); } private HashMapState(Map<KeyStroke, Transition<T>> map) { this.map = map; } public Transition<T> press(KeyStroke key) { return map.get(key); } public Collection<KeyStroke> supportedKeys() { return map.keySet(); } public State<T> union(State<T> other) { HashMapState<T> result = new HashMapState<T>(new HashMap<KeyStroke, Transition<T>>(map)); if (other instanceof HashMapState<?>) { HashMapState<T> otherHMS = (HashMapState<T>) other; result.map.putAll(map); result.map.putAll(otherHMS.map); Set<KeyStroke> commonKeys = new HashSet<KeyStroke>(map.keySet()); commonKeys.retainAll(otherHMS.map.keySet()); for (KeyStroke key: commonKeys) result.map.put(key, transitionUnion(press(key), other.press(key))); return result; } return new UnionState<T>(this, other); } }
package search.core; import java.util.HashMap; import java.util.Iterator; import java.util.Map.Entry; import java.util.Random; public class Histogram<T> implements Iterable<T> { private HashMap<T,Double> counts = new HashMap<>(); private Random rand = new Random(); public Histogram() {} public Histogram(Histogram<T> other) { this.counts.putAll(other.counts); if (this.counts.size() != other.counts.size()) { throw new IllegalStateException("Huh? " + this.counts.size() + ": " + other.counts.size()); } } public void bump(T value) { bumpBy(value, 1); } public void bumpBy(T value, double numBumps) { counts.put(value, getCountFor(value) + numBumps); } public Double getCountFor(T value) { return counts.getOrDefault(value, 0.0); } public Double getTotalCounts() { double total = 0; for (Entry<T,Double> entry: counts.entrySet()) { total += entry.getValue(); } return total; } @Override public Iterator<T> iterator() { return counts.keySet().iterator(); } public T getPluralityWinner() { Entry<T, Double> best = null; for (Entry<T, Double> element : counts.entrySet()){ if ( best == null || best.getValue() < element.getValue()){ best = element; } } return best.getKey(); } public void add(Histogram<T> elements){ for (T key : elements){ bumpBy(key, elements.getCountFor(key)); } } public double probabilityOf(T element){ return getCountFor(element)/getTotalCounts(); } public Histogram<T> combine(Histogram<T> other, double combinationFactor){ Histogram<T> child = new Histogram<>(); for (T key : other){ double newCount = (other.getCountFor(key) - getCountFor(key))*combinationFactor + getCountFor(key); child.bumpBy(key, newCount); } return child; } public double sumExcluded(Histogram<T> other){ double distance = 0; for (T key : other){ if (!counts.containsKey(key)) distance += other.getCountFor(key); } for (T key : counts.keySet()){ if (!other.counts.containsKey(key)) distance += getCountFor(key); } return distance; } public double distanceTo(Histogram<T> other){ double distance = 0; for (Entry<T, Double> element : counts.entrySet()){ distance += Math.pow(element.getValue() - other.getCountFor(element.getKey()), 2); } return distance; } public double sum(int power){ double sum = 0; for (Entry<T, Double> element : counts.entrySet()){ sum += Math.pow(element.getValue(), power); } return sum; } public double sum(Histogram<T> other, int power){ double sum = 0; for (Entry<T, Double> element : counts.entrySet()){ sum += Math.pow(element.getValue() * other.getCountFor(element.getKey()), power); } return sum; } public double cosineSimilarity(Histogram<T> other){ double sumAB = sum(other, 1), sumA2 = sum(2), sumB2 = other.sum(2); return sumAB / (sumA2 + sumB2); } }
package cs.zju.config; import org.apache.commons.configuration2.Configuration; import org.apache.commons.configuration2.builder.fluent.Configurations; import org.apache.commons.configuration2.ex.ConfigurationException; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class Config { private static final Configuration config = getProjectConfiguration(); private static final String[] projects = getStringArrayProperty("projects"); private static final String[] cloneUrls = getStringArrayProperty("urls"); public static Configuration getProjectConfiguration(){ Configurations configs = new Configurations(); try { return configs.properties(new File("config.properties")); } catch (ConfigurationException ex) { ex.printStackTrace(); throw new ExceptionInInitializerError(ex); } } private static String[] getStringArrayProperty(String propertyName){ return config.getStringArray(propertyName); } public static String getStringProperty(String propertyName){ return config.getString(propertyName); } public static boolean getBooleanProperty(String propertyName){ return config.getBoolean(propertyName); } public static List<String> getProjects(){ return new ArrayList<>(Arrays.asList(projects)); } public static List<String> getCloneUrls(){ return new ArrayList<>(Arrays.asList(cloneUrls)); } public static String projectPath(String project){ String tmpFolder = getStringProperty("tmpfolder"); return new File(new File(tmpFolder), "gitfiles/" + project).getAbsolutePath(); } public static String projectPmdPath(String project){ String path = projectPath(project); File baseDir = new File(path).getParentFile(); File pmdDir = new File(baseDir, "pmd/" + project); if (!pmdDir.exists()) pmdDir.mkdirs(); return pmdDir.getAbsolutePath(); } public static String projectPmdResultPath(String project, String commitId){ String pmdPath = projectPmdPath(project); return new File(new File(pmdPath), "result-"+commitId+".csv").getAbsolutePath(); } public static String resultPath(String project){ String path = projectPath(project); File baseDir = new File(path).getParentFile(); File resultFile = new File(baseDir, project + "_add.csv"); return resultFile.getAbsolutePath(); } }
/** Copyright 2013 Osnir F CUNHA Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.ocunha.amensagem.activities; import android.annotation.SuppressLint; import android.content.Intent; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ArrayAdapter; import android.widget.GridView; import com.ocunha.amensagem.BibliaApplication; import com.ocunha.amensagem.R; import com.ocunha.amensagem.db.BibliaDAO; import com.ocunha.amensagem.objects.Capitulo; import com.ocunha.amensagem.objects.Livro; import java.util.List; /** * @author Osnir F CUNHA * */ @SuppressLint("ValidFragment") public class CapituloFragment extends Fragment { private Livro livro; public CapituloFragment(){} public CapituloFragment(int livroId) { livro = BibliaDAO.getInstance(BibliaApplication.getContext()).buscarLivro(livroId); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if(savedInstanceState != null){ livro = (Livro) savedInstanceState.getSerializable("livro"); } List<Capitulo> capitulos = BibliaDAO.getInstance(BibliaApplication.getContext()).buscarCapitulos(livro); ArrayAdapter<Capitulo> arrayAdapter = new ArrayAdapter<>( getActivity(), R.layout.item_grid_capitulo, capitulos); View view = inflater.inflate(R.layout.capitulos_grid, container, false); GridView gridView = (GridView) view.findViewById(R.id.capitulosGridView); gridView.setAdapter(arrayAdapter); gridView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Capitulo capitulo = (Capitulo) parent.getAdapter().getItem(position); capitulo.setLivro(livro); Intent intent = new Intent(getActivity(), VersiculosActivity.class); intent.putExtra("capitulo", capitulo); startActivity(intent); } }); return view; } @Override public void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putSerializable("livro", this.livro); } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.apache.webbeans.test.portable.scopeextension.broken; import jakarta.enterprise.context.Dependent; import jakarta.enterprise.event.Observes; import jakarta.enterprise.inject.spi.AfterBeanDiscovery; import jakarta.enterprise.inject.spi.BeforeBeanDiscovery; /** * This is in fact a broken CDI bean as it implements * a CDI Container Lifecycle observer. * We must ensure that this bean doesn't get called during bootstrap. * The CDI spec says nothing about whether we must throw a DeploymentException * or not, so we leave this out. */ @Dependent public class CdiBeanWithLifecycleObserver { public static boolean beforeBeanDiscoveryCalled = false; public static boolean afterBeanDiscoveryCalled = false; private int meaningOfLife = 42; public int getMeaningOfLife() { return meaningOfLife; } public void setMeaningOfLife(int meaningOfLife) { this.meaningOfLife = meaningOfLife; } /** * This method must not be called by the container during bootstrap */ public void beforeBeanDiscovery(@Observes BeforeBeanDiscovery bbd) { beforeBeanDiscoveryCalled = true; } /** * This method must not be called by the container during bootstrap */ public void afterBeanDiscovery(@Observes AfterBeanDiscovery abd) { afterBeanDiscoveryCalled = true; } }
package com.smxknife.java2.generics; /** * @author smxknife * 2019-04-19 */ public class Animal { }
package com.study.collura.objectboxstudy.mvp.base; public abstract class BaseModel < T > { protected T presenter; public BaseModel (T presenter) { this.presenter = presenter; } }
package cbde.labs.hbase_mapreduce; import java.io.IOException; import java.util.ArrayList; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.IntWritable; import org.apache.hadoop.io.NullWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.Mapper; import org.apache.hadoop.mapreduce.Reducer; import org.apache.hadoop.mapreduce.Reducer.Context; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.SequenceFileInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import cbde.labs.hbase_mapreduce.CartesianProduct.CartesianMapper; import cbde.labs.hbase_mapreduce.CartesianProduct.CartesianReducer; public class Selection extends JobMapReduce { //mirar el projection y será igual cogiendo type 3 y clave usar 1,2,3,.... public Selection() { this.input = null; this.output = null; } public static class SelectionMapper extends Mapper<Text, Text, IntWritable, Text> { private static int N = 100; private int newKey = 0; public void map(Text key, Text value, Context context) throws IOException, InterruptedException { // Obtain the parameters sent during the configuration of the job String where = context.getConfiguration().getStrings("where")[0]; String valor = context.getConfiguration().getStrings("valor")[0]; // Since the value is a CSV, just get the lines split by commas String[] arrayValues = value.toString().split(","); String whereValue = Utils.getAttribute(arrayValues, where); // Do the cartesian product and emit it if (whereValue.equals(valor)) { context.write(new IntWritable(this.newKey), value); newKey++; } } } public boolean run() throws IOException, ClassNotFoundException, InterruptedException { Configuration configuration = new Configuration(); // Define the new job and the name it will be given Job job = Job.getInstance(configuration, "Selection"); configureJob(job,this.input, this.output); // Let's run it! return job.waitForCompletion(true); } public static void configureJob(Job job, String pathIn, String pathOut) throws IOException, ClassNotFoundException, InterruptedException { job.setJarByClass(Selection.class); job.setMapperClass(SelectionMapper.class); job.setMapOutputKeyClass(IntWritable.class); job.setMapOutputValueClass(Text.class); job.setOutputKeyClass(IntWritable.class); job.setOutputValueClass(Text.class); job.setInputFormatClass(SequenceFileInputFormat.class); FileInputFormat.addInputPath(job, new Path(pathIn)); FileOutputFormat.setOutputPath(job, new Path(pathOut)); job.getConfiguration().setStrings("where", "type"); job.getConfiguration().setStrings("valor", "type_1"); } }
package com.test.server; import com.test.dao.ProDao; import com.test.dao.ProDaoTmpl; import com.test.pojo.Product; import com.test.utils.FileAction; import com.test.utils.Proutil; import javax.servlet.ServletException; import javax.servlet.annotation.MultipartConfig; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.Part; import java.io.IOException; @WebServlet(name = "AddProServlet",urlPatterns = "/addpro.do") @MultipartConfig public class AddProServlet extends HttpServlet { private ProDao pd; @Override public void init() throws ServletException { pd = new ProDaoTmpl(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String sname = request.getParameter("proName"); String proPrice = request.getParameter("proPrice"); //获得图片 Part file1 = request.getPart("file1"); String realname = FileAction.uploadFile(file1); String prodes = request.getParameter("prodes"); String prostock = request.getParameter("prostock"); String prodate = request.getParameter("prodate"); String procateid = request.getParameter("procateid"); String profac = request.getParameter("profac"); Product product = new Product(Proutil.getProId(),sname,Double.parseDouble(proPrice),realname,prodes,Short.parseShort(prostock),Proutil.stringToDate(prodate),Short.valueOf(procateid),profac); pd.addOnePro(product); response.sendRedirect("success.jsp"); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } }
package com.tencent.mm.plugin.sns.model; import com.tencent.mm.g.a.nu; import com.tencent.mm.sdk.b.b; import com.tencent.mm.sdk.b.c; import com.tencent.mm.sdk.platformtools.ah; import com.tencent.mm.sdk.platformtools.x; import java.util.ArrayList; class af$35 extends c<nu> { final /* synthetic */ af nqT; af$35(af afVar) { this.nqT = afVar; this.sFo = nu.class.getName().hashCode(); } public final /* synthetic */ boolean a(b bVar) { nu nuVar = (nu) bVar; ArrayList arrayList = nuVar.bYN.bYO; String str = nuVar.bYN.bYP; x.i("MicroMsg.SnsCore", "ResendSnsByUpdateXmlEvent, try resend sns"); ah.A(new 1(this, arrayList, str)); return false; } }
package com.smxknife.java2._volatile; import java.io.IOException; import java.util.concurrent.TimeUnit; /** * @author smxknife * 2021/5/6 */ public class _01_NoVolatile { private boolean enable = true; public static void main(String[] args) throws IOException { final _01_NoVolatile noVolatile = new _01_NoVolatile(); noVolatile.test(); System.in.read(); } private void test() { new Thread(() -> { while (this.enable) { try { TimeUnit.MILLISECONDS.sleep(500); System.out.println("test2 ..."); } catch (InterruptedException e) { e.printStackTrace(); } } }, "test2").start(); new Thread(() -> { while (this.enable) { try { TimeUnit.MILLISECONDS.sleep(500); System.out.println("test1 ..."); this.enable = false; } catch (InterruptedException e) { e.printStackTrace(); } } }, "test1").start(); } }
package projet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @author MAIA MARNAT MOUTRILLE STINDEL * */ public class Deco extends HttpServlet { private static final long serialVersionUID = 1L; /** * déconnexion à l'application */ public Deco() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { PrintWriter out= res.getWriter(); ConnexionSocket cs = ((ConnexionSocket) req.getSession().getAttribute("ConnexionSocket")); cs.killServeur(); String pseudo = ((String) req.getSession().getAttribute("nom")); Tracker.supprMachine(pseudo); req.getSession().invalidate(); try{ res.sendRedirect("index.html"); } finally {out.close();} } }
package com.yhy.dataservices.dao; import com.yhy.dataservices.dto.ChangeRoleDTO; import com.yhy.dataservices.dto.UserAccessDTO; import com.yhy.dataservices.entity.Role; import org.apache.ibatis.annotations.Param; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface AccessDAO { /** *查询 Role 列表 * @param roleName * @return */ List<Role> getRoleList(@Param("roleName") String roleName); /** * 检验角色的名称,是否使用 * @param name * @return */ Integer checkRoleExist(String name); /** * 新增角色 * @param role * @return */ Boolean addRole(Role role); /** * 删除角色 * @param id * @return */ Boolean deleteRole(Integer id); /** * 根据ID,获取角色 * @param id * @return */ Role getRoleById(Integer id); /** * 更新角色 * @param role * @return */ Boolean updateRole(Role role); /** * 更新的时候,检查是否其他role使用了角色名(不包括自己) */ Integer checkRoleNameExceptMe(@Param("roleName") String RoleName,@Param("id") Integer id); /** * 获取用户权限列表 * @param userName * @return */ List<UserAccessDTO> getUserAccessList(String userName); /** * 获取角色列表下拉框 * @return */ List<ChangeRoleDTO> getChangeRoleList(); /** * 修改用户权限 * @param roleId * @param id * @return */ Boolean updateUserAccess(@Param("roleId") Integer roleId, @Param("id") Integer id); }
package firstPg.services; ; import firstPg.model.Books; import firstPg.model.ReaderView; import firstPg.model.User; import java.awt.*; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.*; import java.util.ArrayList; import java.util.List; import javax.swing.*; public class AddBookCurrentlyLibrary extends JFrame { private User user; public AddBookCurrentlyLibrary(User user) throws FileNotFoundException { this.user = user; setLayout(new BorderLayout()); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setTitle("Currently Reading Library "); setResizable(false); setSize(500, 500); setLocationRelativeTo(null); setVisible(true); this.addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { ReaderView view = new ReaderView(user); view.setVisible(true); dispose(); } }); Container contentPane = this.getContentPane(); contentPane.setLayout(null); Color c = Color.pink; contentPane.setBackground(c); Color cl = Color.lightGray; JPanel panel1 = new JPanel();// top panel panel1.setBounds(0,15,500, 600); panel1.setBackground(c); contentPane.add(panel1); JTable table = new JTable(); String readLine = null; BooksListTableModel tableModel = new BooksListTableModel(); File file = new File("src/main/resources/CurrentlyReadingLibrary"); FileReader reader = new FileReader(file); BufferedReader bufReader = new BufferedReader(reader); List<Books> booksList = new ArrayList<>(); try { while((readLine = bufReader.readLine()) != null) { String[] splitData = readLine.split(","); String userID = splitData[4]; if (userID.trim().equals(String.valueOf(user.getID()))) { Books book = new Books(); book.setTitle(splitData[0]); book.setAuthor(splitData[1]); book.setPublicationYear(splitData[2]); book.setDescription(splitData[3]); booksList.add(book); } } } catch(IOException ex) {} tableModel.setList(booksList); table.setModel(tableModel); Color pink=new Color(255, 230, 235, 255); table.setBackground(pink); table.getTableHeader().setBackground(c); JScrollPane scroll = new JScrollPane(table); scroll.getViewport().setBackground(pink); panel1.add(scroll); } }
/* * 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 Controller; import Modelos.Conexion; import java.util.List; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; /** * * @author Pc */ @Controller public class listadoController { private JdbcTemplate jdbc; public listadoController() { Conexion conexion = new Conexion(); //al objeto jdbc debemos indicarle sobre qué bd va a actuar: this.jdbc = new JdbcTemplate(conexion.conectar()); } @RequestMapping("listado.htm") public ModelAndView listado() { ModelAndView modelandview = new ModelAndView(); String consulta= "select * from motores"; List motores = this.jdbc.queryForList(consulta); modelandview.addObject("motores",motores); modelandview.setViewName("listado"); return modelandview; } }
package com.jinshu.xuzhi.feeling; import android.animation.Animator; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.drawable.BitmapDrawable; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.util.Log; import android.view.LayoutInflater; import android.view.MotionEvent; import android.view.View; import android.view.ViewGroup; import android.view.animation.LinearInterpolator; import android.widget.ImageView; import android.widget.RelativeLayout; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Random; import static com.jinshu.xuzhi.feeling.Util.CONSTANTS_RES_PREFIX; import static com.jinshu.xuzhi.feeling.Util.IMAGE_FILE_NAME; import static com.jinshu.xuzhi.feeling.Util.fishingTag; import static com.jinshu.xuzhi.feeling.Util.mScreenHeight; import static com.jinshu.xuzhi.feeling.Util.mScreenWidth; import static com.jinshu.xuzhi.feeling.Util.zoomImg; import static java.lang.Math.abs; import static java.lang.Math.min; import static java.lang.Math.random; /** * A simple {@link Fragment} subclass. */ public class FragmentFishing extends Fragment { private static View mRootView; private static ImageView fish1,fish2,fish3,fish4,fish5,fish6,fishHook,backArrow; static ObjectAnimator bubblePopUp,popUpAfterMove; static Thread timerThread; static AnimatorSet set; private static BitmapFactory.Options opt; private static ArrayList<Fish> mFishList= new ArrayList<Fish>();; private final String LOG_TAG = this.getClass().getSimpleName(); private static int mClickX,mClickY; private static RelativeLayout mFishingLayout; static FragmentFishing mThis; static Bitmap mTarget; static final MediaPlayer mpBubble = new MediaPlayer(),mpEnough = new MediaPlayer(); private class Fish{ int resourceId = 0; Boolean goRight = true; ImageView fishView = null; boolean beShark = false; Fish(ImageView fishView,int resourceId,Boolean goRight){ this.fishView = fishView; this.resourceId = resourceId; this.beShark = false; this.goRight = goRight; } } /*0.5s repeat timer*/ static Handler handler = new Handler() { public void handleMessage(Message msg) { if (!fishingTag) { super.handleMessage(msg); return; } /*if fish meet the bubble ,bite it*/ int x = (int)(fishHook.getX() + fishHook.getWidth()/2); int y = (int)(fishHook.getY() + fishHook.getHeight()/2); for (Fish fish:mFishList) { biteTheBubble(fish,x,y); } super.handleMessage(msg); } }; public FragmentFishing() { // Required empty public constructor mThis = this; } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment mRootView = inflater.inflate(R.layout.fragment_fishing, container, false); fish1 = (ImageView)mRootView.findViewById(R.id.fish1); fish2 = (ImageView)mRootView.findViewById(R.id.fish2); fish3 = (ImageView)mRootView.findViewById(R.id.fish3); fish4 = (ImageView)mRootView.findViewById(R.id.fish4); fish5 = (ImageView)mRootView.findViewById(R.id.fish5); fish6 = (ImageView)mRootView.findViewById(R.id.fish6); backArrow = (ImageView)mRootView.findViewById(R.id.arrowback); mFishingLayout = (RelativeLayout)mRootView.findViewById(R.id.fishingLayout); mFishList.add(new Fish(fish1,R.drawable.fish1,true)); mFishList.add(new Fish(fish2,R.drawable.fish2,false)); mFishList.add(new Fish(fish3,R.drawable.fish3,false)); mFishList.add(new Fish(fish4,R.drawable.fish4,false)); mFishList.add(new Fish(fish5,R.drawable.fish5,true)); mFishList.add(new Fish(fish6,R.drawable.fish6,true)); fishHook = (ImageView)mRootView.findViewById(R.id.fishhook); mTarget = combineImages(R.drawable.bubble60,R.drawable.example40); fishHook.setImageBitmap(mTarget); fishHook.setTag("fishHook"); opt = new BitmapFactory.Options(); opt.inJustDecodeBounds = true; StartFishAnimation(); bubblePopUp = ObjectAnimator.ofFloat(fishHook,"Y",mScreenHeight + 40,0).setDuration((mScreenHeight + 40)*10); bubblePopUp.start(); fishingTag = true; timerThread = new Thread(new MyThread()); timerThread.start(); mpBubble.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { public void onPrepared(MediaPlayer mp) { mp.start(); } }); mpEnough.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { public void onPrepared(MediaPlayer mp) { mp.start(); } }); mRootView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View view, MotionEvent motionEvent) { switch(motionEvent.getAction()) { case MotionEvent.ACTION_UP: mClickX = min((int) motionEvent.getX(),mScreenWidth - fishHook.getWidth()) ; mClickY = min((int) motionEvent.getY(),mScreenHeight - fishHook.getHeight()); /*if any animation not finished stop it */ if ((set != null) &&(set.isRunning())) set.cancel(); if ((bubblePopUp != null) &&(bubblePopUp.isRunning())) bubblePopUp.cancel(); if ((popUpAfterMove != null) &&(popUpAfterMove.isRunning())) popUpAfterMove.cancel(); /*Move fishhook to destination*/ long yDistance = (long)abs(fishHook.getY()-mClickY); long xDistance = (long)abs(fishHook.getX()-mClickX); //Log.v(LOG_TAG,"fishHook x = " + fishHook.getX() + ",fishHook y = "+ fishHook.getY() ); //Log.v(LOG_TAG,"mClickX = " + mClickX + ",mClickY = "+ mClickY ); long speed = yDistance > xDistance? yDistance:xDistance; ObjectAnimator clickY = ObjectAnimator.ofFloat(fishHook,"Y",mClickY).setDuration(speed *5); ObjectAnimator clickX = ObjectAnimator.ofFloat(fishHook,"X", mClickX).setDuration(speed *5); //Log.v(LOG_TAG,"move duration" + speed); set = new AnimatorSet(); set.addListener(new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animator) { } @Override public void onAnimationEnd(Animator animator) { popUpAfterMove = ObjectAnimator.ofFloat(fishHook,"Y",0).setDuration((long)abs(fishHook.getY()) * 10); popUpAfterMove.start(); } @Override public void onAnimationCancel(Animator animator) { } @Override public void onAnimationRepeat(Animator animator) { } }); set.playTogether(clickY, clickX); set.setInterpolator(new LinearInterpolator()); set.start(); break; } return true; } }); backArrow.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Fragment f = getActivity().getSupportFragmentManager().findFragmentById(R.id.fragment); if (f instanceof com.jinshu.xuzhi.feeling.MenuFragment) { return; } Fragment fragment = new com.jinshu.xuzhi.feeling.MenuFragment(); FragmentManager manager = getActivity().getSupportFragmentManager(); FragmentTransaction transaction = manager.beginTransaction(); transaction.replace(R.id.fragment, fragment); transaction.commit(); } }); return mRootView; } int getRandomDuration() { return (int)((new Random().nextInt(10) + 4) * 1000); } void startFishSwimAnimation(int drawableId,final ImageView fish,Boolean goRight) { BitmapFactory.decodeResource(getResources(), drawableId, opt); /******************define animation ***********************/ /*from left to right*/ final ObjectAnimator swim2Right = ObjectAnimator.ofFloat(fish,"X",(float)(-opt.outWidth *4), (float)(mScreenWidth + opt.outWidth *4)); swim2Right.setInterpolator(new LinearInterpolator()); /*from right to left*/ final ObjectAnimator swim2Left = ObjectAnimator.ofFloat(fish,"X", (float)(mScreenWidth + opt.outWidth *4),(float)(-opt.outWidth *4)); swim2Left.setInterpolator(new LinearInterpolator()); /*turn*/ final ObjectAnimator turn180Degree = ObjectAnimator.ofFloat(fish, "rotationY", 0.0F, 180.0F); final ObjectAnimator turnBack = ObjectAnimator.ofFloat(fish, "rotationY",180.0F, 360.0F); /************define listener *************/ Animator.AnimatorListener turn180DegreeListener = new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animator) { } @Override public void onAnimationEnd(Animator animator) { fish.setY((int)(Math.random() * (mScreenHeight - opt.outHeight *2))); turn180Degree.start(); } @Override public void onAnimationCancel(Animator animator) { } @Override public void onAnimationRepeat(Animator animator) { } }; Animator.AnimatorListener turnBackListener = new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animator) { } @Override public void onAnimationEnd(Animator animator) { fish.setY((int)(Math.random() * (mScreenHeight - opt.outHeight *2))); turnBack.start(); } @Override public void onAnimationCancel(Animator animator) { } @Override public void onAnimationRepeat(Animator animator) { } }; Animator.AnimatorListener swim2RightListener = new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animator) { } @Override public void onAnimationEnd(Animator animator) { swim2Right.setDuration(getRandomDuration()); swim2Right.start(); } @Override public void onAnimationCancel(Animator animator) { } @Override public void onAnimationRepeat(Animator animator) { } }; Animator.AnimatorListener swim2LeftListener = new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animator) { } @Override public void onAnimationEnd(Animator animator) { swim2Left.setDuration(getRandomDuration()); swim2Left.start(); } @Override public void onAnimationCancel(Animator animator) { } @Override public void onAnimationRepeat(Animator animator) { } }; /*setup listeners and start animation*/ if (goRight) { swim2Right.addListener(turn180DegreeListener); turn180Degree.addListener(swim2LeftListener); swim2Left.addListener(turnBackListener); turnBack.addListener(swim2RightListener); swim2Right.setDuration(getRandomDuration()); swim2Right.start(); } else { swim2Left.addListener(turn180DegreeListener); turn180Degree.addListener(swim2RightListener); swim2Right.addListener(turnBackListener); turnBack.addListener(swim2LeftListener); swim2Left.setDuration(getRandomDuration()); swim2Left.start(); } } void StartFishAnimation(){ for (Fish fish:mFishList) { startFishSwimAnimation(fish.resourceId,fish.fishView,fish.goRight); } } private Bitmap combineImages(int backgroundId, int foregroundId) { Bitmap mergeImage = null,imageBackground = null,imageForeground = null; try { BitmapDrawable drawableBackground = (BitmapDrawable)getActivity().getResources().getDrawable(backgroundId); BitmapDrawable drawableForeground = (BitmapDrawable)getActivity().getResources().getDrawable(foregroundId); imageBackground = drawableBackground.getBitmap(); imageForeground = drawableForeground.getBitmap(); } catch (Exception e) { e.printStackTrace(); } File file = new File(Environment.getExternalStorageDirectory(), IMAGE_FILE_NAME); if (file.exists()) { Bitmap bitmap = null; try { // 先通过getContentResolver方法获得一个ContentResolver实例, // 调用openInputStream(Uri)方法获得uri关联的数据流stream // 把上一步获得的数据流解析成为bitmap bitmap = BitmapFactory.decodeStream(getActivity().getContentResolver().openInputStream(Uri.fromFile(file))); } catch (FileNotFoundException e) { e.printStackTrace(); return null; } // 设置缩放过的图片为foreground图片 imageForeground = zoomImg(bitmap,70,70); } mergeImage = Bitmap.createBitmap(imageBackground.getWidth(), imageBackground.getHeight(), Bitmap.Config.ARGB_8888); Canvas comboImage = new Canvas(mergeImage); Paint paint = new Paint(); paint.setAlpha(100); comboImage.drawBitmap(imageBackground, 0f, 0f, null); comboImage.drawBitmap(imageForeground, (imageBackground.getWidth()/2 - imageForeground.getWidth()/2), (imageBackground.getHeight() - imageForeground.getHeight() - 20), paint); return mergeImage; } public static void biteTheBubble(Fish fish,int x,int y) { ImageView fishView = fish.fishView; int sharkId = fish.goRight?R.drawable.sharkright:R.drawable.sharkleft; if ((abs((fishView.getX()+ fishView.getWidth()/2) - x) < 40) && (abs((fishView.getY() + fishView.getHeight()/2) - y) < 40)) { fishView.setImageResource(sharkId); fish.beShark = true; /*delete fishhook view ,play audio,popup a new fishhook*/ ImageView fishhook = (ImageView) mRootView.findViewWithTag("fishHook"); try { mpBubble.reset(); int id = mThis.getActivity().getResources().getIdentifier("bite", "raw", "com.jinshu.xuzhi.feeling"); String uriString = CONSTANTS_RES_PREFIX + Integer.toString(id); //Log.v(LOG_TAG,uriString); mpBubble.setDataSource(mThis.getActivity(), Uri.parse(uriString)); mpBubble.prepareAsync(); } catch (IOException e) { e.printStackTrace(); } mFishingLayout.removeView(fishhook); ImageView newFishhook = new ImageView(mThis.getActivity()); newFishhook.setImageBitmap(mTarget); newFishhook.setTag("fishHook"); RelativeLayout.LayoutParams params1 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT); params1.leftMargin = (int)(random() * (mScreenWidth - mTarget.getWidth())); params1.topMargin = mScreenHeight/2; mFishingLayout.addView(newFishhook,params1); fishHook = newFishhook; bubblePopUp = ObjectAnimator.ofFloat(fishHook,"Y",mScreenHeight + 40,0).setDuration((mScreenHeight + 40)*10); bubblePopUp.start(); } else if (fish.beShark) { fishView.setImageResource(fish.resourceId); fish.beShark = false; try { mpEnough.reset(); int id = mThis.getActivity().getResources().getIdentifier("yisell", "raw", "com.jinshu.xuzhi.feeling"); String uriString = CONSTANTS_RES_PREFIX + Integer.toString(id); //Log.v(LOG_TAG,uriString); mpEnough.setDataSource(mThis.getActivity(), Uri.parse(uriString)); mpEnough.prepareAsync(); } catch (IOException e) { e.printStackTrace(); } } } @Override public void onDestroy() { fishingTag = false; mpBubble.release(); mpEnough.release(); Log.v(LOG_TAG, "onDestroy"); super.onDestroy(); } }
package com.tencent.mm.plugin.wxcredit.ui; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import com.tencent.mm.plugin.wallet_core.ui.WalletCardSelectUI; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.wallet_core.a; class WalletBindDepositUI$1 implements OnClickListener { final /* synthetic */ WalletBindDepositUI qwM; WalletBindDepositUI$1(WalletBindDepositUI walletBindDepositUI) { this.qwM = walletBindDepositUI; } public final void onClick(View view) { if (!bi.oW(WalletBindDepositUI.a(this.qwM).getText())) { if (WalletBindDepositUI.b(this.qwM)) { this.qwM.cDL().s(new Object[]{r0}); WalletBindDepositUI.c(this.qwM); return; } Bundle bundle = new Bundle(); bundle.putInt("key_support_bankcard", 1); bundle.putString("key_bank_type", WalletBindDepositUI.d(this.qwM).lMV); bundle.putInt("key_bankcard_type", 1); a.af(this.qwM).a(this.qwM, WalletCardSelectUI.class, bundle, 1); } } }
package android.support.design.widget; import android.support.design.widget.j.a; class j$b extends a { final /* synthetic */ j fB; private j$b(j jVar) { this.fB = jVar; super(jVar, (byte) 0); } /* synthetic */ j$b(j jVar, byte b) { this(jVar); } protected final float ap() { return this.fB.fK + this.fB.fL; } }
package com.takshine.wxcrm.domain; import com.takshine.wxcrm.model.AccessLogsModel; /** * 访问日志 * @author liulin * */ public class AccessLogs extends AccessLogsModel{ private String startDate = null; private String endDate = null; private Integer currpages = 1; private Integer pagecounts = 10; private Integer accessCount = 0; private String accessModule = null; private String opName = null; private String addoppty = null; private String addtask = null; private String addcustomer = null ; private String addcontract = null ; public String getOpName() { return opName; } public void setOpName(String opName) { this.opName = opName; } public String getAccessModule() { return accessModule; } public void setAccessModule(String accessModule) { this.accessModule = accessModule; } public Integer getAccessCount() { return accessCount; } public void setAccessCount(Integer accessCount) { this.accessCount = accessCount; } public String getStartDate() { return startDate; } public void setStartDate(String startDate) { this.startDate = startDate; } public String getEndDate() { return endDate; } public void setEndDate(String endDate) { this.endDate = endDate; } public Integer getCurrpages() { return currpages; } public void setCurrpages(Integer currpages) { this.currpages = currpages; } public Integer getPagecounts() { return pagecounts; } public void setPagecounts(Integer pagecounts) { this.pagecounts = pagecounts; } public String getAddoppty() { return addoppty; } public void setAddoppty(String addoppty) { this.addoppty = addoppty; } public String getAddtask() { return addtask; } public void setAddtask(String addtask) { this.addtask = addtask; } public String getAddcustomer() { return addcustomer; } public void setAddcustomer(String addcustomer) { this.addcustomer = addcustomer; } public String getAddcontract() { return addcontract; } public void setAddcontract(String addcontract) { this.addcontract = addcontract; } }
package com.duanxr.yith.easy; /** * @author Duanran 2019/2/22 0022 */ public class ExcelSheetColumnTitle { /** * Given a positive integer, return its corresponding column title as appear in an Excel sheet. * * For example: * * 1 -> A * * 2 -> B * * 3 -> C * * ... * * 26 -> Z * * 27 -> AA * * 28 -> AB * * ... * * Example 1: * * Input: 1 * * Output: "A" * * Example 2: * * Input: 28 * * Output: "AB" * * Example 3: * * Input: 701 * * Output: "ZY" * * 给定一个正整数,返回它在 Excel 表中相对应的列名称。 * * 例如, * * 1 -> A * * 2 -> B * * 3 -> C * * ... * * 26 -> Z * * 27 -> AA * * 28 -> AB * * ... * * 示例 1: * * 输入: 1 * * 输出: "A" * * 示例 2: * * 输入: 28 * * 输出: "AB" * * 示例 3: * * 输入: 701 * * 输出: "ZY" */ class Solution { public String convertToTitle(int n) { StringBuilder sb = new StringBuilder(); while (n != 0) { int bit = n % 26; n /= 26; char c = getChar(bit); if (bit == 0) { c = 'Z'; n--; } sb.append(c); } return sb.reverse().toString(); } private char getChar(int n) { return (char) ('A' + (n) - 1); } } }
package com.cmpickle.volumize.data.db.platform; import android.app.Application; import com.raizlabs.android.dbflow.config.DatabaseConfig; import com.raizlabs.android.dbflow.config.FlowConfig; import com.raizlabs.android.dbflow.config.FlowManager; import javax.inject.Inject; import javax.inject.Singleton; /** * @author Cameron Pickle * Copyright (C) Cameron Pickle (cmpickle) on 4/3/2017. */ @Singleton public class DatabaseInitializer { @Inject public DatabaseInitializer() { } public final void init(Application application, Class<? extends BaseDatabase>... databaseTypes) { // System.loadLibrary("sqliteX"); FlowConfig.Builder flowConfigBuilder = new FlowConfig.Builder(application); for(Class<? extends BaseDatabase> databaseType : databaseTypes) { DatabaseConfig databaseConfig = new DatabaseConfig.Builder(databaseType) .build(); flowConfigBuilder.addDatabaseConfig(databaseConfig); } FlowConfig flowConfig = flowConfigBuilder.openDatabasesOnInit(true).build(); FlowManager.init(flowConfig); } }
package jdbchomework.dao.hibernate; import jdbchomework.dao.model.CompaniesDao; import jdbchomework.entity.Company; import jdbchomework.entity.Developer; import jdbchomework.exceptions.DbConnectionException; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.query.NativeQuery; import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.List; public class CompaniesHibDao extends AbstractHibDao<Company> implements CompaniesDao { private org.slf4j.Logger log = LoggerFactory.getLogger(CompaniesHibDao.class); public CompaniesHibDao(String entityName, SessionFactory sessionFactory, Class<Company> clazz) { super(entityName, sessionFactory, clazz); } public List<Developer> getCompanyDevelopers(long id) { List result = new ArrayList<>(); try (Session session = sessionFactory.openSession()) { try { session.beginTransaction(); String sql = "select * from developers" + " inner join projects on projects.id = developers.project_id" + " inner join companies on companies.id = projects.company_id" + " where companies.id = :id"; NativeQuery query = session.createNativeQuery(sql); query.addEntity(Developer.class); query.setParameter("id", id); result.addAll(query.list()); session.getTransaction().commit(); } catch (HibernateException e) { session.getTransaction().rollback(); log.error(CANNOT_CONNECT_TO_DB, e); throw new DbConnectionException(CANNOT_CONNECT_TO_DB, e); } } return result; } }
package root.resource; import root.entity.BacklogItem; import root.entity.BacklogItemStatus; import root.entity.Sprint; import root.exception.ChangeItemStatusException; import root.exception.SprintStartException; import root.exception.UpdateBacklogException; import root.service.BacklogItemService; import root.service.SprintService; import javax.inject.Inject; import javax.ws.rs.*; import javax.ws.rs.core.GenericEntity; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.net.URI; import java.util.List; @Path("/sprints") public class SprintResource { @Inject private SprintService sprintService; @Inject private BacklogItemService backlogItemService; @GET @Path("/{id}") @Produces(MediaType.APPLICATION_JSON) public Response getSprint(@PathParam("id") long sprintId) { return Response.ok().entity(sprintService.findById(sprintId)).build(); } @GET @Produces(MediaType.APPLICATION_JSON) public Response getSprints() { return Response.ok().entity(new GenericEntity<List<Sprint>>(sprintService.findAll()) { }).build(); } @PUT @Path("/{id}/finished") public Response finishSprint(@PathParam("id") long sprintId) { sprintService.finish(sprintId); return Response.accepted().build(); } @PUT @Path("/{id}/backlogitems/{backlogItemId}/status/{status}") public Response changeBacklogItemStatus(@PathParam("id") long sprintId, @PathParam("backlogItemId") long backlogItemId, @PathParam("status") BacklogItemStatus status) throws ChangeItemStatusException { backlogItemService.status(backlogItemId, status); return Response.accepted().build(); } @PUT @Path("/{id}/started") public Response startSprint(@PathParam("id") long sprintId) throws SprintStartException { sprintService.start(sprintId); return Response.accepted().build(); } @POST @Consumes(MediaType.APPLICATION_JSON) public Response addSprint(Sprint sprint) { sprintService.insert(sprint); return Response.created(URI.create("/sprints/" + sprint.getId())).build(); } @POST @Path("/{id}/backlogitems") @Consumes(MediaType.APPLICATION_JSON) public Response addBacklogItem(@PathParam("id") long sprintId, BacklogItem backlogItem) throws UpdateBacklogException { backlogItemService.insertInSprint(backlogItem, sprintId); return Response.created(URI.create("/sprints/" + sprintId + "/backlogitems/" + backlogItem.getId())).build(); } @PUT @Path("/{id}/backlogitems/{backlogItemId}") @Consumes(MediaType.APPLICATION_JSON) public Response addBacklogItem(@PathParam("id") long sprintId, @PathParam("backlogItemId") long backlogItemId, BacklogItem backlogItem) throws UpdateBacklogException, ChangeItemStatusException { backlogItemService.updateInSprint(backlogItem, sprintId); return Response.created(URI.create("/sprints/" + sprintId + "/backlogitems/" + backlogItem.getId())).build(); } @GET @Path("/{id}/backlogitems") @Produces(MediaType.APPLICATION_JSON) public Response getSprintBacklog(@PathParam("id") long sprintId) { return Response.ok().entity(new GenericEntity<List<BacklogItem>>(backlogItemService.findBySprintId(sprintId)) { }).build(); } }
/** * Paintroid: An image manipulation application for Android. * Copyright (C) 2010-2013 The Catrobat Team * (<http://developer.catrobat.org/credits>) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.catrobat.paintroid.test.junit.tools; import org.catrobat.paintroid.PaintroidApplication; import org.catrobat.paintroid.test.utils.PrivateAccess; import org.catrobat.paintroid.tools.ToolType; import org.catrobat.paintroid.tools.implementation.BaseToolWithRectangleShape; import org.catrobat.paintroid.tools.implementation.BaseToolWithShape; import org.junit.Before; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.Canvas; import android.graphics.PointF; public class BaseToolWithRectangleShapeToolTest extends BaseToolTest { private static final String TOOL_MEMBER_WIDTH = "mBoxWidth"; private static final String TOOL_MEMBER_HEIGHT = "mBoxHeight"; private static final String TOOL_MEMBER_POSITION = "mToolPosition"; private static final String TOOL_MEMBER_RESPECT_BOUNDS = "mRespectImageBounds"; private static final String TOOL_MEMBER_BOX_RESIZE_MARGIN = "DEFAULT_BOX_RESIZE_MARGIN"; private static final String TOOL_MEMBER_ROTATION = "mBoxRotation"; private static final String TOOL_MEMBER_ROTATION_ENABLED = "mRotationEnabled"; private static final int RESIZE_MOVE_DISTANCE = 50; private static final int X_OFFSET = 5; private static final int Y_OFFSET = 40; private float mScreenWidth = 1; private float mScreenHeight = 1; public BaseToolWithRectangleShapeToolTest() { super(); } @Override @Before protected void setUp() throws Exception { mToolToTest = new BaseToolWithRectangleShapeImpl(getActivity(), ToolType.NONE); super.setUp(); mScreenWidth = getActivity().getWindowManager().getDefaultDisplay().getWidth(); mScreenHeight = getActivity().getWindowManager().getDefaultDisplay().getHeight(); } public void testResizeRectangle() throws SecurityException, IllegalArgumentException, NoSuchFieldException, IllegalAccessException, InterruptedException { float rectWidth = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, mToolToTest, TOOL_MEMBER_WIDTH); float rectHeight = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, mToolToTest, TOOL_MEMBER_HEIGHT); PointF rectPosition = (PointF) PrivateAccess.getMemberValue(BaseToolWithShape.class, mToolToTest, TOOL_MEMBER_POSITION); // resize bigger top left only on Y-coordinate float dragFromX = rectPosition.x - rectWidth / 2; float dragToX = dragFromX; float dragFromY = rectPosition.y - rectHeight / 2; float dragToY = dragFromY - RESIZE_MOVE_DISTANCE; doResize(dragFromX, dragToX, dragFromY, dragToY, true, true, true, true); // resize smaller top left only on Y-coordinate dragToX = dragFromX; dragToY = dragFromY + RESIZE_MOVE_DISTANCE; doResize(dragFromX, dragToX, dragFromY, dragToY, true, true, false, true); // resize bigger top left only on X-coordinate dragToX = dragFromX - RESIZE_MOVE_DISTANCE; dragToY = dragFromY; doResize(dragFromX, dragToX, dragFromY, dragToY, true, true, true, true); // resize smaller top left only on X-coordinate dragToX = dragFromX + RESIZE_MOVE_DISTANCE; dragToY = dragFromY; doResize(dragFromX, dragToX, dragFromY, dragToY, true, true, false, true); // resize bigger top center dragFromX = rectPosition.x; dragToX = dragFromX; dragToY = dragFromY - RESIZE_MOVE_DISTANCE; doResize(dragFromX, dragToX, dragFromY, dragToY, false, true, true, false); // resize smaller top center; dragToY = dragFromY + RESIZE_MOVE_DISTANCE; doResize(dragFromX, dragToX, dragFromY, dragToY, false, true, false, false); // resize bigger top right dragFromX = rectPosition.x + rectWidth / 2; dragToX = dragFromX + RESIZE_MOVE_DISTANCE; dragToY = dragFromY - RESIZE_MOVE_DISTANCE / 2; doResize(dragFromX, dragToX, dragFromY, dragToY, true, true, true, true); // resize smaller top right dragToX = dragFromX - RESIZE_MOVE_DISTANCE / 2; dragToY = dragFromY + RESIZE_MOVE_DISTANCE; doResize(dragFromX, dragToX, dragFromY, dragToY, true, true, false, true); // resize bigger center right dragToX = dragFromX + RESIZE_MOVE_DISTANCE; dragFromY = rectPosition.y; dragToY = dragFromY; doResize(dragFromX, dragToX, dragFromY, dragToY, true, false, true, false); // resize smaller center right dragToX = dragFromX - RESIZE_MOVE_DISTANCE; doResize(dragFromX, dragToX, dragFromY, dragToY, true, false, false, false); // resize bigger bottom right dragToX = dragFromX + RESIZE_MOVE_DISTANCE; dragFromY = rectPosition.y + rectHeight / 2; dragToY = dragFromY + RESIZE_MOVE_DISTANCE; doResize(dragFromX, dragToX, dragFromY, dragToY, true, true, true, true); // resize smaller bottom right dragToX = dragFromX - RESIZE_MOVE_DISTANCE; dragToY = dragFromY - RESIZE_MOVE_DISTANCE; doResize(dragFromX, dragToX, dragFromY, dragToY, true, true, false, true); // resize bigger bottom center dragFromX = rectPosition.x; dragToX = dragFromX; dragToY = dragFromY + RESIZE_MOVE_DISTANCE; doResize(dragFromX, dragToX, dragFromY, dragToY, false, true, true, false); // resize smaller bottom center dragToY = dragFromY - RESIZE_MOVE_DISTANCE; doResize(dragFromX, dragToX, dragFromY, dragToY, false, true, false, false); // resize bigger bottom left only on Y-coordinate dragFromX = rectPosition.x - rectWidth / 2; dragFromY = rectPosition.y + rectHeight / 2; dragToX = dragFromX; dragToY = dragFromY + RESIZE_MOVE_DISTANCE; doResize(dragFromX, dragToX, dragFromY, dragToY, true, true, true, true); // resize smaller bottom left only on Y-coordinate dragToX = dragFromX; dragToY = dragFromY - RESIZE_MOVE_DISTANCE; doResize(dragFromX, dragToX, dragFromY, dragToY, true, true, false, true); // resize bigger bottom left only on X-coordinate dragToX = dragFromX - RESIZE_MOVE_DISTANCE; dragToY = dragFromY; doResize(dragFromX, dragToX, dragFromY, dragToY, true, true, true, true); // resize smaller bottom left only on X-coordinate dragToX = dragFromX + RESIZE_MOVE_DISTANCE; dragToY = dragFromY; doResize(dragFromX, dragToX, dragFromY, dragToY, true, true, false, true); // resize bigger center left dragToX = dragFromX - RESIZE_MOVE_DISTANCE; dragFromY = rectPosition.y; dragToY = dragFromY; doResize(dragFromX, dragToX, dragFromY, dragToY, true, false, true, false); // resize smaller center left dragToX = dragFromX + RESIZE_MOVE_DISTANCE; doResize(dragFromX, dragToX, dragFromY, dragToY, true, false, false, false); } public void testResizeRectangleMinimumSizeBiggerThanMargin() throws SecurityException, IllegalArgumentException, NoSuchFieldException, IllegalAccessException, InterruptedException { float rectWidth = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, mToolToTest, TOOL_MEMBER_WIDTH); float rectHeight = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, mToolToTest, TOOL_MEMBER_HEIGHT); PointF rectPosition = (PointF) PrivateAccess.getMemberValue(BaseToolWithShape.class, mToolToTest, TOOL_MEMBER_POSITION); float dragFromX = rectPosition.x - rectWidth / 2; float dragToX = dragFromX + rectWidth + RESIZE_MOVE_DISTANCE; float dragFromY = rectPosition.y - rectHeight / 2; float dragToY = dragFromY + rectHeight + RESIZE_MOVE_DISTANCE; mToolToTest.handleDown(new PointF(dragFromX, dragFromY)); mToolToTest.handleMove(new PointF(dragToX, dragToY)); mToolToTest.handleUp(new PointF(dragToX, dragToY)); float newWidth = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, mToolToTest, TOOL_MEMBER_WIDTH); float newHeight = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, mToolToTest, TOOL_MEMBER_HEIGHT); float boxResizeMargin = (Integer) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, mToolToTest, TOOL_MEMBER_BOX_RESIZE_MARGIN); assertTrue("new width should be bigger or equal to the resize margin", newWidth >= boxResizeMargin); assertTrue("new height should be bigger or equal to the resize margin", newHeight >= boxResizeMargin); } public void testMoveRectangle() throws SecurityException, IllegalArgumentException, NoSuchFieldException, IllegalAccessException, InterruptedException { float rectWidth = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, mToolToTest, TOOL_MEMBER_WIDTH); float rectHeight = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, mToolToTest, TOOL_MEMBER_HEIGHT); PointF rectPosition = (PointF) PrivateAccess.getMemberValue(BaseToolWithShape.class, mToolToTest, TOOL_MEMBER_POSITION); float dragFromX = rectPosition.x; float dragToX = dragFromX + RESIZE_MOVE_DISTANCE; float dragFromY = rectPosition.y; float dragToY = dragFromY + RESIZE_MOVE_DISTANCE; mToolToTest.handleDown(new PointF(dragFromX, dragFromY)); mToolToTest.handleMove(new PointF(dragToX, dragToY)); mToolToTest.handleUp(new PointF(dragToX, dragToY)); float newWidth = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, mToolToTest, TOOL_MEMBER_WIDTH); float newHeight = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, mToolToTest, TOOL_MEMBER_HEIGHT); PointF newPosition = (PointF) PrivateAccess.getMemberValue(BaseToolWithShape.class, mToolToTest, TOOL_MEMBER_POSITION); assertTrue("width should be the same", rectWidth == newWidth); assertTrue("height should be the same", rectHeight == newHeight); assertTrue("position should have moved", (newPosition.x == dragToX) && (newPosition.y == dragToY)); } public void testMoveRectangleRespectBorders() throws SecurityException, IllegalArgumentException, NoSuchFieldException, IllegalAccessException, InterruptedException { PrivateAccess.setMemberValue(BaseToolWithRectangleShape.class, mToolToTest, TOOL_MEMBER_RESPECT_BOUNDS, true); float rectWidth = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, mToolToTest, TOOL_MEMBER_WIDTH); float rectHeight = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, mToolToTest, TOOL_MEMBER_HEIGHT); PointF rectPosition = (PointF) PrivateAccess.getMemberValue(BaseToolWithShape.class, mToolToTest, TOOL_MEMBER_POSITION); float dragFromX = rectPosition.x; float dragToX = rectPosition.x - mScreenWidth; float dragFromY = rectPosition.y; float dragToY = rectPosition.y - mScreenHeight; mToolToTest.handleDown(new PointF(dragFromX, dragFromY)); mToolToTest.handleMove(new PointF(dragToX, dragToY)); mToolToTest.handleUp(new PointF(dragToX, dragToY)); float newWidth = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, mToolToTest, TOOL_MEMBER_WIDTH); float newHeight = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, mToolToTest, TOOL_MEMBER_HEIGHT); PointF newPosition = (PointF) PrivateAccess.getMemberValue(BaseToolWithShape.class, mToolToTest, TOOL_MEMBER_POSITION); assertEquals("old width should be same as new width", rectWidth, newWidth); assertEquals("old height should be same as new height", rectHeight, newHeight); assertEquals("rectangle should be top left: x ", rectWidth / 2, newPosition.x); assertEquals("rectangle should be top left: y", rectHeight / 2, newPosition.y); } public void testRectangleSizeMaximumWhenZoomed() throws SecurityException, IllegalArgumentException, NoSuchFieldException, IllegalAccessException { float scale = 0.8f; PaintroidApplication.perspective.setScale(scale); mToolToTest = new BaseToolWithRectangleShapeImpl(getActivity(), ToolType.NONE); float width = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, mToolToTest, TOOL_MEMBER_WIDTH); float height = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, mToolToTest, TOOL_MEMBER_HEIGHT); assertEquals("Width and Height should be the same with activating Rectangletool on low zoom out", width, height); scale = 0.15f; PaintroidApplication.perspective.setScale(scale); mToolToTest = new BaseToolWithRectangleShapeImpl(getActivity(), ToolType.NONE); width = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, mToolToTest, TOOL_MEMBER_WIDTH); height = (Float) PrivateAccess .getMemberValue(BaseToolWithRectangleShape.class, mToolToTest, TOOL_MEMBER_HEIGHT); assertNotSame( "With zooming out a lot, height and width should not be the same anymore and adjust the ratio to the drawinSurface", width, height); scale = 0.1f; PaintroidApplication.perspective.setScale(scale); mToolToTest = new BaseToolWithRectangleShapeImpl(getActivity(), ToolType.NONE); float newWidth = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, mToolToTest, TOOL_MEMBER_WIDTH); float newHeight = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, mToolToTest, TOOL_MEMBER_HEIGHT); assertEquals( "After zooming out a little more (from already beeing zoomed out a lot), width should stay the same", newWidth, width); assertEquals( "After zooming out a little more (from already beeing zoomed out a lot), height should stay the same", newHeight, height); } public void testRectangleSizeChangeWhenZoomedLevel1ToLevel2() throws SecurityException, IllegalArgumentException, NoSuchFieldException, IllegalAccessException { float scale = 1f; PaintroidApplication.perspective.setScale(scale); BaseToolWithRectangleShape rectTool1 = new BaseToolWithRectangleShapeImpl(getActivity(), null); Float rectWidthZoom1 = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, rectTool1, TOOL_MEMBER_WIDTH); Float rectHeightZoom1 = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, rectTool1, TOOL_MEMBER_HEIGHT); scale = 2f; PaintroidApplication.perspective.setScale(scale); try { Thread.sleep(3000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } BaseToolWithRectangleShape rectTool2 = new BaseToolWithRectangleShapeImpl(getActivity(), null); Float rectWidthZoom2 = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, rectTool2, TOOL_MEMBER_WIDTH); Float rectHeightZoom2 = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, rectTool2, TOOL_MEMBER_HEIGHT); assertTrue("rectangle should be smaller with scale 2", (rectWidthZoom1.floatValue() > rectWidthZoom2.floatValue()) && (rectHeightZoom1.floatValue() > rectHeightZoom2.floatValue())); } public void testRectangleSizeChangeWhenZoomedLevel1ToLevel05() throws SecurityException, IllegalArgumentException, NoSuchFieldException, IllegalAccessException { float scale = 1f; PaintroidApplication.perspective.setScale(scale); BaseToolWithRectangleShape rectTool1 = new BaseToolWithRectangleShapeImpl(getActivity(), null); Float rectWidthZoom1 = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, rectTool1, TOOL_MEMBER_WIDTH); Float rectHeightZoom1 = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, rectTool1, TOOL_MEMBER_HEIGHT); scale = 0.5f; PaintroidApplication.perspective.setScale(scale); BaseToolWithRectangleShape rectTool05 = new BaseToolWithRectangleShapeImpl(getActivity(), null); Float rectWidthZoom05 = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, rectTool05, TOOL_MEMBER_WIDTH); Float rectHeightZoom05 = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, rectTool05, TOOL_MEMBER_HEIGHT); assertTrue("rectangle should be bigger with scale 0.5", (rectWidthZoom1.floatValue() < rectWidthZoom05.floatValue()) && (rectHeightZoom1.floatValue() < rectHeightZoom05.floatValue())); } public void testRotateRectangle() throws SecurityException, IllegalArgumentException, NoSuchFieldException, IllegalAccessException, InterruptedException { PointF position = (PointF) PrivateAccess.getMemberValue(BaseToolWithShape.class, mToolToTest, TOOL_MEMBER_POSITION); PrivateAccess.setMemberValue(BaseToolWithRectangleShape.class, mToolToTest, TOOL_MEMBER_ROTATION_ENABLED, true); mToolToTest.handleDown(position); mToolToTest.handleUp(position); float rotation = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, mToolToTest, TOOL_MEMBER_ROTATION); // try rotate right mToolToTest.handleDown(new PointF(X_OFFSET, Y_OFFSET)); mToolToTest.handleMove(new PointF(mScreenWidth / 2, Y_OFFSET + 30)); mToolToTest.handleUp(new PointF(mScreenWidth / 2, Y_OFFSET + 30)); float newRotation = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, mToolToTest, TOOL_MEMBER_ROTATION); assertTrue("Rotation value should be bigger after rotating.", rotation < newRotation); // try rotate left rotation = newRotation; mToolToTest.handleDown(new PointF(mScreenWidth / 2, Y_OFFSET)); mToolToTest.handleMove(new PointF(X_OFFSET, Y_OFFSET + 30)); mToolToTest.handleUp(new PointF(X_OFFSET, Y_OFFSET + 30)); newRotation = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, mToolToTest, TOOL_MEMBER_ROTATION); assertTrue("Rotation value should be smaller after rotating.", rotation > newRotation); // try rotate even more left (start from bottom of screen) rotation = newRotation; mToolToTest.handleDown(new PointF(mScreenWidth - X_OFFSET, mScreenWidth / 2)); mToolToTest.handleMove(new PointF(mScreenWidth - X_OFFSET, Y_OFFSET)); mToolToTest.handleUp(new PointF(mScreenWidth - X_OFFSET, Y_OFFSET)); newRotation = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, mToolToTest, TOOL_MEMBER_ROTATION); assertTrue("Rotation value should be smaller after rotating.", rotation > newRotation); // and now a lot to the right rotation = newRotation; mToolToTest.handleDown(new PointF(X_OFFSET, mScreenHeight / 2)); mToolToTest.handleMove(new PointF(X_OFFSET * 2, Y_OFFSET)); mToolToTest.handleUp(new PointF(X_OFFSET * 2, Y_OFFSET)); mToolToTest.handleDown(new PointF(mScreenWidth / 2, Y_OFFSET)); mToolToTest.handleMove(new PointF(mScreenWidth - X_OFFSET * 2, Y_OFFSET * 2)); mToolToTest.handleUp(new PointF(mScreenWidth - X_OFFSET * 2, Y_OFFSET * 2)); newRotation = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, mToolToTest, TOOL_MEMBER_ROTATION); assertTrue("Rotation value should be smaller after rotating.", rotation < newRotation); } private void doResize(float dragFromX, float dragToX, float dragFromY, float dragToY, boolean resizeWidth, boolean resizeHeight, boolean resizeBigger, boolean isCorner) throws SecurityException, IllegalArgumentException, NoSuchFieldException, IllegalAccessException, InterruptedException { float rectWidth = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, mToolToTest, TOOL_MEMBER_WIDTH); float rectHeight = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, mToolToTest, TOOL_MEMBER_HEIGHT); PointF rectPosition = (PointF) PrivateAccess.getMemberValue(BaseToolWithShape.class, mToolToTest, TOOL_MEMBER_POSITION); PointF pointDown = new PointF(dragFromX, dragFromY); PointF pointMoveTo = new PointF(dragToX, dragToY); mToolToTest.handleDown(pointDown); mToolToTest.handleMove(pointMoveTo); mToolToTest.handleUp(pointMoveTo); float newWidth = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, mToolToTest, TOOL_MEMBER_WIDTH); float newHeight = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, mToolToTest, TOOL_MEMBER_HEIGHT); PointF newPosition = (PointF) PrivateAccess.getMemberValue(BaseToolWithShape.class, mToolToTest, TOOL_MEMBER_POSITION); if (resizeBigger) { if (resizeWidth) { assertTrue("new width should be bigger", newWidth > rectWidth); } else { assertTrue("height should not have changed", newWidth == rectWidth); } if (resizeHeight) { assertTrue("new width should be bigger", newHeight > rectHeight); } else { assertTrue("height should not have changed", newHeight == rectHeight); } if (isCorner) { assertTrue("resizing should be in aspect ratio", newHeight == newWidth); } } else { if (resizeWidth) { assertTrue("new height should be smaller", newWidth < rectWidth); } else { assertTrue("height should not have changed", newWidth == rectWidth); } if (resizeHeight) { assertTrue("new width should be smaller", newHeight < rectHeight); } else { assertTrue("height should not have changed", newHeight == rectHeight); } if (isCorner) { assertTrue("resizing should be in aspect ratio", newHeight == newWidth); } } assertTrue("position should be the same", (newPosition.x == rectPosition.x) && (newPosition.y == rectPosition.y)); PrivateAccess.setMemberValue(BaseToolWithRectangleShape.class, mToolToTest, TOOL_MEMBER_WIDTH, rectWidth); PrivateAccess.setMemberValue(BaseToolWithRectangleShape.class, mToolToTest, TOOL_MEMBER_HEIGHT, rectHeight); } public void testRatioOfBoxAfterSetImage() throws SecurityException, IllegalArgumentException, NoSuchFieldException, IllegalAccessException { float bitmapWidth = 300; float bitmapHeight = 200; float bitmapRatio = bitmapWidth / bitmapHeight; Bitmap bitmap = Bitmap.createBitmap((int) bitmapWidth, (int) bitmapHeight, Config.ARGB_8888); ((BaseToolWithRectangleShape) mToolToTest).setBitmap(bitmap); float boxWidth = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, mToolToTest, TOOL_MEMBER_WIDTH); float boxHeight = (Float) PrivateAccess.getMemberValue(BaseToolWithRectangleShape.class, mToolToTest, TOOL_MEMBER_HEIGHT); float boxRatio = boxWidth / boxHeight; // correct floating point errors bitmapRatio *= 1000.0f; boxRatio *= 1000.0f; assertEquals("bitmap ratio should be box Ratio", Math.round(bitmapRatio), Math.round(boxRatio)); } private class BaseToolWithRectangleShapeImpl extends BaseToolWithRectangleShape { public BaseToolWithRectangleShapeImpl(Context context, ToolType toolType) { super(context, toolType); } @Override public void resetInternalState() { } @Override protected void onClickInBox() { mDrawingBitmap = Bitmap.createBitmap(1, 1, Config.ALPHA_8); } @Override protected void drawToolSpecifics(Canvas canvas) { } } }
import java.awt.Color; import java.awt.GridLayout; import java.awt.Image; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.io.File; import java.nio.file.Files; import java.util.ArrayList; import java.util.Collections; import java.util.Stack; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; public class TabuleiroInterface extends JFrame { private JButton casas[][]; private EstadoTabuleiro estado; private int dimensao; private Tabuleiro tabuleiroGenetico; public TabuleiroInterface(int dimensao,int tipo) { this.tabuleiroGenetico = new Tabuleiro(dimensao); this.estado = new EstadoTabuleiro(dimensao); //Cria o EstadoTabuleiro Inicial this.estado.inicializarCasasComRainha(); //Coloca as rainhas em posições aleatórias this.estado.construirHeuristica(); //Conta a quantidade de conflitos para cada posição do tabuleiro this.dimensao = dimensao; inicializarTabuleiro(tipo); //Cria o Jframe para o tabuleiro } // public TabuleiroInterface(EstadoTabuleiro estado) {; // this.dimensao = estado.getDimensaoTabuleiro(); // this.estado = estado; // this.estado.construirHeuristica(); // inicializarTabuleiro(); // } //mostra a quantidade de conflito de cada posição do tabuleiro (Tabuleiro A*) private void exibirHeuristica() { for(int i = 0; i < dimensao; ++i) { for(int j = 0; j< dimensao; ++j) { casas[i][j].setText(estado.getHeuristica()[i][j]+""); } } } //Cria JFrame para exibir o tabuleiro private void inicializarTabuleiro(int tipo) { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); setSize(500,500); setLayout(new GridLayout(dimensao,dimensao)); if(tipo == 1){ desenharCasas(); }else{ desenharCasasGenetica(); } } //Cria os botões representando cada posição do tabuleiro A* e pinta de azul private void desenharCasas() { casas = new JButton[dimensao][dimensao]; for(int i = 0; i < dimensao; ++i) { for(int j = 0; j < dimensao; ++j) { casas[i][j] = new JButton(); add(casas[i][j]); casas[i][j].setBackground(Color.BLUE); } } validate(); desenharRainha(); } //Cria botões representando cada posição do tabuleiro Genético e pinta de azul private void desenharCasasGenetica() { casas = new JButton[dimensao][dimensao]; for(int i = 0; i < dimensao; ++i) { for(int j = 0; j < dimensao; ++j) { casas[i][j] = new JButton(); add(casas[i][j]); casas[i][j].setBackground(Color.BLUE); } } validate(); desenharRainhaGenetico(); } //Coloca as rainhas e a quantidade de conflitos de cada posição private void desenharRainha() { exibirHeuristica(); for(int i = 0; i < dimensao; ++i) { for(int j = 0; j < dimensao; ++j) { casas[i][j].setBackground(Color.blue); casas[i][j].setIcon(null); addEvento(i,j,1); if(estado.getCasas()[i][j] == 1) { JButton casa = casas[i][j]; try { File imgFile = new File(getClass().getResource("img/rainha.png").getFile()); Image img = new ImageIcon(Files.readAllBytes(imgFile.toPath())).getImage(); img = img.getScaledInstance(casa.getWidth(), casa.getWidth(), java.awt.Image.SCALE_SMOOTH); casa.setIcon(new ImageIcon(img)); } catch (Exception e) { e.printStackTrace(); } } casas[i][j].repaint(); casas[i][j].validate(); } } } private void desenharRainhaGenetico() { for(int i = 0; i < dimensao; ++i) { for(int j = 0; j < dimensao; ++j) { casas[i][j].setBackground(Color.blue); casas[i][j].setIcon(null); addEvento(i,j,2); if(tabuleiroGenetico.getTabuleiro()[i][j]) { JButton casa = casas[i][j]; try { File imgFile = new File(getClass().getResource("img/rainha.png").getFile()); Image img = new ImageIcon(Files.readAllBytes(imgFile.toPath())).getImage(); img = img.getScaledInstance(casa.getWidth(), casa.getWidth(), java.awt.Image.SCALE_SMOOTH); casa.setIcon(new ImageIcon(img)); } catch (Exception e) { e.printStackTrace(); } } casas[i][j].repaint(); casas[i][j].validate(); } } } private void pintarBotao(int i, int j, Color cor, boolean pintarAmeacas, int tipo) { for(int k = 0; k < dimensao; ++k) { casas[i][k].setBackground(cor); if(tipo == 1){ if(estado.getCasas()[i][k] == 1 && pintarAmeacas) { casas[i][k].setBackground(Color.red); } } else{ if(tabuleiroGenetico.getTabuleiro()[i][k] && pintarAmeacas){ casas[i][k].setBackground(Color.red); } } } for(int k = 0; k < dimensao; ++k) { casas[k][j].setBackground(cor); if(tipo == 1){ if(estado.getCasas()[k][j] == 1 && pintarAmeacas) { casas[k][j].setBackground(Color.red); } } else{ if(tabuleiroGenetico.getTabuleiro()[k][j] && pintarAmeacas){ casas[k][j].setBackground(Color.red); } } } int l = i-1; int c = j-1; while(c >= 0 && l >= 0) { casas[l][c].setBackground(cor); if(tipo == 1){ if(estado.getCasas()[l][c] == 1 && pintarAmeacas) { casas[l][c].setBackground(Color.red); } } else{ if(tabuleiroGenetico.getTabuleiro()[l][c] && pintarAmeacas){ casas[l][c].setBackground(Color.red); } } c--; l--; } l = i+1; c = j+1; while(c < dimensao && l < dimensao) { casas[l][c].setBackground(cor); if(tipo == 1){ if(estado.getCasas()[l][c] == 1 && pintarAmeacas) { casas[l][c].setBackground(Color.red); } } else{ if(tabuleiroGenetico.getTabuleiro()[l][c] && pintarAmeacas){ casas[l][c].setBackground(Color.red); } } c++; l++; } l = i-1; c = j+1; while(c < dimensao && l >= 0) { casas[l][c].setBackground(cor); if(tipo == 1){ if(estado.getCasas()[l][c] == 1 && pintarAmeacas) { casas[l][c].setBackground(Color.red); } } else{ if(tabuleiroGenetico.getTabuleiro()[l][c] && pintarAmeacas){ casas[l][c].setBackground(Color.red); } } c++; l--; } l = i+1; c = j-1; while(c >= 0 && l < dimensao) { casas[l][c].setBackground(cor); if(tipo == 1){ if(estado.getCasas()[l][c] == 1 && pintarAmeacas) { casas[l][c].setBackground(Color.red); } } else{ if(tabuleiroGenetico.getTabuleiro()[l][c] && pintarAmeacas){ casas[l][c].setBackground(Color.red); } } c--; l++; } } private void addEvento(int i, int j, int tipo) { JButton casa = casas[i][j]; casa.addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent me) { } @Override public void mousePressed(MouseEvent me) { } @Override public void mouseReleased(MouseEvent me) { } @Override public void mouseEntered(MouseEvent me) { if(tipo == 1){ if(estado.getCasas()[i][j] == 1){ pintarBotao(i, j, Color.YELLOW, true, tipo); } } else{ if(tabuleiroGenetico.getTabuleiro()[i][j]){ pintarBotao(i, j, Color.YELLOW, true, tipo); } } } @Override public void mouseExited(MouseEvent me) { pintarBotao(i, j, Color.BLUE, false,tipo); } }); } public void mostrarSolucao(Stack<EstadoTabuleiro> passos) { for(int i = 0; i < dimensao; ++i) { for(int j = 0; j < dimensao; ++j) { casas[i][j].addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent ae) { if(!passos.empty()) { estado = passos.pop(); desenharRainha(); validate(); } } }); } } } public void mostrarSolucaoAlgoritmoGenetico(Tabuleiro tabuleiro) { //System.out.println(tabuleiro.toString()); for(int i = 0; i < dimensao; ++i) { for(int j = 0; j < dimensao; ++j) { tabuleiroGenetico = tabuleiro; desenharRainhaGenetico(); validate(); } } } public No buscaAEstrela() { No raiz = new No(estado, 1); No noAtual = raiz; ArrayList<No> nos = new ArrayList(); while(true) { EstadoTabuleiro estadoAtual = noAtual.getEstadoTabuleiro(); int d = estadoAtual.getDimensaoTabuleiro(); int h[][] = estadoAtual.getHeuristica(); for(int i = 0; i < d; ++i) { for(int j = 0; j < d; ++j) { EstadoTabuleiro e = estadoAtual.moverRainha(i, j); No filho = new No(e, 1); e.construirHeuristica(); filho.setCustoHeuristica(h[i][j]); if(noAtual.addFilho(filho)) { nos.add(filho); } } } Collections.sort(nos); int maisRaso = nos.get(0).getCustoCaminho(); int fNo = nos.get(0).getCustoHeuristica(); int idNo = 0; for(int i = 1; i < nos.size(); ++i) { if(nos.get(i).getCustoCaminho() < maisRaso && fNo == nos.get(i).getCustoHeuristica()) { maisRaso = nos.get(i).getCustoCaminho(); idNo = i; } } No filho = nos.remove(idNo); if(filho.getEstadoTabuleiro().contarConflitos() == 0) { return filho; } noAtual = filho; } } // public static void main(String args[]) { // // TabuleiroInterface tabuleiroEstrela = new TabuleiroInterface(8,1); // tabuleiroEstrela.setTitle("A*"); // long start_A = System.currentTimeMillis(); // No solucaoAEstrela = tabuleiroEstrela.buscaAEstrela(); // long elapsed_A = System.currentTimeMillis() - start_A; // // Stack<EstadoTabuleiro> passosAEstrela = new Stack(); // while(solucaoAEstrela != null) { // passosAEstrela.push(solucaoAEstrela.getEstadoTabuleiro()); // solucaoAEstrela = solucaoAEstrela.getPai(); // } // // tabuleiroEstrela.mostrarSolucao(passosAEstrela); // // //Tabuleiro Algoritmo Genetico // TabuleiroInterface tabuleiroGenetico1 = new TabuleiroInterface(8,2); // tabuleiroGenetico1.setTitle("Algoritmo Genetico"); // // AlgoritmoGenetico ag = new AlgoritmoGenetico(100, 7); // tabuleiroGenetico1.mostrarSolucaoAlgoritmoGenetico(ag.pegaTabuleiro()); // long start_genetico = System.currentTimeMillis(); // ag.evoluir(2000); // long elapsed_genetico = System.currentTimeMillis() - start_genetico; // tabuleiroGenetico1.mostrarSolucaoAlgoritmoGenetico(ag.pegaTabuleiro()); // // System.out.println("Tempo de execucao A*: " + elapsed_A + " ms"); // System.out.println("Tempo de execucao Algoritmo Genético: " + elapsed_genetico +" ms"); // } }
package com.noname.setalarm.view; import android.animation.Animator; import android.animation.AnimatorListenerAdapter; import androidx.lifecycle.ViewModelProviders; import androidx.databinding.DataBindingUtil; import android.animation.AnimatorSet; import android.animation.ObjectAnimator; import android.content.Intent; import android.os.Bundle; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.selection.SelectionTracker; import androidx.recyclerview.widget.LinearLayoutManager; import android.util.Log; import android.view.View; import android.view.ViewAnimationUtils; import android.view.animation.AccelerateInterpolator; import android.view.animation.DecelerateInterpolator; import android.widget.TimePicker; import com.noname.setalarm.AlarmLogic; import com.noname.setalarm.R; import com.noname.setalarm.databinding.ActivityAddalarmBinding; import com.noname.setalarm.model.ClockModel; import com.noname.setalarm.repository.AlarmRoom; import com.noname.setalarm.viewmodel.ClockViewModel; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.UUID; public class AddAlarmActivity extends AppCompatActivity { private static String TAG = AddAlarmActivity.class.getSimpleName(); private ActivityAddalarmBinding activityAddalarmBinding; private AlarmLogic alarmLogic; private ClockViewModel viewModel; private SelectionTracker selectionTracker; private ArrayList<ClockModel> models = new ArrayList<>(); @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); activityAddalarmBinding = DataBindingUtil.setContentView(this, R.layout.activity_addalarm); activityAddalarmBinding.setLifecycleOwner(this); activityAddalarmBinding.setProvider(new ImageProvider(R.drawable.hills, R.drawable.moon)); setSupportActionBar(activityAddalarmBinding.toolbar); Intent intent = getIntent(); Calendar calendar = Calendar.getInstance(); if (calendar.get(Calendar.HOUR_OF_DAY) >= 12){ activityAddalarmBinding.pm.setVisibility(View.INVISIBLE); }else { activityAddalarmBinding.pm.setVisibility(View.VISIBLE); } alarmLogic = new AlarmLogic(this); viewModel = ViewModelProviders.of(this).get(ClockViewModel.class); if (intent.hasExtra("modifyList")) { models = intent.getParcelableArrayListExtra("modifyList"); for (ClockModel clockModel : models){ viewModel.insert(clockModel); } }else { // Log.d(TAG, "HOUR + " + alarmLogic.getCurrentHour() + "MINUTE : " + alarmLogic.getCurrentMinute()); ClockModel clockModel = new ClockModel(alarmLogic.makeID(alarmLogic.getCurrentHour(), alarmLogic.getCurrentMinute(), alarmLogic.getCurrentSecond()), alarmLogic.getCurrentHour(), alarmLogic.getCurrentMinute(), alarmLogic.getCurrentHour() >= 12); models.add(clockModel); viewModel.insert(clockModel); } // selectionTracker = new SelectionTracker.Builder("selction-clock", // activityAddalarmBinding.recycler, new StableIdKeyProvider(activityAddalarmBinding.recycler), // new MyDetailsLookup(activityAddalarmBinding.recycler), StorageStrategy.createLongStorage() // ).build(); // // selectionTracker.addObserver(new SelectionTracker.SelectionObserver() { // @Override // public void onItemStateChanged(@NonNull Object key, boolean selected) { // super.onItemStateChanged(key, selected); // Log.d(TAG , "selected item key: " + key); // } // }); ClockAdapter clockAdapter = new ClockAdapter(getApplicationContext()); viewModel.getListLiveData().observe(this, clockModels -> { clockAdapter.submitList(clockModels); }); clockAdapter.setClockClickListener((hour, minute) -> { activityAddalarmBinding.timer.setHour(hour); activityAddalarmBinding.timer.setMinute(minute); revealpm(hour); }); activityAddalarmBinding.recycler.setAdapter(clockAdapter); LinearLayoutManager horizontalLayout = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false); activityAddalarmBinding.recycler.setLayoutManager(horizontalLayout); activityAddalarmBinding.timer.setIs24HourView(true); activityAddalarmBinding.timer.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() { @Override public void onTimeChanged(TimePicker timePicker, int hourOfDay, int minutes) { viewModel.updateHour(clockAdapter.getSelectedID(), hourOfDay); viewModel.updateMinute(clockAdapter.getSelectedID(), minutes); viewModel.updateAMPM(clockAdapter.getSelectedID(), hourOfDay >= 12); revealpm(hourOfDay); } }); ArrayList<ClockModel> finalModels = models; activityAddalarmBinding.addSize.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Calendar tmp = Calendar.getInstance(); Log.d(TAG, "추가"); ClockModel tmpClock = new ClockModel(alarmLogic.makeID(tmp.get(Calendar.HOUR_OF_DAY), tmp.get(Calendar.MINUTE), tmp.get(Calendar.SECOND)), tmp.get(Calendar.HOUR_OF_DAY), tmp.get(Calendar.MINUTE), tmp.get(Calendar.HOUR_OF_DAY)<12); finalModels.add(tmpClock); viewModel.insert(tmpClock); } }); activityAddalarmBinding.confirm.setOnClickListener(v -> { //수정버튼으로 들어온 경우 //원래 id 의 alarmroom 데이터를 수정된 clocklist로 덮어씌워야함. //원래 id의 알람은 삭제. if(intent.hasExtra("modifyList")){ for (int i = 0; i<models.size(); i++) { alarmLogic.unregisterAlarm(models.get(i).getId()); } List<ClockModel> tmpList = viewModel.getListLiveData().getValue(); for (int i = 0; i < tmpList.size(); i++) { alarmLogic.setToCalendar(tmpList.get(i).getHour(), tmpList.get(i).getMinute(), tmpList.get(i).getHour() >= 12); alarmLogic.newAlarm(tmpList.get(i).getId(), alarmLogic.getCalendarTime()); } viewModel.updateAlarm(intent.getStringExtra("alarmId"), tmpList); }else { List<ClockModel> tmpList = viewModel.getListLiveData().getValue(); for (int i = 0; i < tmpList.size(); i++) { alarmLogic.setToCalendar(tmpList.get(i).getHour(), tmpList.get(i).getMinute(), tmpList.get(i).getHour() >= 12); alarmLogic.newAlarm(tmpList.get(i).getId(), alarmLogic.getCalendarTime()); } viewModel.insertAlarm(new AlarmRoom(UUID.randomUUID().toString(), tmpList, true, activityAddalarmBinding.memo.getText().toString())); } viewModel.deleteAll(); super.onBackPressed(); }); } @Override protected void onStart() { super.onStart(); rescaleViewAnimation(activityAddalarmBinding.confirm, 1f, 500, null); } public void onPause() { super.onPause(); overridePendingTransition(0, 0); } @Override public void finish(){ rescaleViewAnimation(activityAddalarmBinding.confirm, 0, 300, new Animator.AnimatorListener() { @Override public void onAnimationStart(Animator animation) { } @Override public void onAnimationEnd(Animator animation) { AddAlarmActivity.super.finish(); } @Override public void onAnimationCancel(Animator animation) { } @Override public void onAnimationRepeat(Animator animation) { } }); } @Override public void onBackPressed() { super.onBackPressed(); viewModel.deleteAll(); } private void revealpm(int hour){ //am_pm true : 오후 false: 오전 if( (hour < 12 && !activityAddalarmBinding.pm.isShown())){ revealThepm(); } else if (hour >= 12 && activityAddalarmBinding.pm.isShown()) { hideThepm(); } } private Animator createRevealAnimator(boolean show, View view ) { final int cx = view.getWidth() ; final int cy = view.getHeight() ; final int radius = (int) Math.hypot(cx, cy); final Animator animator; if (show) { animator = ViewAnimationUtils.createCircularReveal(view, cx, cy, 0, radius); animator.setInterpolator(new DecelerateInterpolator()); } else { animator = ViewAnimationUtils.createCircularReveal(view, cx, cy, radius, 0); animator.setInterpolator(new AccelerateInterpolator()); } animator.setDuration(getResources().getInteger(R.integer.default_anim_duration)); return animator; } private void revealThepm() { activityAddalarmBinding.pm.setVisibility(View.VISIBLE); Animator reveal = createRevealAnimator(true, activityAddalarmBinding.pm); reveal.start(); activityAddalarmBinding.am.setVisibility(View.INVISIBLE); } /** * Hide the am */ private void hideThepm() { activityAddalarmBinding.am.setVisibility(View.VISIBLE); Animator hide = createRevealAnimator(false, activityAddalarmBinding.pm); hide.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); activityAddalarmBinding.pm.setVisibility(View.INVISIBLE); } }); hide.start(); } private void rescaleViewAnimation(View view, float targetScale, int durationOffset, Animator.AnimatorListener listener) { ObjectAnimator scaleOnX = ObjectAnimator.ofFloat(view, "scaleX", targetScale); ObjectAnimator scaleOnY = ObjectAnimator.ofFloat(view, "scaleY", targetScale); scaleOnX.setDuration(durationOffset); scaleOnY.setDuration(durationOffset); AnimatorSet scaleSet = new AnimatorSet(); scaleSet.playTogether( scaleOnX, scaleOnY ); if (listener != null){ scaleSet.addListener(listener); } scaleSet.start(); } }
package com.model; public class ImageData { String id; String imagePath; String imageName; public ImageData(String id, String imagePath,String imageName) { super(); this.id = id; this.imagePath = imagePath; this.imageName=imageName; } public String getImageName() { return imageName; } public void setImageName(String imageName) { this.imageName = imageName; } public ImageData() { super(); } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getImagePath() { return imagePath; } public void setImagePath(String imagePath) { this.imagePath = imagePath; } }
package TrabalhoFinal; public class Endereco { private String nomeRua; private int numero; private String bairro; private String nomeCidade; private String estado; public void setNomeRua(String nomeRua){ this.nomeRua=nomeRua; } public void setNumero(int numero){ this.numero=numero; } public void setBairro(String bairro){ this.bairro=bairro; } public void setNomeCidade(String nomeCidade){ this.nomeCidade=nomeCidade; } public void setEstado(String estado){ this.estado=estado; } public String getNomeRua(){ return this.nomeRua; } public String getBairro(){ return this.bairro; } public String getNomeCidade(){ return this.nomeCidade; } public String getEstado(){ return this.estado; } public int getNumero(){ return this.numero; } }
package switch2019.project.infrastructure.jpa; import org.springframework.data.jpa.repository.JpaRepository; import switch2019.project.dataModel.entities.CategoryIdJpa; import switch2019.project.dataModel.entities.CategoryJpa; import java.util.List; import java.util.Optional; public interface CategoryJpaRepository extends JpaRepository<CategoryJpa, String> { List<CategoryJpa> findAll(); Optional<CategoryJpa> findById(String id); Optional<CategoryJpa> findByCategoryIdJpa (CategoryIdJpa categoryIdjpa); List<CategoryJpa> findAllByCategoryIdJpa_Owner (String ownerID); }
package tests; import clients.SetupClient; import org.junit.*; import static org.junit.Assert.*; import server.QuizServer; import service.QuizService; import java.io.*; import java.nio.charset.StandardCharsets; import java.rmi.RemoteException; /** * Created by Sophie on 02/02/15. * Test the setup client */ public class TestSetupClient { private SetupClient setup; private static File file; private static QuizService server; @BeforeClass public static void setUpFirst() throws IOException { file = new File("setuptest.txt"); file.createNewFile(); server = new QuizServer(file); server.start(); } @Before public void buildUp() { setup = new SetupClient(); setup.launch(); } @Test public void testCreateQuiz(){ try { String answers = "what is 1+1\n2\n3\n4\n5\nN"; System.setIn(new ByteArrayInputStream(answers.getBytes(StandardCharsets.UTF_8))); setup.createQuiz("test quiz"); assertEquals("test quiz", server.getQuizList().get(0).getQuizName()); } catch (RemoteException e) { e.printStackTrace(); } } @AfterClass public static void tearDown(){ file.delete(); } }
package com.zb666.item; import com.chad.library.adapter.base.entity.MultiItemEntity; public class EntityB implements MultiItemEntity { private int b; public int getB() { return b; } public void setB(int b) { this.b = b; } @Override public int getItemType() { return 1; } }
package com.ittr.data.Product; import java.util.ArrayList; public class ProductData { public ArrayList<Product> results; }
import javax.swing.JOptionPane; /** * Este arquivo ficará responsável de forma primária para funcionar como interface da aplicação * durante o desenvolvimento. Não ficará responsável por nenhuma regra de négocio. */ public class MySuperMarket { public static void main(final String[] args){ JOptionPane.showMessageDialog(null,"Bem vindo a MySuperMarket"); int command; do{ final String response = (JOptionPane.showInputDialog(null, "Digite 1 para cadastrar um novo funcionário, 2 para listar os funcionários e 0 para encerrar o programa!")); command = Integer.parseInt(response); switch(response){ case "1": final CreateOffice office = new CreateOffice(); office.CreateOffice(); break; case "2": final OfficeRepository officies = new OfficeRepository(); officies.getAll(); break; } }while(command != 0); JOptionPane.showMessageDialog(null, "Obrigado por nos acessar!"); } }
package org.team3128.compbot.calibration; import org.team3128.compbot.subsystems.Constants; import org.team3128.compbot.subsystems.Shooter; import edu.wpi.first.wpilibj.command.Command; import org.team3128.common.utility.Log; import edu.wpi.first.wpilibj.Timer; import edu.wpi.first.wpilibj.RobotController; public class CmdShooterFF extends Command { Shooter shooter; double current = 0; double error = 0; double output = 0; double accumulator = 0; double prevError = 0; public static int setpoint = 1000; public static int increment = 250; public static int counter = 0; public double sumOutput, sumBatteryVoltage, sumRPM, sumVoltage, startVoltage, voltageBattery, voltageMotor, currentTime, pastTime; int plateauCount = 0; public CmdShooterFF(Shooter shooter) { this.shooter = shooter; } @Override protected void initialize() { } @Override protected void execute() { /* * current = shooter.getRPM(); error = setpoint - current; accumulator += error * * Constants.MechanismConstants.DT; if (accumulator > * Constants.ShooterConstants.SHOOTER_SATURATION_LIMIT) { accumulator = * Constants.ShooterConstants.SHOOTER_SATURATION_LIMIT; } else if (accumulator < * -Constants.ShooterConstants.SHOOTER_SATURATION_LIMIT) { accumulator = * -Constants.ShooterConstants.SHOOTER_SATURATION_LIMIT; } double kP_term = * Constants.ShooterConstants.SHOOTER_PID.kP * error; double kI_term = * Constants.ShooterConstants.SHOOTER_PID.kI * accumulator; double kD_term = * Constants.ShooterConstants.SHOOTER_PID.kD * (error - prevError) / * Constants.MechanismConstants.DT; * * double voltage_output = shooter.shooterFeedForward(setpoint) + kP_term + * kI_term + kD_term; double voltage = RobotController.getBatteryVoltage(); // * TODO: investigate bus voltage * * output = voltage_output / voltage; * * prevError = error; * * if (Math.abs(error) <= Constants.ShooterConstants.RPM_THRESHOLD) { * plateauCount++; } else { plateauCount = 0; } * * if (output > 1) { Log.info("SHOOTER", * "WARNING: Tried to set power above available voltage! Saturation limit SHOULD take care of this " * ); output = 1; } else if (output < -1) { Log.info("SHOOTER", * "WARNING: Tried to set power above available voltage! Saturation limit SHOULD take care of this " * ); output = -1; } shooter.LEFT_SHOOTER.set(output); * shooter.RIGHT_SHOOTER.set(-output); */ shooter.setSetpoint(setpoint); voltageBattery = RobotController.getBatteryVoltage(); voltageMotor = shooter.LEFT_SHOOTER.getBusVoltage(); currentTime = Timer.getFPGATimestamp(); if (Math.abs(setpoint - shooter.getRPM()) <= 300) { counter += 1; //sumOutput += output; //sumBatteryVoltage += RobotController.getBatteryVoltage(); sumRPM += shooter.getRPM(); sumVoltage += shooter.LEFT_SHOOTER.getBusVoltage() * shooter.LEFT_SHOOTER.getAppliedOutput(); if ((increment) != 0 && (counter >= 100)) { Log.info("Shooter", "Current Setpoint: " + setpoint + " Average RPM: " + (sumRPM / counter) + " Average Voltage: " + (sumVoltage / counter)); setpoint += increment; counter = 0; //sumOutput = 0; //sumBatteryVoltage = 0; sumRPM = 0; sumVoltage = 0; } } pastTime = currentTime; } @Override protected boolean isFinished() { if (setpoint >= 4500) { Log.info("Shooter", "Finished with automated loop"); setpoint = 0; increment = 0; return true; } else { return false; } } @Override protected void end() { shooter.LEFT_SHOOTER.set(0); shooter.RIGHT_SHOOTER.set(0); } @Override protected void interrupted() { end(); } }
package it.unirc.pwm.eureca.utils; public class Costant { //public static String URL_GAZZETTA = "http://xml2.temporeale.gazzettaobjects.it/optatrsport/"; public static Integer SIZE_LIST =10; public static int PUNTI_VIAGGI =50; public static String OGGETTO_EMAIL = "Registrazione Associazione E.U.Re.Ca."; public static String MESSAGGIO_EMAIL = "Registrazione Associazione E.U.Re.Ca." + " avvenuta con successo!!!!! "; public static String PASSWORD_EMAIL =" La tua password è: "; public static String USERNAME_EMAIL =" La tua username è: "; public static String ALTROMESSAGGIO_EMAIL =" Ricordati di cambiare la password dopo l'accesso!!!!"; public static String EMAIL ="programmazionewm@gmail.com"; public static String PASSWORD ="programmazionewm1"; }
package fel_1; import java.util.Random; import static fel_1.Main.arrayWritten; public class AddToArray extends Thread { private final String[] array; public AddToArray(String[] array) { this.array = array; } @Override public void run() { Random random = new Random(); while (true) { int num = random.nextInt(26); char ch = (char) (num + 97); /** a = 97 */ String str = "" + ch + ch + ch; synchronized (array) { array[minIndex()] = str; } int temp = arrayWritten.getAndDecrement(); if (temp < 1) { System.out.println("Array has been modified 300 times: " + arrayWritten.get()); System.exit(0); } try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } synchronized (System.out) { print(); } } } public int minIndex() { int min = 0; for (int i = 1; i < array.length; i++) { if (array[i].compareTo(array[min]) < 0) { min = i; } } return min; } public void print() { System.out.print(Thread.currentThread().getName() + ": "); for (String s : array) { System.out.print(s + " "); } System.out.println(); } }
//package com.sprmvc.web.ch5.services; // //import org.springframework.beans.factory.annotation.Autowired; //import org.springframework.context.annotation.Bean; //import org.springframework.context.annotation.ComponentScan; //import org.springframework.context.annotation.Configuration; //import org.springframework.remoting.caucho.HessianServiceExporter; //import org.springframework.remoting.rmi.RmiProxyFactoryBean; //import org.springframework.remoting.rmi.RmiServiceExporter; // //@Configuration //@ComponentScan //public class SpServicesConf { // // @Bean // public SpitterService spitterService() { // return new SpitterServiceImpl(); // } // // //// @Bean //// @Autowired //// public RmiServiceExporter rmiExporter(SpitterService spitterService) { //// RmiServiceExporter rmiExporter = new RmiServiceExporter(); //// rmiExporter.setService(spitterService); //// rmiExporter.setServiceName("SpitterService"); //// rmiExporter.setServiceInterface(SpitterService.class); //// return rmiExporter; //// } //// //// @Bean //// public RmiProxyFactoryBean spitterService() { //// RmiProxyFactoryBean rmiProxy = new RmiProxyFactoryBean(); //// rmiProxy.setServiceUrl("rmi://localhost/SpitterService"); //// rmiProxy.setServiceInterface(SpitterService.class); //// return rmiProxy; //// } //}
package eat_more_pizza; abstract class PizzaPieD { RemAV remFn = new RemAV(); RemFishV rfFn = new RemFishV(); RemIntV riFn = new RemIntV(); RemV roFn = new RemV(); SubstFishV sfFn = new SubstFishV(); SubstV soFn = new SubstV(); abstract PizzaPieD remA(); abstract PizzaPieD remFish(FishD f); abstract PizzaPieD remInt(Integer i); abstract PizzaPieD Rem(Object o); abstract PizzaPieD substFish(FishD n, FishD o); abstract PizzaPieD subst(Object n, Object o); } class Bottom extends PizzaPieD { PizzaPieD remA() { return remFn.forBottom(); } PizzaPieD remFish(FishD f) { return rfFn.forBottom(f); } public PizzaPieD remInt(Integer i) { return riFn.forBottom(i); } PizzaPieD Rem(Object o) { return roFn.forBottom(o); } PizzaPieD substFish(FishD n, FishD o) { return sfFn.forBottom(n, o); } PizzaPieD subst(Object n, Object o) { return soFn.forBottom(n, o); } } class Topping extends PizzaPieD { private Object t; private PizzaPieD r; Topping(Object _t, PizzaPieD _r) { t = _t; r = _r; } PizzaPieD remA() { return remFn.forTopping(t, r); } PizzaPieD remFish(FishD f) { return rfFn.ForTopping(t, r, f); } public PizzaPieD remInt(Integer i) { return riFn.forTopping(t, r, i); } PizzaPieD Rem(Object o) { return roFn.forTopping(t, r, o); } PizzaPieD substFish(FishD n, FishD o) { return sfFn.forTopping(t, r, n, o); } PizzaPieD subst(Object n, Object o) { return soFn.forTopping(t, r, n, o); } } public class EatMorePizza { public static void main(String[] args) { PizzaPieD p = new Topping( new Salmon(), new Topping( new Anchovy(), new Bottom() ) ); p.substFish(new Tuna(), new Anchovy()); } }
package com.projectn.app.entities; import javax.persistence.Column; import javax.persistence.Id; import org.hibernate.annotations.Entity; @Entity public class Citizen { @Id private String id; @Column private String firstName; @Column private String lastName; @Column private String alias; @Column private int gender; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getAlias() { return alias; } public void setAlias(String alias) { this.alias = alias; } public int getGender() { return gender; } public void setGender(int gender) { this.gender = gender; } }
package com.qunchuang.carmall.domain.privilege; import cn.wzvtcsoft.bosdomain.Entry; import cn.wzvtcsoft.bosdomain.annotations.Bostype; import com.qunchuang.carmall.graphql.annotation.SchemaDocumentation; import lombok.Getter; import lombok.Setter; import javax.persistence.Entity; import javax.persistence.ManyToOne; /** * @author Curtain * @date 2018/10/22 16:54 */ @Entity @SchemaDocumentation("角色集合") @Bostype("R02") @Getter @Setter public class RoleItem extends Entry { /** * 角色 */ @ManyToOne private Role role; @Override public String toString() { return "RoleItem{" + "role=" + role + '}'; } }
// Virginia Tech Honor Code Pledge: // // As a Hokie, I will conduct myself with honor and integrity at all times. // I will not lie, cheat, or steal, nor will I accept the actions of those // who do. // -- Musaab Elsheikh (melsheikh) import sofia.micro.*; import sofia.graphics.Color; //------------------------------------------------------------------------- /** * This class represents a sand particle in the ParticleWorld map. * * @author Musaab Elsheikh (melsheikh) * @version (2019.11.05) */ public class Sand extends Particle { //~ Fields ................................................................ //~ Constructor ........................................................... // ---------------------------------------------------------- /** * Creates a new Sand object. */ public Sand() { super(Color.khaki, true, 2.5); } //~ Methods ............................................................... }
package com.meridal.examples.mvc; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; import com.meridal.examples.domain.VehicleCertificate; import com.meridal.examples.service.InspectionService; /** * Controller for public-facing API requests. * @author Martin Ingram */ @RestController @RequestMapping("/api") public class PublicAPIController { @Autowired private InspectionService inspectionService; @RequestMapping(value="/inspection/all", method=RequestMethod.GET) @ResponseBody public List<VehicleCertificate> getAllVehicleCertificates() { return this.inspectionService.findAllVehicleCertificates(); } @RequestMapping(value="/inspection/{registrationNumber}", method=RequestMethod.GET) @ResponseBody public VehicleCertificate getVehicleCertificate(@PathVariable String registrationNumber) { return this.inspectionService.findVehicleCertificate(registrationNumber); } @RequestMapping(value="/inspection", method=RequestMethod.POST) @ResponseBody public VehicleCertificate postVehicleCertificate(@RequestBody VehicleCertificate vehicle) { this.inspectionService.saveVehicleCertificate(vehicle); return vehicle; } @RequestMapping(value="/inspection/{registrationNumber}", method=RequestMethod.PUT) @ResponseBody public VehicleCertificate putVehicleCertificate(@RequestBody VehicleCertificate vehicle) { this.inspectionService.saveVehicleCertificate(vehicle); return vehicle; } @RequestMapping(value="/inspection", method=RequestMethod.DELETE) @ResponseBody public VehicleCertificate deleteVehicleCertificate(@RequestBody VehicleCertificate vehicle) { this.inspectionService.deleteVehicleCertificate(vehicle); return vehicle; } }
public class InventoryItems { private static String manufacturer, name, category; private static int UPC, price; //constructors public InventoryItems(String man, String n) { manufacturer = man; name = n; UPC = (int)(Math.random()*1000000000)+100000000; } public InventoryItems(String man, String n, String cat, int p) { manufacturer = man; name = n; category = cat; price = p; UPC = (int)(Math.random()*1000000000)+100000000; } public String toString() { return "Item Info...\nItem Manufacturer: " + manufacturer + "\nItem Name: " + name + "\nItem Category: " + category + "\nItem UPC#: " + UPC + "\nItem Price: " + price; } }
package com.hb.rssai.presenter; import android.text.TextUtils; import com.hb.rssai.constants.Constant; import com.hb.rssai.contract.ForgetContract; import com.hb.rssai.util.StringUtil; import java.util.HashMap; import java.util.Map; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; /** * Created by Administrator on 2018/1/27 0027. */ public class ForgetPresenter extends BasePresenter<ForgetContract.View> implements ForgetContract.Presenter { private ForgetContract.View mView; public ForgetPresenter(ForgetContract.View mView) { this.mView = mView; this.mView.setPresenter(this); } private String checkEmail(String email) { if (TextUtils.isEmpty(email)) { return "请输入与账户绑定的邮箱"; } return null; } private String checkUserName(String userName) { if (TextUtils.isEmpty(userName)) { return "请输入登录账户"; } return null; } private String checkMobile(String mobile) { if (TextUtils.isEmpty(mobile)) { return "请输入联系手机号"; } if (!StringUtil.isMobileNO(mobile)) { return "请输入正确的手机号"; } return null; } private Map<String, String> getParams(String type, String email, String userName, String mobile) { Map<String, String> map = new HashMap<>(); String jsonParams = "{\"type\":\"" + type + "\",\"email\":\"" + email + "\",\"userName\":\"" + userName + "\",\"mobile\":\"" + mobile + "\"}"; System.out.println(jsonParams); map.put(Constant.KEY_JSON_PARAMS, jsonParams); return map; } @Override public void retrievePassword(String type, String email, String userName, String mobile) { String error; if (Constant.TYPE_EMAIL.equals(type)) { if ((error = checkEmail(email)) != null) { mView.showCheckError(error); return; } if ((error = checkUserName(userName)) != null) { mView.showCheckError(error); return; } } else if (Constant.TYPE_REPRESENTATION.equals(type)) { if ((error = checkUserName(userName)) != null) { mView.showCheckError(error); return; } if ((error = checkMobile(mobile)) != null) { mView.showCheckError(error); return; } } else { mView.showCheckError("跑飞了"); return; } loginApi.forgetPassword(getParams(type, email, userName, mobile)) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(resBase -> mView.showRetrieveSuccess(resBase), mView::showRetrieveFailed); } @Override public void start() { } }
package com.jake.ffmpegandroid.record; import android.text.TextUtils; import com.jake.ffmpegandroid.common.VLog; import com.jake.ffmpegandroid.record.videocodec.VideoCodec; import com.jake.ffmpegandroid.record.videocodec.VideoCodecFactory; import com.jake.ffmpegandroid.record.videocodec.VideoCodecParameters; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Queue; import java.util.concurrent.ExecutorService; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * 视频录制 * * @author jake * @since 2017/5/2 下午6:07 */ public class VideoRecord { private static final int DEFAULT_FRAME_RATE = 25; private Queue<Frame> mInputFrameQueue; private Queue<Queue<Frame>> mRawFrameQueue; private Queue<Frame> mHandledFrameQueue; private VideoCodec mVideoCodec; private boolean isAcceptFrame = false; private long lastFrameTimestamp; private ExecutorService mExecutorService; private boolean isStop = false; private volatile int frameRate = DEFAULT_FRAME_RATE; private volatile int positionFrameRate = DEFAULT_FRAME_RATE; private VideoCodecParameters mVideoCodecParameters; private String mFilePath; public VideoRecord() { //TODO } public void setVideoCodecParameters(VideoCodecParameters parameters) { if (parameters == null) { throw new NullPointerException("parameters can't be null"); } this.mVideoCodecParameters = parameters; this.frameRate = parameters.frameRate; this.positionFrameRate = parameters.frameRate; } public void setPositionFrameRate(int positionFrameRate) { if (positionFrameRate > 0) { this.positionFrameRate = positionFrameRate; } } public void start(String filePath) { if (mVideoCodecParameters == null) { throw new NullPointerException("VideoCodecParameters is null,please setup VideoCodecParameters"); } if (TextUtils.isEmpty(filePath)) { isAcceptFrame = false; return; } mFilePath = filePath; release(); isStop = false; isAcceptFrame=true; mExecutorService = new ThreadPoolExecutor(5, 10, 5 * 1000, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(5)); mRawFrameQueue = new LinkedBlockingQueue(); mVideoCodec = VideoCodecFactory.getVideoCodec(); mVideoCodec.setCallback(codecCallback); mVideoCodec.setExecutor(mExecutorService); mVideoCodec.start(mVideoCodecParameters); mExecutorService.execute(handleRawFrameTask); mExecutorService.execute(codecTask); } public void resume() { isAcceptFrame = true; } public void pause() { isAcceptFrame = false; } public void stop() { isStop = true; flushRawFrame(); } private void release() { lastFrameTimestamp = -1; if (mRawFrameQueue != null) { mRawFrameQueue.clear(); mRawFrameQueue = null; } if (mExecutorService != null) { mExecutorService.shutdownNow(); mExecutorService = null; } if (mVideoCodec != null) { mVideoCodec.stop(); mVideoCodec = null; } } private void flushRawFrame() { if (mInputFrameQueue != null) { mRawFrameQueue.add(mInputFrameQueue); mInputFrameQueue = null; } } public void record(byte[] data, int width, int height, long timestamp) { if (!isAcceptFrame) { return; } if (lastFrameTimestamp == -1 || (timestamp - lastFrameTimestamp >= 1000)) { if (mInputFrameQueue != null) { if (timestamp - lastFrameTimestamp >= 1000) { mRawFrameQueue.offer(mInputFrameQueue); } mInputFrameQueue = null; } mInputFrameQueue = new LinkedBlockingQueue<>(); lastFrameTimestamp = timestamp; } else { mInputFrameQueue.add(Frame.create(data, width, height, timestamp)); } } private VideoCodec.Callback codecCallback = new VideoCodec.Callback() { FileOutputStream outputStream; private String lastFilePath; @Override public void onReceive(byte[] data) { VLog.d("VideoRecord codecCallback onReceive len"+data.length); try { createOutFile(); outputStream.write(data); } catch (IOException e) { e.printStackTrace(); } } @Override public void onFinish() { clearOutputStream(); } private void clearOutputStream() { if (outputStream != null) { try { outputStream.flush(); outputStream.close(); } catch (IOException e) { e.printStackTrace(); } outputStream = null; } } private void createOutFile() throws IOException { if (!TextUtils.equals(mFilePath, lastFilePath)) { File file = new File(mFilePath); if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } if (file.exists()) { file.delete(); } file.createNewFile(); if (outputStream != null) { clearOutputStream(); } outputStream = new FileOutputStream(file); lastFilePath = mFilePath; } } }; private Runnable handleRawFrameTask = new Runnable() { private boolean isNeedThisFrame(int index, int targetTotal, int total) { if (targetTotal != total) { int remove = total - (total - targetTotal); if (targetTotal > total) { remove = targetTotal % total; } if (remove <= 0) { return true; } double removeSpitD = (double) total / (double) remove; boolean needReverse = false; if (removeSpitD < 2) { removeSpitD = (double) total / (double) (total - remove); needReverse = true; } int removeSpit = (int) (removeSpitD + 0.5); if ((index % removeSpit) == 0) { return needReverse; } return !needReverse; } else { return true; } } @Override public void run() { sleepThread(1000); while (true) { if (mRawFrameQueue != null) { VLog.d("VideoRecord handleRawFrameTask mRawFrameQueue len"+mRawFrameQueue.size()); if (mRawFrameQueue.isEmpty()) { if (isStop) { break; } else { sleepThread(1000); continue; } } Queue<Frame> frameQueue = mRawFrameQueue.poll(); if (frameQueue != null) { if (mHandledFrameQueue == null) { mHandledFrameQueue = new LinkedBlockingQueue(); } int len = frameQueue.size(); if (len > 0) { if (positionFrameRate >= frameRate) {//正常速率和视频加速 int index = 0; while (!frameQueue.isEmpty()) { if (isNeedThisFrame(index, positionFrameRate, len)) { Frame frame = frameQueue.poll(); if (frame != null) { mHandledFrameQueue.offer(frame); } } index++; } } else {//减速 int index = 0; while (!frameQueue.isEmpty()) { Frame frame = frameQueue.poll(); if (frame == null) { continue; } if (isNeedThisFrame(index, positionFrameRate, len)) { frame.writeTimes += 1; } if (positionFrameRate > len) { frame.writeTimes += positionFrameRate / len; } mHandledFrameQueue.offer(frame); index++; } } } } } else { sleepThread(1000); } } } }; private void sleepThread(long millis) { try { Thread.sleep(millis); } catch (InterruptedException e) { e.printStackTrace(); } } private Runnable codecTask = new Runnable() { @Override public void run() { sleepThread(1000); while (true) { if (mHandledFrameQueue != null) { if (mHandledFrameQueue.isEmpty()) { if (isStop) { release(); break; } else { sleepThread(1000); continue; } } Frame frame = mHandledFrameQueue.poll(); if (mVideoCodec == null) { release(); break; } if (frame != null) { for (int i = 0; i < frame.writeTimes; i++) { mVideoCodec.encode(frame.data, frame.width, frame.height); } } else { continue; } } else { sleepThread(30); } } } }; private static class Frame { public static Frame create(byte[] data, int width, int height, long timestamp) { Frame frame = new Frame(); frame.data = data; frame.width = width; frame.height = height; frame.timestamp = timestamp; frame.writeTimes = 1; return frame; } public long timestamp; public int width; public int height; public byte[] data; public int writeTimes = 1; } }
package org.fuserleer; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.LongSupplier; import org.fuserleer.crypto.CryptoException; import org.fuserleer.database.DatabaseEnvironment; import org.fuserleer.database.SystemMetaData; import org.fuserleer.events.Events; import org.fuserleer.exceptions.StartupException; import org.fuserleer.exceptions.TerminationException; import org.fuserleer.executors.Executor; import org.fuserleer.executors.ScheduledExecutable; import org.fuserleer.ledger.Ledger; import org.fuserleer.logging.Logger; import org.fuserleer.logging.Logging; import org.fuserleer.network.Network; import org.fuserleer.node.LocalNode; import org.fuserleer.node.Node; import org.fuserleer.serialization.DsonOutput; import org.fuserleer.serialization.DsonOutput.Output; import org.fuserleer.serialization.Serialization; import org.java_websocket.WebSocketImpl; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableMap; public final class Context implements Service { private static final Logger log = Logging.getLogger (); private static final Map<String, Context> contexts = Collections.synchronizedMap(new HashMap<String, Context>()); private static final AtomicInteger incrementer = new AtomicInteger(0); private static Context _default = null; public final static Context create() throws StartupException { return Context.create("node-"+contexts.size(), Configuration.getDefault()); } public final static Context createCleanAndStart() throws StartupException { try { Context context = Context.create(); context.clean(); context.start(); return context; } catch (IOException ioex) { throw new StartupException(ioex); } } public final static Context create(final Configuration config) throws StartupException { Objects.requireNonNull(config); return Context.create("node-"+contexts.size(), config); } public final static Context createAndStart() throws StartupException { return createAndStart("node-"+contexts.size(), Configuration.getDefault()); } public final static Context createAndStart(final Configuration config) throws StartupException { return createAndStart("node-"+contexts.size(), config); } public final static Context createAndStart(final String name, final Configuration config) throws StartupException { Context context = create(name.toLowerCase(), config); context.start(); return context; } public final static Collection<Context> createAndStart(final int count, final String name, final Configuration configuration) throws StartupException { List<Context> contexts = new ArrayList<Context>(); try { for (int cc = 0 ; cc < count ; cc++) { Context context = Context.create(name.toLowerCase()+"-"+incrementer.get(), configuration); context.start(); contexts.add(context); } return contexts; } catch (StartupException stex) { for (Context context : contexts) { try { context.stop(); } catch (TerminationException tex) { log.fatal(tex); } } throw stex; } } public final static Context create(final String name, final Configuration configuration) throws StartupException { Objects.requireNonNull(name); Objects.requireNonNull(configuration); synchronized(contexts) { if (contexts.containsKey(name.toLowerCase()) == true) throw new IllegalStateException("Context "+name.toLowerCase()+" already created"); Configuration contextConfig = new Configuration(Objects.requireNonNull(configuration)); contextConfig.set("network.port", configuration.get("network.port", Universe.getDefault().getPort())+incrementer.get()); contextConfig.set("network.udp", configuration.get("network.udp", Universe.getDefault().getPort())+incrementer.get()); contextConfig.set("websocket.port", configuration.get("websocket.port", WebSocketImpl.DEFAULT_PORT)+incrementer.get()); if (incrementer.get() > 0) { String seeds[] = configuration.get("network.seeds", "").split(","); Set<String> seedSet = new HashSet<String>(); for (String seed : seeds) seedSet.add(seed); seedSet.add(contextConfig.get("network.address", "127.0.0.1")); contextConfig.set("network.seeds", String.join(",", seedSet)); } LocalNode node; try { node = LocalNode.load(name.toLowerCase(), contextConfig, true); } catch (CryptoException e) { throw new StartupException(e); } for (Context context : contexts.values()) if (context.node.getIdentity().equals(node.getIdentity()) == true) throw new IllegalStateException("Context "+name.toLowerCase()+":"+node+" already created"); Context context = new Context(name.toLowerCase(), node, contextConfig); Context.incrementer.incrementAndGet(); contexts.put(name.toLowerCase(), context); if (Context._default == null) Context._default = context; return context; } } public final static void stop(final Context context) throws TerminationException { Objects.requireNonNull(context).stop(); contexts.remove(context.getName()); if (Context._default == context) Context._default = null; } public final static void stopAll() throws TerminationException { synchronized(contexts) { for (Context context : contexts.values()) Objects.requireNonNull(context).stop(); contexts.clear(); Context._default = null; } } public final static void setDefault(final Context context) { Objects.requireNonNull(context); Context._default = context; } public final static Context get() { return Context._default; } public final static Context get(String name) { return contexts.get(name.toLowerCase()); } public final static Collection<Context> getAll() { return Collections.unmodifiableCollection(new ArrayList<Context>(contexts.values())); } public static void clear() { contexts.clear(); } // FIXME: This is a pretty horrible way of ensuring unit tests are stable, // as freeMemory() can return varying numbers between calls. // This is adjusted via reflection in the unit tests to be something that // returns a constant. private static LongSupplier freeMemory = () -> Runtime.getRuntime().freeMemory(); private static LongSupplier maxMemory = () -> Runtime.getRuntime().maxMemory(); private static LongSupplier totalMemory = () -> Runtime.getRuntime().totalMemory(); private final String name; private final LocalNode node; private final Configuration configuration; private final Events events; private final Network network; private final Ledger ledger; private final SystemMetaData metaData; private final DatabaseEnvironment environment; private boolean isStarted = false, isStopped = false; private long startedTimestamp = 0, stoppedTimestamp = 0; private transient Future<?> metaDataTaskFuture; /** A null Context used for unit testing */ private Context(Configuration configuration) { this.name = "null"; this.configuration = Objects.requireNonNull(configuration); this.node = null; this.environment = null; this.events = null; this.metaData = null; this.network = null; this.ledger = null; } public Context(String name, LocalNode node, Configuration configuration) { this.name = Objects.requireNonNull(name).toLowerCase(); this.configuration = Objects.requireNonNull(configuration); this.node = Objects.requireNonNull(node); this.environment = new DatabaseEnvironment(this, new File(System.getProperty("user.dir")+File.separatorChar+"database"+File.separatorChar+name)); this.events = new Events(this); this.metaData = new SystemMetaData(this); this.network = new Network(this); this.ledger = new Ledger(this); if (Boolean.parseBoolean(System.getProperty("testing.unit", "false")) == true) node.setSynced(true); } @Override public void start() throws StartupException { if (this.isStarted == true) throw new StartupException("Context "+this.getName()+" is already started"); try { this.events.start(); this.metaData.start(); if (this.metaData.has("node.local") == true) { try { byte[] nodeBytes = this.metaData.get("node.local", (byte[]) null); if (nodeBytes == null) throw new IllegalStateException("Expected node.local bytes but got null"); Node persisted = Serialization.getInstance().fromDson(nodeBytes, Node.class); if (persisted.getIdentity().equals(Context.this.node.getIdentity()) == false) // TODO what happens if has changed? Dump everything? log.warn("Node key has changed from "+persisted.getIdentity()+" to "+Context.this.node.getIdentity()); Context.this.node.fromPersisted(persisted); } catch (IOException ex) { log.error("Could not load persisted system state from SystemMetaData", ex); } } this.network.start(); this.ledger.start(); this.node.setHead(this.ledger.getHead()); this.metaDataTaskFuture = Executor.getInstance().scheduleAtFixedRate(new ScheduledExecutable(1, 1, TimeUnit.SECONDS) { @Override public void execute() { try { byte[] nodeBytes = Serialization.getInstance().toDson(Context.this.getNode(), Output.PERSIST); Context.this.metaData.put("node.local", nodeBytes); } catch (IOException e) { log.error("Could not persist local node state", e); } } }); } finally { this.isStopped = false; this.stoppedTimestamp = 0; this.isStarted = true; this.startedTimestamp = System.currentTimeMillis(); } } @Override public void stop() throws TerminationException { try { if (this.isStopped == true) throw new TerminationException("Context "+this.getName()+" is already stopped"); this.ledger.stop(); this.network.stop(); this.metaDataTaskFuture.cancel(false); this.metaData.stop(); this.events.stop(); } finally { this.isStarted = false; this.isStopped = true; this.stoppedTimestamp = System.currentTimeMillis(); } } public void clean() throws IOException { this.ledger.clean(); this.network.clean(); this.metaData.clean(); } public long startedAt() { return this.startedTimestamp; } public long stoppedAt() { return this.stoppedTimestamp; } public boolean isStarted() { return this.isStarted; } public boolean isStopped() { return this.isStopped; } public long uptime() { if (this.stoppedTimestamp < this.startedTimestamp) return System.currentTimeMillis() - this.startedTimestamp; else return this.stoppedTimestamp - this.startedTimestamp; } public Configuration getConfiguration() { return this.configuration; } public Network getNetwork() { return this.network; } public Events getEvents() { return this.events; } public LocalNode getNode() { return this.node; } public Ledger getLedger() { return this.ledger; } public SystemMetaData getMetaData() { return this.metaData; } public DatabaseEnvironment getDatabaseEnvironment() { return this.environment; } // Property "ledger" - 1 getter // No really obvious way of doing this better @JsonProperty("ledger") @DsonOutput(Output.API) Map<String, Object> getJsonLedger() { SystemMetaData smd = this.metaData; Map<String, Object> latency = ImmutableMap.of( "path", smd.get("ledger.latency.path", 0), "persist", smd.get("ledger.latency.persist", 0) ); Map<String, Object> faults = ImmutableMap.of( "tears", smd.get("ledger.faults.tears", 0), "assists", smd.get("ledger.faults.assists", 0), "stitched", smd.get("ledger.faults.stitched", 0), "failed", smd.get("ledger.faults.failed", 0) ); return ImmutableMap.<String, Object>builder(). put("processed", smd.get("ledger.processed", 0)). put("processing", smd.get("ledger.processing", 0)). put("stored", smd.get("ledger.stored", 0)). put("storedPerShard", smd.get("ledger.storedPerShard", "0")). put("storing", smd.get("ledger.storing", 0)). put("storingPerShard", smd.get("ledger.storingPerShard", 0)). put("storing.peak", smd.get("ledger.storing.peak", 0)). put("checksum", smd.get("ledger.checksum", 0)). put("latency", latency). put("faults", faults).build(); } // Property "global" - 1 getter @JsonProperty("global") @DsonOutput(Output.API) Map<String, Object> getJsonGlobal() { return ImmutableMap.of( "stored", this.metaData.get("ledger.network.stored", 0), "processing", this.metaData.get("ledger.network.processing", 0), "storing", this.metaData.get("ledger.network.storing", 0) ); } // Property "events" - 1 getter @JsonProperty("events") @DsonOutput(Output.API) Map<String, Object> getJsonEvents() { SystemMetaData smd = this.metaData; Map<String, Object> processed = ImmutableMap.of( "synchronous", smd.get("events.processed.synchronous", 0L), "asynchronous", smd.get("events.processed.asynchronous", 0L) ); return ImmutableMap.of( "processed", processed, "processing", smd.get("events.processing", 0L), "broadcast", smd.get("events.broadcast", 0L), "queued", smd.get("events.queued", 0L), "dequeued", smd.get("events.dequeued", 0L) ); } // Property "messages" - 1 getter // No obvious improvements here @JsonProperty("messages") @DsonOutput(Output.API) Map<String, Object> getJsonMessages() { Map<String, Object> outbound = ImmutableMap.of( "sent", this.metaData.get("messages.outbound.sent", 0), "processed", this.metaData.get("messages.outbound.processed", 0), "pending", this.metaData.get("messages.outbound.pending", 0), "aborted", this.metaData.get("messages.outbound.aborted", 0)); Map<String, Object> inbound = ImmutableMap.of( "processed", this.metaData.get("messages.inbound.processed", 0), "received", this.metaData.get("messages.inbound.received", 0), "pending", this.metaData.get("messages.inbound.pending", 0), "discarded", this.metaData.get("messages.inbound.discarded", 0)); return ImmutableMap.of( "inbound", inbound, "outbound", outbound); } // Property "memory" - 1 getter // No obvious improvements here @JsonProperty("memory") @DsonOutput(Output.API) Map<String, Object> getJsonMemory() { return ImmutableMap.of( "free", freeMemory.getAsLong(), "total", totalMemory.getAsLong(), "max", maxMemory.getAsLong()); } // Property "processors" - 1 getter // No obvious improvements here @JsonProperty("processors") @DsonOutput(Output.API) int getJsonProcessors() { return Runtime.getRuntime().availableProcessors(); } @Override public final String getName() { return this.name; } @Override public String toString() { return this.name+":"+this.node.getIdentity(); } }
package com.mengdo.gameframework.net; import java.util.Queue; /** * @ClassName: MessageQueue * @Description: 消息队列 * @author chenpeng * @date 2012-8-9 下午02:15:33 * */ public class MessageQueue { private Queue<GameRequest> requestQueue; private boolean running = false; private boolean gmRunning = false; public MessageQueue(Queue<GameRequest> requestQueue) { this.requestQueue = requestQueue; } public Queue<GameRequest> getRequestQueue() { return requestQueue; } /** * 清除消息队列 */ public void clear() { requestQueue.clear(); requestQueue = null; } /** * 获取消息队列长度 * * @return */ public int size() { return requestQueue != null ? requestQueue.size() : 0; } /** * 向消息队列中添加请求消息 * * @param request * @return */ public boolean add(GameRequest request) { return this.requestQueue.add(request); } /** * 设置消息队列运行状态 * * @param running */ public void setRunning(boolean running) { this.running = running; } /** * 消息队列是否正在被轮询 * * @return */ public boolean isRunning() { return running; } /** * 是否有GM消息在处理中 * @return */ public boolean isGmRunning() { return gmRunning; } public void setGmRunning(boolean gmRunning) { this.gmRunning = gmRunning; } }
package singleton.step1; public class AClass { private int intVar; //1번 private static AClass INSTANCE; //2번 변수가 null이냐 아니야. 변수의 타입은 '클래스명'과 동일 // 최소null public static AClass getInstance(){ //3.main에서 access해야하기에 public static+ 변수타입 if(INSTANCE==null) { INSTANCE = new AClass(); //객체를 만들자. instace최초만들면 new. 그 객체가 위INSTANCE가 가지고 있기 때문에 newAClass } return INSTANCE; } private AClass() {} //? public int getIntVar() { return intVar; } public void setIntVar(int intVar) { this.intVar = intVar; } }
package hello; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.SimpleTagSupport; import java.io.IOException; public class HelloWorldTagHandler extends SimpleTagSupport { public void doTag() throws JspException, IOException { getJspContext().getOut().write("Hello world!"); } }
package org.overlord.rtgov.activity.store.elasticsearch; /* * 2012-4 Red Hat Inc. and/or its affiliates and other contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * User: imk@redhat.com * Date: 22/04/14 * Time: 22:10 */ import org.elasticsearch.client.Client; import org.elasticsearch.client.transport.TransportClient; import org.elasticsearch.common.transport.InetSocketTransportAddress; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import org.overlord.commons.services.ServiceRegistryUtil; import org.overlord.rtgov.activity.model.ActivityType; import org.overlord.rtgov.activity.model.ActivityUnit; import org.overlord.rtgov.activity.model.Context; import org.overlord.rtgov.activity.model.Origin; import org.overlord.rtgov.activity.model.soa.RequestSent; import org.overlord.rtgov.activity.model.soa.ResponseReceived; import org.overlord.rtgov.activity.util.ActivityUtil; import org.overlord.rtgov.common.elasticsearch.ElasticsearchNode; import org.overlord.rtgov.common.util.RTGovProperties; import org.overlord.rtgov.common.util.RTGovPropertiesProvider; import org.overlord.rtgov.internal.common.elasticsearch.ElasticsearchNodeImpl; import java.util.Properties; import junit.framework.Assert; import static org.junit.Assert.fail; public class ElasticsearchActivityStoreTest { private static final String ENDPOINT_ID_1 = "abc123"; private static final String ENDPOINT_ID_2 = "abc456"; private static final String AU_ID_2 = "au2"; private static final String AU_ID_1 = "au1"; private static final String CONV_ID_2 = "2"; private static final String CONV_ID_1 = "1"; private static ElasticsearchActivityStore _elasticsearchActivityStore; private static ElasticsearchNodeImpl _node=null; /** * elastic search index to test against */ private final static String INDEX = "rtgovtest"; /** * elastich search host */ private final static String HOST = "embedded"; /** * elasticsearch port */ private final static int PORT = 9300; /** * elasticsearch type to test */ private final static String TYPE = "activity"; public static class TestPropertiesProvider implements RTGovPropertiesProvider { private java.util.Properties _properties = new java.util.Properties(); public TestPropertiesProvider() { System.setProperty("elasticsearch.config", "ElasticsearchActivityStoreTest-es.properties"); _properties = new Properties(); _properties.setProperty("Elasticsearch.hosts", HOST + ":" + 9300); _properties.setProperty("Elasticsearch.schedule", "3000"); _properties.setProperty("ActivityStore.Elasticsearch.type", TYPE); _properties.setProperty("ActivityStore.Elasticsearch.index", INDEX); _properties.setProperty("elasticsearch.config", "ElasticsearchActivityStoreTest-es.properties"); } public String getProperty(String name) { return _properties.getProperty(name); } public Properties getProperties() { return _properties; } } /** * tear down test index again. * @throws Exception */ @AfterClass public static void tearDown() throws Exception { Client c = new TransportClient(); if (HOST.equals("embedded")) { c = _node.getClient(); } else { c = new TransportClient().addTransportAddress(new InetSocketTransportAddress(HOST, PORT)); } c.admin().indices().prepareDelete(INDEX).execute().actionGet(); if (_node != null) { _node.close(); } if (_elasticsearchActivityStore != null) { _elasticsearchActivityStore.close(); } } /** * Initialize the store before each test. * * @throws Exception */ @BeforeClass public static void initialiseStore() throws Exception { TestPropertiesProvider provider = new TestPropertiesProvider(); Client c = null; if (HOST.equals("embedded")) { _node = (ElasticsearchNodeImpl)ServiceRegistryUtil.getSingleService(ElasticsearchNode.class); _node.init(); c = _node.getClient(); } else { c = new TransportClient().addTransportAddress(new InetSocketTransportAddress(HOST, PORT)); } // remove index. if (c.admin().indices().prepareExists(INDEX).execute().actionGet().isExists()) { c.admin().indices().prepareDelete(INDEX).execute().actionGet(); } RTGovProperties.setPropertiesProvider(provider); _elasticsearchActivityStore = new ElasticsearchActivityStore(); _elasticsearchActivityStore.init(); } @Test public void testStoreAndGetActivityUnit() { try { java.util.List<ActivityUnit> list=new java.util.ArrayList<ActivityUnit>(); list.add(createTestActivityUnit(AU_ID_1, CONV_ID_1, ENDPOINT_ID_1, 0)); _elasticsearchActivityStore.store(list); } catch (Exception e) { fail("Could not store Add activity unit " + e); } try { ActivityUnit au = _elasticsearchActivityStore.getActivityUnit(AU_ID_1); if (au != null) { if (!au.getId().equals(AU_ID_1)) fail("Activity unit reterive does not match activity unit stored. Could not get AU"); } else fail("Activity unit is null. Could not get AU"); } catch (Exception e) { fail("Could not get activity unit " + e); } try { _elasticsearchActivityStore.getClient().remove(AU_ID_1); } catch (Exception e) { fail("Could not remove activity unit " + e); } } /** * ****Works******* { "query" : { "nested" : { "path" : "activityTypes", "query" : { "match" : { "activityTypes.type" : "RequestSent" } } } }} */ /** * ****Works******* * <p/> * { * "query" : { * "nested" : { * "path" : "activityTypes", * "query" : { * "match" : { * "activityTypes.type" : "RequestSent" * } * } * } * }} * * @return */ @Test public void testStoreAndQuery() { java.util.List<ActivityUnit> activities = new java.util.ArrayList<ActivityUnit>(); ActivityUnit au1 = createTestActivityUnit(AU_ID_1, CONV_ID_1, ENDPOINT_ID_1, 0); ActivityUnit au2 = createTestActivityUnit(AU_ID_2, CONV_ID_2, ENDPOINT_ID_2, 5000); activities.add(au1); activities.add(au2); try { _elasticsearchActivityStore.store(activities); // Delay to enable search index synchronized (this) { wait(2000); } } catch (Exception e) { fail("Failed to store activities: " + e.getMessage() + ", "); } try { ActivityUnit au1r = _elasticsearchActivityStore.getActivityUnit(AU_ID_1); ActivityUnit au2r = _elasticsearchActivityStore.getActivityUnit(AU_ID_2); if (au1r != null) { if (!au1r.getId().equals(AU_ID_1)) { fail("Activity unit reterive does not match activity unit stored. Could not get AU"); } } else { fail("Activity unit is null. Could not get AU"); } if (au2r != null) { if (!au2r.getId().equals(AU_ID_2)) { fail("Activity unit reterive does not match activity unit stored. Could not get AU"); } } else { fail("Activity unit is null. Could not get AU"); } // Check activity unit is the same String au1ser=new String(ActivityUtil.serializeActivityUnit(au1)); String au1rser=new String(ActivityUtil.serializeActivityUnit(au1r)); // Unfortunately the context objects are not serialized in any particular order, so we need // to test for equality in multiple steps if (au1rser.length() != au1ser.length()) { fail("Lengths don't match"); } if (!au1ser.substring(0, 270).equals(au1rser.substring(0, 270))) { fail("First 270 did not match"); } if (!au1ser.substring(350).equals(au1rser.substring(350))) { fail("From 350 did not match"); } } catch (Exception e) { fail("Could not get activity unit " + e); } try { _elasticsearchActivityStore.getClient().remove(AU_ID_1); _elasticsearchActivityStore.getClient().remove(AU_ID_2); } catch (Exception e) { fail("Could not remove activity unit " + e); } } @Test public void testGetActivityTypesWithContextAndTimeframe() { java.util.List<ActivityType> results1 = null; java.util.List<ActivityType> results2 = null; java.util.List<ActivityUnit> activities = new java.util.ArrayList<ActivityUnit>(); ActivityUnit au1 = createTestActivityUnit("7", "C1", "E1", 10000); ActivityUnit au2 = createTestActivityUnit("8", "C1", "E2", 15000); // Setting endpoint value to C1 to make sure does not get value and type picked up // from different context objects ActivityUnit au3 = createTestActivityUnit("9", "C2", "C1", 20000); activities.add(au1); activities.add(au2); activities.add(au3); try { //store both ATs _elasticsearchActivityStore.store(activities); } catch (Exception e) { e.printStackTrace(); fail("Could not store activity units " + e); } Context context1 = new Context(); context1.setType(Context.Type.Conversation); context1.setValue("C1"); try { results1 = _elasticsearchActivityStore.getActivityTypes(context1); } catch (Exception e) { e.printStackTrace(); fail("Could not get activity units " + e); } Context context2 = new Context(); context2.setType(Context.Type.Conversation); context2.setValue("C1"); try { results2 = _elasticsearchActivityStore.getActivityTypes(context2, 12500, 17500); } catch (Exception e) { e.printStackTrace(); fail("Could not get activity units " + e); } if (results1 == null) { fail("Results1 is null"); } if (results1.size() != 2) { fail("Expecting 2 results: " + results1.size()); } if (results2 == null) { fail("Results2 is null"); } if (results2.size() != 1) { fail("Expecting 1 result: " + results2.size()); } if (!results2.get(0).getUnitId().equals("8")) { fail("Expecting au 8: " + results2.get(0).getUnitId()); } try { _elasticsearchActivityStore.getClient().remove("7"); _elasticsearchActivityStore.getClient().remove("8"); _elasticsearchActivityStore.getClient().remove("9"); } catch (Exception e) { fail("Could not remove activity unit " + e); } } @Test public void testGetActivityTypesWithNoContextAndTimeframe() { java.util.List<ActivityType> results1 = null; java.util.List<ActivityUnit> activities = new java.util.ArrayList<ActivityUnit>(); ActivityUnit au1 = createTestActivityUnit("7", "C1", "E1", 30000); ActivityUnit au2 = createTestActivityUnit("8", "C1", "E2", 35000); // Setting endpoint value to C1 to make sure does not get value and type picked up // from different context objects ActivityUnit au3 = createTestActivityUnit("9", "C2", "C1", 40000); activities.add(au1); activities.add(au2); activities.add(au3); try { //store both ATs _elasticsearchActivityStore.store(activities); } catch (Exception e) { e.printStackTrace(); fail("Could not store activity units " + e); } try { results1 = _elasticsearchActivityStore.getActivityTypes(null, 32500, 37500); } catch (Exception e) { e.printStackTrace(); fail("Could not get activity units " + e); } if (results1 == null) { fail("Results1 is null"); } if (results1.size() != 2) { fail("Expecting 2 results: " + results1.size()); } try { _elasticsearchActivityStore.getClient().remove("7"); _elasticsearchActivityStore.getClient().remove("8"); _elasticsearchActivityStore.getClient().remove("9"); } catch (Exception e) { fail("Could not remove activity unit " + e); } } @Test public void testGetActivityTypesWithNoContextAndNoTimeframe() { try { _elasticsearchActivityStore.getActivityTypes(null, 0, 0); fail("Should have reported exception"); } catch (Exception e) { } } protected ActivityUnit createTestActivityUnit(String id, String convId, String endpointId, long baseTime) { ActivityUnit act = new ActivityUnit(); act.setId(id); Origin origin = new Origin(); origin.setHost("MyHost"); origin.setNode("MyNode"); origin.setPrincipal("Me"); origin.setThread("MyThread"); act.setOrigin(origin); RequestSent me1 = new RequestSent(); me1.setUnitId(id); me1.setUnitIndex(0); me1.setTimestamp(baseTime + 1000); me1.setContent("<tns:Order xmlns:tns=\"http://www.savara.org\" amount=\"100\" />"); me1.setMessageType("{http://message}Order"); me1.setOperation("myOp"); me1.setServiceType("{http://service}OrderService"); me1.setMessageId("corr1"); me1.getProperties().put("customer", "Fred"); me1.getProperties().put("trader", "Joe"); me1.getProperties().put("sss", "Joe"); me1.getProperties().put("sss", "Joe"); if (baseTime==0) { me1.getProperties().put("cccc","ysdasdasdda"); } Context c1 = new Context(); c1.setType(Context.Type.Conversation); c1.setValue(convId); me1.getContext().add(c1); act.getActivityTypes().add(me1); ResponseReceived me2 = new ResponseReceived(); me2.setUnitId(id); me2.setUnitIndex(1); me2.setTimestamp(baseTime + 2000); me2.setContent("<tns:Confirmation xmlns:tns=\"http://www.savara.org\" amount=\"100\" />"); me2.setFault("MyFault"); me2.setMessageType("{http://message}Confirmation"); me2.setOperation("myOp"); me2.setServiceType("{http://service}OrderService"); me2.setMessageId("corr2"); me2.setReplyToId("corr1"); me2.getProperties().put("customer", "Fred"); me2.getProperties().put("manager", "Jane"); Context c2 = new Context(); c2.setType(Context.Type.Endpoint); c2.setValue(endpointId); me2.getContext().add(c2); act.getActivityTypes().add(me2); return (act); } }
package com.zp.dao; import com.zp.pojo.Resume; import org.springframework.data.jpa.repository.JpaRepository; public interface ResumeDao extends JpaRepository<Resume, Long> { }
package ir.aligorji.automapper.example.mapper; import android.support.annotation.NonNull; import ir.aligorji.automapper.example.holder.ParentHolder; import ir.aligorji.automapper.example.holder.UserHolder; import ir.aligorji.automapper.AutoMapper; import ir.aligorji.automapper.example.model.ParentModel; import ir.aligorji.automapper.example.model.UserModel; public final class Mapper { public static void config() { AutoMapper.createMap(UserModel.class, UserHolder.class).usingAuto(); AutoMapper.createMap(ParentModel.class, ParentHolder.class).usingAuto(new AutoMapper.Action<ParentModel, ParentHolder>() { @Override public void before(@NonNull ParentModel source, @NonNull ParentHolder destination) { } @Override public void after(@NonNull ParentModel source, @NonNull ParentHolder destination) { } }); AutoMapper.build(); /*AutoMapper.createMap(ParentModel.class, ParentHolder.class).using(new AutoMapper.Mapper<ParentModel, ParentHolder>() { @Override public void onMap(@NonNull ParentModel source, @NonNull ParentHolder destination) { destination.id = source.id; } });*/ } }
package com.cloud.ribbon.consumer.ribbon_consumer.service; import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.web.client.RestTemplate; @Service public class HelloService { @Autowired RestTemplate restTemplate; @HystrixCommand(fallbackMethod = "helloFallback",commandKey = "helloKsy") public String sayHello(){ String msg = restTemplate.getForObject("http://ribbon-provider/hello?name=bighead",String.class); return msg; } public String helloFallback(){ return "error"; } }
package com.frank.servicelmpl; import com.frank.bean.Fan; import com.frank.bean.Subscribe; import com.frank.dao.Subs_fanMapper; import com.frank.service.Subs_fanService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; /** * Created by 啸 on 2017/6/1. */ @Service public class Subs_fanServicelmpl implements Subs_fanService { @Autowired() private Subs_fanMapper subs_fanMapper; public int countUserSubscribe(String username) { return subs_fanMapper.countUserSubscribe(username); } public int countUserFans(String username) { return subs_fanMapper.countUserFans(username); } public List<Subscribe> showUserSubscribe(String username) { return subs_fanMapper.showUserSubscribe(username); } public void unfollowUser(String username, String sub_name) { subs_fanMapper.unfollowUser(username,sub_name); } public void followUser(String username, String sub_name) { subs_fanMapper.followUser(username,sub_name); } public List<Fan> showUserFans(String username) { return subs_fanMapper.showUserFans(username); } }
package go.nvhieucs.notins.model.follow; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.cassandra.core.CassandraTemplate; import org.springframework.data.cassandra.core.mapping.CassandraPersistentEntity; import org.springframework.data.cassandra.repository.query.CassandraEntityInformation; import org.springframework.data.cassandra.repository.support.MappingCassandraEntityInformation; import java.util.UUID; @Configuration public class FollowConfig { @Bean public FollowRepositoryImpl followRepository(final CassandraTemplate cassandraTemplate) { final CassandraPersistentEntity<?> persistentEntity = cassandraTemplate.getConverter() .getMappingContext().getRequiredPersistentEntity(Follow.class); final CassandraEntityInformation<Follow, FollowKey> entityInformation = new MappingCassandraEntityInformation<Follow, FollowKey>( (CassandraPersistentEntity<Follow>) persistentEntity, cassandraTemplate.getConverter()); return new FollowRepositoryImpl(entityInformation, cassandraTemplate); } }
package com.hb.rssai.view.service; import android.annotation.TargetApi; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Build; import android.widget.RemoteViews; import com.hb.rssai.R; import com.hb.rssai.bean.ResInformation; import com.hb.rssai.constants.Constant; import com.hb.rssai.view.common.ContentActivity; import com.hb.rssai.view.common.RichTextActivity; import java.util.HashMap; import java.util.Map; import rx.android.schedulers.AndroidSchedulers; import rx.schedulers.Schedulers; import static com.hb.rssai.presenter.BasePresenter.informationApi; /** * Created by LIUYONGKUI726 on 2017-07-10. */ @TargetApi(Build.VERSION_CODES.CUPCAKE) public class WidgetProvider extends AppWidgetProvider { final String clickAction = "com.rssai.WidgetProvider.onclick"; final String refreshAction = "refresh"; @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH) public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { // System.out.println(WidgetProvider.class.getSimpleName() + "============================================================>" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())); final int N = appWidgetIds.length; for (int i=0; i<N; i++) { int appWidgetId = appWidgetIds[i]; // 获取Widget的组件名 ComponentName thisWidget = new ComponentName(context, WidgetProvider.class); // 创建一个RemoteView RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.app_widget); // 把这个Widget绑定到RemoteViewsService Intent intent = new Intent(context, ListWidgetService.class); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[0]); // 设置适配器 remoteViews.setRemoteAdapter(R.id.list_view, intent); // 设置当显示的widget_list为空显示的View remoteViews.setEmptyView(R.id.list_view, R.layout.layout_no_data); // 点击列表触发事件 Intent clickIntent = new Intent(context, WidgetProvider.class); // 设置Action,方便在onReceive中区别点击事件 clickIntent.setAction(clickAction); clickIntent.setData(Uri.parse(clickIntent.toUri(Intent.URI_INTENT_SCHEME))); PendingIntent pendingIntentTemplate = PendingIntent.getBroadcast(context, 0, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT); remoteViews.setPendingIntentTemplate(R.id.list_view, pendingIntentTemplate); // 刷新按钮 final Intent refreshIntent = new Intent(context, WidgetProvider.class); refreshIntent.setAction(refreshAction); final PendingIntent refreshPendingIntent = PendingIntent.getBroadcast(context, 0, refreshIntent, PendingIntent.FLAG_UPDATE_CURRENT); remoteViews.setOnClickPendingIntent(R.id.widget_iv_refresh, refreshPendingIntent); // 创建一个RemoteView RemoteViews remoteViews2 = new RemoteViews(context.getPackageName(), R.layout.app_widget_lock_screen); // 把这个Widget绑定到RemoteViewsService Intent intent2 = new Intent(context, ListWidgetService.class); intent2.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetIds[0]); // 设置适配器 remoteViews2.setRemoteAdapter(R.id.list_view, intent2); // 设置当显示的widget_list为空显示的View remoteViews2.setEmptyView(R.id.list_view, R.layout.layout_no_data); // 点击列表触发事件 Intent clickIntent2 = new Intent(context, WidgetProvider.class); // 设置Action,方便在onReceive中区别点击事件 clickIntent2.setAction(clickAction); clickIntent2.setData(Uri.parse(clickIntent2.toUri(Intent.URI_INTENT_SCHEME))); PendingIntent pendingIntentTemplate2 = PendingIntent.getBroadcast(context, 0, clickIntent2, PendingIntent.FLAG_UPDATE_CURRENT); remoteViews2.setPendingIntentTemplate(R.id.list_view, pendingIntentTemplate2); // 刷新按钮 final Intent refreshIntent2 = new Intent(context, WidgetProvider.class); refreshIntent2.setAction(refreshAction); final PendingIntent refreshPendingIntent2 = PendingIntent.getBroadcast(context, 0, refreshIntent2, PendingIntent.FLAG_UPDATE_CURRENT); remoteViews2.setOnClickPendingIntent(R.id.widget_iv_refresh, refreshPendingIntent2); // 更新Wdiget appWidgetManager.updateAppWidget(appWidgetId, remoteViews); // 更新Wdiget appWidgetManager.updateAppWidget(appWidgetId, remoteViews2); } } /** * 接收Intent */ private Context mContext; @Override public void onReceive(Context context, Intent intent) { super.onReceive(context, intent); String action = intent.getAction(); System.out.println(WidgetProvider.class.getSimpleName() + "============================================================>" + action ); if (action.equals(refreshAction)) { mContext = context; getLikeByTitle(context); // 刷新Widget // final AppWidgetManager mgr = AppWidgetManager.getInstance(context); // final ComponentName cn = new ComponentName(context, WidgetProvider.class); // WdRemoteViewsFactory.listData.clear(); // 这句话会调用RemoteViewSerivce中RemoteViewsFactory的onDataSetChanged()方法。 // mgr.notifyAppWidgetViewDataChanged(mgr.getAppWidgetIds(cn), R.id.list_view); } else if (action.equals(clickAction)) { Intent toIntent = new Intent(context, RichTextActivity.class); toIntent.putExtra(ContentActivity.KEY_TITLE, intent.getStringExtra(ContentActivity.KEY_TITLE)); toIntent.putExtra(ContentActivity.KEY_URL, intent.getStringExtra(ContentActivity.KEY_URL)); toIntent.putExtra(ContentActivity.KEY_INFORMATION_ID, intent.getStringExtra(ContentActivity.KEY_INFORMATION_ID)); toIntent.putExtra("pubDate", intent.getStringExtra("pubDate")); toIntent.putExtra("whereFrom", intent.getStringExtra("whereFrom")); toIntent.putExtra("abstractContent", intent.getStringExtra("abstractContent")); toIntent.putExtra("clickGood", intent.getLongExtra("clickGood", 0)); toIntent.putExtra("clickNotGood", intent.getLongExtra("clickNotGood", 0)); toIntent.putExtra("id", intent.getStringExtra("id")); toIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(toIntent); }else{ mContext = context; getLikeByTitle(context); } } public void getLikeByTitle(Context context) { informationApi.getLikeByTitle(getParams()).subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(resInfo -> { setListResult(resInfo, context); }, this::loadError); } private void setListResult(ResInformation resInformation, Context context) { if (resInformation.getRetObj() == null || resInformation.getRetObj().getRows() == null) { return; } if (WdRemoteViewsFactory.listData != null) { WdRemoteViewsFactory.listData.clear(); } WdRemoteViewsFactory.listData = resInformation.getRetObj().getRows(); // 刷新Widget final AppWidgetManager mgr = AppWidgetManager.getInstance(context); final ComponentName cn = new ComponentName(context, WidgetProvider.class); // WdRemoteViewsFactory.listData.clear(); // 这句话会调用RemoteViewSerivce中RemoteViewsFactory的onDataSetChanged()方法。 mgr.notifyAppWidgetViewDataChanged(mgr.getAppWidgetIds(cn), R.id.list_view); } private void loadError(Throwable throwable) { throwable.printStackTrace(); } private Map<String, String> getParams() { Map<String, String> map = new HashMap<>(); String des = ""; String title = ""; String jsonParams = "{\"title\":\"" + title + "\"}"; map.put(Constant.KEY_JSON_PARAMS, jsonParams); return map; } }
package com.tencent.mm.g.a; import android.os.Bundle; public final class np$b { public boolean bYJ; public Bundle extras; }
package com.myself.email.config; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; /** * @Author:UncleCatMySelf * @Email:zhupeijie_java@126.com * @QQ:1341933031 * @Date:Created in 21:33 2018\9\10 0010 */ @Data @Component @ConfigurationProperties(prefix = "email") public class EmailConfig { private String from; }
package kodlamaio.hrms.entities.concreates; import java.time.LocalDate; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty.Access; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @Data @Entity @AllArgsConstructor @NoArgsConstructor @Table(name="resumes") public class Resume { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name="id") private int id; @JsonProperty(access = Access.WRITE_ONLY) @ManyToOne(targetEntity = Candidate.class) @JoinColumn(name ="candidate_id",referencedColumnName ="id",nullable = false) private Candidate candidate; @Column(name="photo_url") private String photoUrl; @Column(name="github_link") private String githubLink; @Column(name="linked_link") private String linkedLink; @Column(name="description") private String description; @Column(name="is_active") private boolean isActive; @Column(name = "created_at",updatable = false) private LocalDate createdAt; @Column(name="updated_at") private LocalDate updatedAt; @OneToMany(mappedBy ="resume" ) private List<School> schools; @OneToMany(mappedBy ="resume" ) private List<Language> languages; @OneToMany(mappedBy ="resume" ) private List<Ability> abilities; @OneToMany(mappedBy ="resume" ) private List<JobExperience> jobExperiences; }
package com.tencent.mm.plugin.sns.model; import com.tencent.mm.protocal.c.ate; final class ay { String bKW; ate caK; int dQm; int dQo; int dTR; String elz; String nsF; ay() { } public final String toString() { return "cdnMediaId " + this.elz + " isPlayMode " + this.dQm + " createTime " + this.dTR + " snsLocalId " + this.bKW + " postName " + this.nsF + " url " + this.caK.jPK; } }
package com.faisal.evaly.repositories; import com.faisal.evaly.models.Category; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; @Repository public interface CategoryRepository extends CrudRepository<Category, Long> { }
package org.linqs.psl.LTR_Rec.modelSettings; import org.linqs.psl.LTR_Rec.modelSettings.ModelSetting; import org.linqs.psl.model.term.ConstantType; import java.util.HashMap; public class YelpSetting extends ModelSetting { @Override public String[] getSettingRules() { String[] rules = new String[21]; // Similarities like Pearson, Cosine, and Adjusted Cosine Similarity between items. rules[0] = "1.0 : rated(U,I1) & rated(U,I2) & rating(U,I1) & sim_pearson_items(I1,I2) >> rating(U,I2)^2"; rules[1] = "1.0 : rated(U,I1) & rated(U,I2) & rating(U,I1) & sim_cosine_items(I1,I2) >> rating(U,I2)^2"; rules[2] = "1.0 : rated(U,I1) & rated(U,I2) & rating(U,I1) & sim_adjcos_items(I1,I2) >> rating(U,I2)^2"; // Similarities like Pearson and Cosine Similarity between users. rules[3] = "1.0 : rated(U1,I) & rated(U2,I) & rating(U1,I) & sim_pearson_users(U1,U2) >> rating(U2,I)^2"; rules[4] = "1.0 : rated(U1,I) & rated(U2,I) & rating(U1,I) & sim_cosine_users(U1,U2) >> rating(U2,I)^2"; // Other low dimension space similarities like Matrix Factorization Cosine and Euclidean Similarity between users. rules[5] = "1.0 : user(U1) & user(U2) & item(I) & rating(U1,I) & rated(U1,I) &rated(U2,I) & sim_mf_cosine_users(U1,U2) >> rating(U2,I)^2"; rules[6] = "1.0 : user(U1) & user(U2) & item(I) & rating(U1,I) & rated(U1,I) &rated(U2,I) & sim_mf_euclidean_users(U1,U2) >> rating(U2,I)^2"; // Other low dimension space similarities like Matrix Factorization Cosine and Euclidean Similarity between items. rules[7] = "1.0 : user(U) & item(I1) & item(I2) & rating(U,I1) & rated(U,I1) & rated(U,I2) & sim_mf_cosine_items(I1,I2) >> rating(U,I2)^2"; rules[8] = "1.0 : user(U) & item(I1) & item(I2) & rating(U,I1) & rated(U,I1) & rated(U,I2) & sim_mf_euclidean_items(I1,I2) >> rating(U,I2)^2"; // Predictions by different other methods like SGD, Item based Pearson methods, and BPMF methods. rules[9] = "1.0 : sgd_rating(U,I) >> rating(U,I)^2"; rules[10] = "1.0 : rating(U,I) >> sgd_rating(U,I)^2"; rules[11] = "1.0 : item_pearson_rating(U,I) >> rating(U,I)^2"; rules[12] = "1.0 : rating(U,I) >> item_pearson_rating(U,I)^2"; rules[13] = "1.0 : bpmf_rating(U,I) >> rating(U,I)^2"; rules[14] = "1.0 : rating(U,I) >> bpmf_rating(U,I)^2"; // Average prior of user rating and item ratings. rules[15] = "1.0 : user(U) & item(I) & rated(U,I) & avg_user_rating(U) >> rating(U,I)^2"; rules[16] = "1.0 : user(U) & item(I) & rated(U,I) & rating(U,I) >> avg_user_rating(U)^2"; rules[17] = "1.0 : user(U) & item(I) & rated(U,I) & avg_item_rating(I) >> rating(U,I)^2"; rules[18] = "1.0 : user(U) & item(I) & rated(U,I) & rating(U,I) >> avg_item_rating(I)^2"; // Social rule of friendship influencing ratings. rules[19] = "1.0 : rated(U1,I) & rated(U2,I) & users_are_friends(U1,U2) & rating(U1,I) >> rating(U2,I)^2"; // Content rule by Jaccard similarity. rules[20] = "1.0 : rated(U,I1) & rated(U,I2) & rating(U,I1) & sim_content_items_jaccard(I1,I2) >> rating(U,I2)^2"; return rules; } @Override public HashMap<String, ConstantType[]> getSettingPredicates() { HashMap<String, ConstantType[]> predicates = new HashMap<>(); predicates.put("user", new ConstantType[] {ConstantType.UniqueStringID}); predicates.put("item", new ConstantType[] {ConstantType.UniqueStringID}); predicates.put("users_are_friends", new ConstantType[] {ConstantType.UniqueStringID, ConstantType.UniqueStringID}); predicates.put("sim_content_items_jaccard", new ConstantType[] {ConstantType.UniqueStringID, ConstantType.UniqueStringID}); predicates.put("sim_pearson_items",new ConstantType[] { ConstantType.UniqueStringID, ConstantType.UniqueStringID}); predicates.put("sim_cosine_items", new ConstantType[] {ConstantType.UniqueStringID, ConstantType.UniqueStringID}); predicates.put("sim_adjcos_items", new ConstantType[] {ConstantType.UniqueStringID, ConstantType.UniqueStringID}); predicates.put("sim_pearson_users", new ConstantType[] {ConstantType.UniqueStringID, ConstantType.UniqueStringID}); predicates.put("sim_cosine_users", new ConstantType[] {ConstantType.UniqueStringID, ConstantType.UniqueStringID}); predicates.put("sim_mf_cosine_users", new ConstantType[] {ConstantType.UniqueStringID, ConstantType.UniqueStringID}); predicates.put("sim_mf_euclidean_users", new ConstantType[] {ConstantType.UniqueStringID, ConstantType.UniqueStringID}); predicates.put("sim_mf_cosine_items", new ConstantType[] {ConstantType.UniqueStringID, ConstantType.UniqueStringID}); predicates.put("sim_mf_euclidean_items", new ConstantType[] {ConstantType.UniqueStringID, ConstantType.UniqueStringID}); predicates.put("avg_user_rating", new ConstantType[] {ConstantType.UniqueStringID}); predicates.put("avg_item_rating", new ConstantType[] {ConstantType.UniqueStringID}); predicates.put("rated", new ConstantType[] {ConstantType.UniqueStringID, ConstantType.UniqueStringID}); predicates.put("sgd_rating", new ConstantType[] {ConstantType.UniqueStringID, ConstantType.UniqueStringID}); predicates.put("bpmf_rating", new ConstantType[] {ConstantType.UniqueStringID, ConstantType.UniqueStringID}); predicates.put("item_pearson_rating", new ConstantType[] {ConstantType.UniqueStringID, ConstantType.UniqueStringID}); predicates.put("rating", new ConstantType[] {ConstantType.UniqueStringID, ConstantType.UniqueStringID}); return predicates; } private String predicateNameToDataPrefix(String PredicateName) { String prefix; switch (PredicateName){ case "Preference": prefix = "rel_rank"; break; case "SimilarUsersBlock": prefix = "sim_cosine_users"; break; case "SimilarItemsBlock": prefix = "sim_cosine_items"; break; default: throw new IllegalArgumentException("Predicate Name:" + PredicateName + " does not exist for Yelp"); } return prefix; } @Override public HashMap<String, String> getObservedPredicateData() { return getObservedPredicateData(new String[0]); } @Override public HashMap<String, String> getObservedPredicateData(String[] ablationPredicateNames) { HashMap<String, String> ObservedPredicateData = new HashMap<>(); // Default ObservedPredicateData.put("user", "user"); ObservedPredicateData.put("item", "item"); ObservedPredicateData.put("users_are_friends", "users_are_friends"); ObservedPredicateData.put("sim_content_items_jaccard", "sim_content_items_jaccard"); ObservedPredicateData.put("sim_pearson_items", "sim_pearson_items"); ObservedPredicateData.put("sim_cosine_items", "sim_cosine_items"); ObservedPredicateData.put("sim_adjcos_items", "sim_adjcos_items"); ObservedPredicateData.put("sim_pearson_users", "sim_pearson_users"); ObservedPredicateData.put("sim_cosine_users", "sim_cosine_users"); ObservedPredicateData.put("sim_mf_cosine_users", "sim_mf_cosine_users"); ObservedPredicateData.put("sim_mf_euclidean_users", "sim_mf_euclidean_users"); ObservedPredicateData.put("sim_mf_cosine_items", "sim_mf_cosine_items"); ObservedPredicateData.put("sim_mf_euclidean_items", "sim_mf_euclidean_items"); ObservedPredicateData.put("avg_user_rating", "avg_user_rating"); ObservedPredicateData.put("avg_item_rating", "avg_item_rating"); ObservedPredicateData.put("rated", "rated"); ObservedPredicateData.put("sgd_rating", "sgd_rating"); ObservedPredicateData.put("bpmf_rating", "bpmf_rating"); ObservedPredicateData.put("item_pearson_rating", "item_pearson_rating"); // Ablation predicates for(String predicateName: ablationPredicateNames){ ObservedPredicateData.put(predicateName, this.predicateNameToDataPrefix(predicateName)); } return ObservedPredicateData; } @Override public HashMap<String, String> getTargetPredicateData() { return getTargetPredicateData(new String[0]); } @Override public HashMap<String, String> getTargetPredicateData(String[] ablationPredicateNames) { HashMap<String, String> TargetPredicateData = new HashMap<>(); // Default TargetPredicateData.put("Rating", "rating"); // Ablation predicates for(String predicateName: ablationPredicateNames){ TargetPredicateData.put(predicateName, this.predicateNameToDataPrefix(predicateName)); } return TargetPredicateData; } @Override public HashMap<String, String> getTruthPredicateData() { return getTruthPredicateData(new String[0]); } @Override public HashMap<String, String> getTruthPredicateData(String[] ablationPredicateNames) { HashMap<String, String> TruthPredicateData = new HashMap<>(); // Default TruthPredicateData.put("Rating", "rating"); // Ablation predicates for(String predicateName: ablationPredicateNames){ TruthPredicateData.put(predicateName, this.predicateNameToDataPrefix(predicateName)); } return TruthPredicateData; } @Override public String[] getOpenPredicateNames() { String[] openPredicates = new String[1]; openPredicates[0] = "Rating"; return new String[0]; } @Override public String[] getClosedPredicateNames() { String[] closedPredicateNames = new String[19]; closedPredicateNames[0] = "user"; closedPredicateNames[1] = "item"; closedPredicateNames[2] = "users_are_friends"; closedPredicateNames[3] = "sim_content_items_jaccard"; closedPredicateNames[4] = "sim_pearson_items"; closedPredicateNames[5] = "sim_cosine_items"; closedPredicateNames[6] = "sim_adjcos_items"; closedPredicateNames[7] = "sim_pearson_users"; closedPredicateNames[8] = "sim_cosine_users"; closedPredicateNames[9] = "sim_mf_cosine_users"; closedPredicateNames[10] = "sim_mf_euclidean_users"; closedPredicateNames[11] = "sim_mf_cosine_items"; closedPredicateNames[12] = "sim_mf_euclidean_items"; closedPredicateNames[13] = "avg_user_rating"; closedPredicateNames[14] = "avg_item_rating"; closedPredicateNames[15] = "rated"; closedPredicateNames[16] = "sgd_rating"; closedPredicateNames[17] = "bpmf_rating"; closedPredicateNames[18] = "item_pearson_rating"; return closedPredicateNames; } @Override public String[] getBlockingPredicateNames() { return new String[0]; } }
package com.zhuzhixu.adminproject.dao; import com.zhuzhixu.adminproject.entity.ProductEntity; import org.apache.ibatis.annotations.Select; import org.apache.ibatis.annotations.Update; import java.util.Date; import java.util.List; public interface ProductMapper { @Select("select * from t_product") List<ProductEntity> getAllEntity(); @Select("select * form t_product where id=#{id}") ProductEntity getProductEnyityById(long id); @Update("update t_product set name=#{name}, description=#{description}, category=#{category} where id = #{id}") void updateProduct(long id, String name, String description, String category, int amount, Date time); }
/* * The programm will show you the reverse of your number */ package Lab06C; /** * * @author Aliaksiej Protas */ public class Lab06C { public static void main(String[] args) { View.print("The programm will show you the " + " reverse of your number "); while (true){ int number = UserInput.input("Please, input the number"); View.print("The reverse number is " + ReverseNumber.findReverse(number)); if (!Complete.complete("Do you want to continue?")){ break; } } } }
package com.tencent.mm.plugin.webview.ui.tools.widget; import com.tencent.mm.ui.widget.MMWebView; import com.tencent.xweb.WebView; public final class h extends g { private final b qkG; public h(MMWebView mMWebView, b bVar) { super((MMWebViewWithJsApi) mMWebView); this.qkG = bVar; } public final void d(WebView webView, String str) { if (this.qkG != null) { this.qkG.iZ(str); } else { super.d(webView, str); } } }
package com.sudheer; import java.util.Date; import org.hibernate.Session; import com.sudheer.stock.Stock; import com.sudheer.stock.StockDetail; import com.sudheer.util.HibernateUtil; public class App { public static void main(String[] args) { System.out.println("Hibernate one to one (Annotation)"); Session session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); Stock stock = new Stock(); stock.setStockCode("666"); stock.setStockName("WMart"); StockDetail stockDetail = new StockDetail(); stockDetail.setCompName("Wal-Mart Stores"); stockDetail.setCompDesc("Best retail corporation in the world"); stockDetail.setRemark(""); stockDetail.setListedDate(new Date()); stock.setStockDetail(stockDetail); stockDetail.setStock(stock); session.save(stock); session.getTransaction().commit(); System.out.println("Done"); } }
package uk.co.samwho.modopticon; public class Main { public static void main(String... args) throws Exception { Modopticon modopticon = DaggerModopticon.builder().build(); modopticon.inits().forEach(Runnable::run); modopticon.jda().awaitReady(); modopticon.backfiller().run(); modopticon.apiServer().run(); } }
import java.util.ArrayList; /** * Created by diegobaldassare on 4/12/16. */ public class Game { private ArrayList<Piece> pieces; private Board board; private HumanPlayer user = new HumanPlayer(this); private ComputerPlayer computer = new ComputerPlayer(this); private UIGame uiGame; private boolean turn; //true: user turn private boolean win; //true: user won private boolean endGame; public Game() { uiGame = new UIGame(this); pieces = new ArrayList<>(); board = new Board(); for (int i = 0; i < 7; i++) { for (int j = i; j < 7; j++) { pieces.add(new Piece(i, j)); } } giveOut(); begin(); } public void giveOut() { int random; while (!pieces.isEmpty()) { random = (int)Math.random() * pieces.size(); user.receivePieces(pieces.get(random)); pieces.remove(random); random = (int)Math.random() * pieces.size(); computer.receivePieces(pieces.get(random)); pieces.remove(random); } } //empieza el juego public void begin(){ if(user.starts()){ turn = true; //falta algo?? } else { turn = false; } } //termina el juego y da un ganador public void endGame(AbstractPlayer player){ if(player instanceof HumanPlayer){ win = true; } else { win = false; } endGame = true; } //si el juego termino devuelve quien gano public boolean win(){ if(endGame){ return win; } else { throw new RuntimeException("Unfinished Game"); } } //devuelve si el juego termino public boolean isGameEnded(){ return endGame; } //si es true juega el humano, si es false juega la computadora public boolean turns(){ boolean result = turn; turn = !turn; return result; } public HumanPlayer getUser() { return user; } public Board getBoard() { return board; } public UIGame getUiGame() { return uiGame; } }
package com.example.android.dreamdestinations.Model; import android.os.Parcel; import android.os.Parcelable; /** * Created by joycelin12 on 9/21/18. */ public class Agents implements Parcelable { String Id; String Name; String ImageUrl; String Status; String OptimisedForMobile; String Type; public Agents(String id, String name, String imageUrl, String status, String optimisedForMobile, String type) { Id = id; Name = name; ImageUrl = imageUrl; Status = status; OptimisedForMobile = optimisedForMobile; Type = type; } public String getId() { return Id; } public void setId(String id) { Id = id; } public String getName() { return Name; } public void setName(String name) { Name = name; } public String getImageUrl() { return ImageUrl; } public void setImageUrl(String imageUrl) { ImageUrl = imageUrl; } public String getStatus() { return Status; } public void setStatus(String status) { Status = status; } public String getOptimisedForMobile() { return OptimisedForMobile; } public void setOptimisedForMobile(String optimisedForMobile) { OptimisedForMobile = optimisedForMobile; } public String getType() { return Type; } public void setType(String type) { Type = type; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(this.Id); dest.writeString(this.Name); dest.writeString(this.ImageUrl); dest.writeString(this.Status); dest.writeString(this.OptimisedForMobile); dest.writeString(this.Type); } protected Agents(Parcel in) { this.Id = in.readString(); this.Name = in.readString(); this.ImageUrl = in.readString(); this.Status = in.readString(); this.OptimisedForMobile = in.readString(); this.Type = in.readString(); } public static final Parcelable.Creator<Agents> CREATOR = new Parcelable.Creator<Agents>() { @Override public Agents createFromParcel(Parcel source) { return new Agents(source); } @Override public Agents[] newArray(int size) { return new Agents[size]; } }; }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.net.telnet; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InterruptedIOException; final class TelnetInputStream extends BufferedInputStream implements Runnable { /** End of file has been reached */ private static final int EOF = -1; /** Read would block */ private static final int WOULD_BLOCK = -2; // TODO should these be private enums? static final int STATE_DATA = 0, STATE_IAC = 1, STATE_WILL = 2, STATE_WONT = 3, STATE_DO = 4, STATE_DONT = 5, STATE_SB = 6, STATE_SE = 7, STATE_CR = 8, STATE_IAC_SB = 9; private boolean hasReachedEOF; // @GuardedBy("queue") private volatile boolean isClosed; private boolean readIsWaiting; private int receiveState, queueHead, queueTail, bytesAvailable; private final int[] queue; private final TelnetClient client; private final Thread thread; private IOException ioException; /* TERMINAL-TYPE option (start) */ private final int suboption[]; private int suboptionCount; /* TERMINAL-TYPE option (end) */ private volatile boolean threaded; TelnetInputStream(final InputStream input, final TelnetClient client) { this(input, client, true); } TelnetInputStream(final InputStream input, final TelnetClient client, final boolean readerThread) { super(input); this.client = client; this.receiveState = STATE_DATA; this.isClosed = true; this.hasReachedEOF = false; // Make it 2049, because when full, one slot will go unused, and we // want a 2048 byte buffer just to have a round number (base 2 that is) this.queue = new int[2049]; this.queueHead = 0; this.queueTail = 0; this.suboption = new int[client.maxSubnegotiationLength]; this.bytesAvailable = 0; this.ioException = null; this.readIsWaiting = false; this.threaded = false; if (readerThread) { this.thread = new Thread(this); } else { this.thread = null; } } @Override public int available() throws IOException { // Critical section because run() may change bytesAvailable synchronized (queue) { if (threaded) { // Must not call super.available when running threaded: NET-466 return bytesAvailable; } return bytesAvailable + super.available(); } } // Cannot be synchronized. Will cause deadlock if run() is blocked // in read because BufferedInputStream read() is synchronized. @Override public void close() throws IOException { // Completely disregard the fact thread may still be running. // We can't afford to block on this close by waiting for // thread to terminate because few if any JVM's will actually // interrupt a system read() from the interrupt() method. super.close(); synchronized (queue) { hasReachedEOF = true; isClosed = true; if (thread != null && thread.isAlive()) { thread.interrupt(); } queue.notifyAll(); } } /** Returns false. Mark is not supported. */ @Override public boolean markSupported() { return false; } // synchronized(client) critical sections are to protect against // TelnetOutputStream writing through the telnet client at same time // as a processDo/Will/etc. command invoked from TelnetInputStream // tries to write. Returns true if buffer was previously empty. private boolean processChar(final int ch) throws InterruptedException { // Critical section because we're altering bytesAvailable, // queueTail, and the contents of _queue. final boolean bufferWasEmpty; synchronized (queue) { bufferWasEmpty = bytesAvailable == 0; while (bytesAvailable >= queue.length - 1) { // The queue is full. We need to wait before adding any more data to it. Hopefully the stream owner // will consume some data soon! if (!threaded) { // We've been asked to add another character to the queue, but it is already full and there's // no other thread to drain it. This should not have happened! throw new IllegalStateException("Queue is full! Cannot process another character."); } queue.notify(); try { queue.wait(); } catch (final InterruptedException e) { throw e; } } // Need to do this in case we're not full, but block on a read if (readIsWaiting && threaded) { queue.notify(); } queue[queueTail] = ch; ++bytesAvailable; if (++queueTail >= queue.length) { queueTail = 0; } } return bufferWasEmpty; } @Override public int read() throws IOException { // Critical section because we're altering bytesAvailable, // queueHead, and the contents of _queue in addition to // testing value of hasReachedEOF. synchronized (queue) { while (true) { if (ioException != null) { final IOException e; e = ioException; ioException = null; throw e; } if (bytesAvailable == 0) { // Return EOF if at end of file if (hasReachedEOF) { return EOF; } // Otherwise, we have to wait for queue to get something if (threaded) { queue.notify(); try { readIsWaiting = true; queue.wait(); readIsWaiting = false; } catch (final InterruptedException e) { throw new InterruptedIOException("Fatal thread interruption during read."); } } else { // alreadyread = false; readIsWaiting = true; int ch; boolean mayBlock = true; // block on the first read only do { try { if ((ch = read(mayBlock)) < 0) { // must be EOF if (ch != WOULD_BLOCK) { return ch; } } } catch (final InterruptedIOException e) { synchronized (queue) { ioException = e; queue.notifyAll(); try { queue.wait(100); } catch (final InterruptedException interrupted) { // Ignored } } return EOF; } try { if (ch != WOULD_BLOCK) { processChar(ch); } } catch (final InterruptedException e) { if (isClosed) { return EOF; } } // Reads should not block on subsequent iterations. Potentially, this could happen if the // remaining buffered socket data consists entirely of Telnet command sequence and no "user" data. mayBlock = false; } // Continue reading as long as there is data available and the queue is not full. while (super.available() > 0 && bytesAvailable < queue.length - 1); readIsWaiting = false; } continue; } final int ch; ch = queue[queueHead]; if (++queueHead >= queue.length) { queueHead = 0; } --bytesAvailable; // Need to explicitly notify() so available() works properly if (bytesAvailable == 0 && threaded) { queue.notify(); } return ch; } } } // synchronized(client) critical sections are to protect against // TelnetOutputStream writing through the telnet client at same time // as a processDo/Will/etc. command invoked from TelnetInputStream // tries to write. /** * Get the next byte of data. IAC commands are processed internally and do not return data. * * @param mayBlock true if method is allowed to block * @return the next byte of data, or -1 (EOF) if end of stread reached, or -2 (WOULD_BLOCK) if mayBlock is false and there is no data available */ private int read(final boolean mayBlock) throws IOException { int ch; while (true) { // If there is no more data AND we were told not to block, // just return WOULD_BLOCK (-2). (More efficient than exception.) if (!mayBlock && super.available() == 0) { return WOULD_BLOCK; } // Otherwise, exit only when we reach end of stream. if ((ch = super.read()) < 0) { return EOF; } ch = ch & 0xff; /* Code Section added for supporting AYT (start) */ synchronized (client) { client.processAYTResponse(); } /* Code Section added for supporting AYT (end) */ /* Code Section added for supporting spystreams (start) */ client.spyRead(ch); /* Code Section added for supporting spystreams (end) */ switch (receiveState) { case STATE_CR: if (ch == '\0') { // Strip null continue; } // How do we handle newline after cr? // else if (ch == '\n' && _requestedDont(TelnetOption.ECHO) && // Handle as normal data by falling through to _STATE_DATA case //$FALL-THROUGH$ case STATE_DATA: if (ch == TelnetCommand.IAC) { receiveState = STATE_IAC; continue; } if (ch == '\r') { synchronized (client) { if (client.requestedDont(TelnetOption.BINARY)) { receiveState = STATE_CR; } else { receiveState = STATE_DATA; } } } else { receiveState = STATE_DATA; } break; case STATE_IAC: switch (ch) { case TelnetCommand.WILL: receiveState = STATE_WILL; continue; case TelnetCommand.WONT: receiveState = STATE_WONT; continue; case TelnetCommand.DO: receiveState = STATE_DO; continue; case TelnetCommand.DONT: receiveState = STATE_DONT; continue; /* TERMINAL-TYPE option (start) */ case TelnetCommand.SB: suboptionCount = 0; receiveState = STATE_SB; continue; /* TERMINAL-TYPE option (end) */ case TelnetCommand.IAC: receiveState = STATE_DATA; break; // exit to enclosing switch to return IAC from read case TelnetCommand.SE: // unexpected byte! ignore it (don't send it as a command) receiveState = STATE_DATA; continue; default: receiveState = STATE_DATA; client.processCommand(ch); // Notify the user continue; // move on the next char } break; // exit and return from read case STATE_WILL: synchronized (client) { client.processWill(ch); client.flushOutputStream(); } receiveState = STATE_DATA; continue; case STATE_WONT: synchronized (client) { client.processWont(ch); client.flushOutputStream(); } receiveState = STATE_DATA; continue; case STATE_DO: synchronized (client) { client.processDo(ch); client.flushOutputStream(); } receiveState = STATE_DATA; continue; case STATE_DONT: synchronized (client) { client.processDont(ch); client.flushOutputStream(); } receiveState = STATE_DATA; continue; /* TERMINAL-TYPE option (start) */ case STATE_SB: switch (ch) { case TelnetCommand.IAC: receiveState = STATE_IAC_SB; continue; default: // store suboption char if (suboptionCount < suboption.length) { suboption[suboptionCount++] = ch; } break; } receiveState = STATE_SB; continue; case STATE_IAC_SB: // IAC received during SB phase switch (ch) { case TelnetCommand.SE: synchronized (client) { client.processSuboption(suboption, suboptionCount); client.flushOutputStream(); } receiveState = STATE_DATA; continue; case TelnetCommand.IAC: // De-dup the duplicated IAC if (suboptionCount < suboption.length) { suboption[suboptionCount++] = ch; } break; default: // unexpected byte! ignore it break; } receiveState = STATE_SB; continue; /* TERMINAL-TYPE option (end) */ } break; } return ch; } /** * Reads the next number of bytes from the stream into an array and returns the number of bytes read. Returns -1 if the end of the stream has been reached. * <p> * * @param buffer The byte array in which to store the data. * @return The number of bytes read. Returns -1 if the end of the message has been reached. * @throws IOException If an error occurs in reading the underlying stream. */ @Override public int read(final byte buffer[]) throws IOException { return read(buffer, 0, buffer.length); } /** * Reads the next number of bytes from the stream into an array and returns the number of bytes read. Returns -1 if the end of the message has been reached. * The characters are stored in the array starting from the given offset and up to the length specified. * <p> * * @param buffer The byte array in which to store the data. * @param offset The offset into the array at which to start storing data. * @param length The number of bytes to read. * @return The number of bytes read. Returns -1 if the end of the stream has been reached. * @throws IOException If an error occurs while reading the underlying stream. */ @Override public int read(final byte buffer[], int offset, int length) throws IOException { int ch; final int off; if (length < 1) { return 0; } // Critical section because run() may change bytesAvailable synchronized (queue) { if (length > bytesAvailable) { length = bytesAvailable; } } if ((ch = read()) == EOF) { return EOF; } off = offset; do { buffer[offset++] = (byte) ch; } while (--length > 0 && (ch = read()) != EOF); // client._spyRead(buffer, off, offset - off); return offset - off; } @Override public void run() { int ch; try { _outerLoop: while (!isClosed) { try { if ((ch = read(true)) < 0) { break; } } catch (final InterruptedIOException e) { synchronized (queue) { ioException = e; queue.notifyAll(); try { queue.wait(100); } catch (final InterruptedException interrupted) { if (isClosed) { break _outerLoop; } } continue; } } catch (final RuntimeException re) { // We treat any runtime exceptions as though the // stream has been closed. We close the // underlying stream just to be sure. super.close(); // Breaking the loop has the effect of setting // the state to closed at the end of the method. break _outerLoop; } // Process new character boolean notify = false; try { notify = processChar(ch); } catch (final InterruptedException e) { if (isClosed) { break _outerLoop; } } // Notify input listener if buffer was previously empty if (notify) { client.notifyInputListener(); } } } catch (final IOException ioe) { synchronized (queue) { ioException = ioe; } client.notifyInputListener(); } synchronized (queue) { isClosed = true; // Possibly redundant hasReachedEOF = true; queue.notify(); } threaded = false; } void start() { if (thread == null) { return; } int priority; isClosed = false; // TODO remove this // Need to set a higher priority in case JVM does not use pre-emptive // threads. This should prevent scheduler induced deadlock (rather than // deadlock caused by a bug in this code). priority = Thread.currentThread().getPriority() + 1; if (priority > Thread.MAX_PRIORITY) { priority = Thread.MAX_PRIORITY; } thread.setPriority(priority); thread.setDaemon(true); thread.start(); threaded = true; // tell _processChar that we are running threaded } }
int main() { if (true) { } else { } return 0; }
/* *实现客户端向服务端发送短信,写什么发送什么(只能发一次),直至客户端写“exit”结束通信 */ package day17; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; import java.net.UnknownHostException; import java.util.Scanner; import org.junit.Test; public class TestUDP1 { // 客户端 @Test public void client() { DatagramSocket ds = null; try { ds = new DatagramSocket(); // 创建数据报 Scanner scanner = new Scanner(System.in); String str = scanner.nextLine(); while (!str.equals("exit")) { byte[] b = str.getBytes(); DatagramPacket pack = new DatagramPacket(b, 0, b.length, InetAddress.getByName("127.0.0.1"), 9090); // 发送 ds.send(pack); } } catch (IOException e) { e.printStackTrace(); } finally { if (ds != null) { ds.close(); } } } // 服务端 @Test public void Server() { DatagramSocket ds = null; try { ds = new DatagramSocket(9090); // 获取数据 byte[] b = new byte[1024]; DatagramPacket pack = new DatagramPacket(b, 0, b.length); ds.receive(pack); System.out.println(new String(pack.getData(), 0, pack.getLength())); } catch (IOException e) { e.printStackTrace(); } finally { if (ds != null) { ds.close(); } } } }
package com.countout.portal.servlet; import org.springframework.data.redis.connection.MessageListener; /** * 监听redis过期key * @author Mr.tang */ public interface ExpiredMessageListener extends MessageListener { }
package com.igitras.codegen.common.next; import com.igitras.codegen.common.next.annotations.NotNull; import com.igitras.codegen.common.next.exceptions.IncorrectOperationException; /** * Created by mason on 1/5/15. */ public interface CgClassOwner extends CgFile { /** * @return classes owned by this element. */ @NotNull CgClass[] getClasses(); /** * Returns the name of the package to which the file belongs. * * @return the name specified in the package statement, or an empty string for a JSP page or * file which has no package statement. */ String getPackageName(); void setPackageName(String packageName) throws IncorrectOperationException; }
package fadhel.iac.tn.eventtracker.utils; import android.app.AlarmManager; import android.app.Notification; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.os.Build; import android.os.SystemClock; import android.support.v4.app.TaskStackBuilder; import android.util.Log; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import fadhel.iac.tn.eventtracker.receivers.NotificationPublisher; import fadhel.iac.tn.eventtracker.R; import fadhel.iac.tn.eventtracker.activities.FavoritesActivity; /** * Created by Fadhel on 15/04/2016. */ public class Utils { public static Date getDate(String date , String format1) { SimpleDateFormat df = new SimpleDateFormat(format1); Date d = null; try { d = df.parse(date); }catch(ParseException e) {e.printStackTrace();} return d; } public static String transformDate(String date , String format1 , String format2) { SimpleDateFormat df = new SimpleDateFormat(format1); Date d = null; try { d = df.parse(date); }catch(ParseException e) {e.printStackTrace();} df = new SimpleDateFormat(format2); return df.format(d); } public static String updateDate() { Date d1 = null; Date d2 = null; Calendar cal = Calendar.getInstance(); d1 = cal.getTime(); cal.add(Calendar.WEEK_OF_MONTH,2); d2 = cal.getTime(); SimpleDateFormat sd = new SimpleDateFormat("yyyyMMdd00"); return sd.format(d1) + "-" + sd.format(d2); } public static int scheduleNotification(Notification notification, long delay,Context context,String notif_type) { Intent notificationIntent = new Intent(context, NotificationPublisher.class); SharedPreferences sp = context.getSharedPreferences("myPrefs", context.MODE_PRIVATE); SharedPreferences.Editor e = sp.edit(); int notification_id = sp.getInt("notification_id",1); notificationIntent.putExtra(NotificationPublisher.NOTIFICATION_ID, notification_id); notificationIntent.putExtra(NotificationPublisher.NOTIFICATION, notification); notificationIntent.putExtra("notification_type",notif_type); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, notification_id, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT); long futureInMillis = SystemClock.elapsedRealtime() + delay; AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { alarmManager.setExact(AlarmManager.ELAPSED_REALTIME, futureInMillis, pendingIntent); } else alarmManager.set(AlarmManager.ELAPSED_REALTIME, futureInMillis, pendingIntent); notification_id = (notification_id + 1) % 2147483647; if (notification_id==0) notification_id++; e.putInt("notification_id",notification_id); e.commit(); return (notification_id-1); } public static Notification getNotification(String EventTitle,String content,Context context) { Notification.Builder builder = new Notification.Builder(context); TaskStackBuilder stackBuilder = TaskStackBuilder.create(context); Intent resultIntent = new Intent(context,FavoritesActivity.class); builder.setContentTitle(EventTitle); Log.d("EVENT TITLE", EventTitle); builder.setContentText(content); builder.setSmallIcon(R.drawable.logo); stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent( 0, PendingIntent.FLAG_ONE_SHOT //can only be used once ); // start the activity when the user clicks the notification text builder.setContentIntent(resultPendingIntent); return builder.build(); } // -1 : Non // 0 : date event = date aujourdhui // 1 : date event = date aujourdhui - 1 public static int launchNotification(Date dueDate ){ SimpleDateFormat sf = new SimpleDateFormat("dd-MM-yyyy"); String dueDateString = sf.format(dueDate); Calendar cal = Calendar.getInstance(); Date today = cal.getTime(); String todayDate = sf.format(today); cal.add(Calendar.DAY_OF_MONTH, 1); Date tomorrow = cal.getTime(); String tomorrowDate = sf.format(tomorrow); if(todayDate.equals(dueDateString)) return 0; else if(tomorrowDate.equals(dueDateString)) return 1; else return -1; } }
package matth.dungeon.Utility; import android.app.Activity; import android.content.Context; import android.support.constraint.ConstraintLayout; import android.support.constraint.ConstraintSet; import android.util.Log; import android.view.View; import android.widget.ImageView; public class MainUtility { public static String LOAD_SAVED = "loadSaved"; public static String LOAD_PLAYER = "loadPlayer"; public static String DELETE_CURRENT_TILE = "deleteCurrentTile"; public static String ENEMIES = "enemies"; public static String BOSS = "boss"; private Context con; private static boolean active = true; public MainUtility(Context con) { this.con = con; } public static boolean isActive() { return active; } public static void setActive(boolean bool) { Log.d("test", Boolean.toString(bool)); active = bool; } public Context getCon() { return con; } public int getScreenHeight() { return con.getResources().getDisplayMetrics().heightPixels; } public int getScreenWidth() { return con.getResources().getDisplayMetrics().widthPixels; } public ImageView addImage(String layoutName, String imageName, float x, float y) { int id = con.getResources().getIdentifier(layoutName, "id", con.getPackageName()); ConstraintLayout map = ((Activity)con).findViewById(id); ConstraintSet set = new ConstraintSet(); ConstraintLayout.LayoutParams lp = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.WRAP_CONTENT, ConstraintLayout.LayoutParams.WRAP_CONTENT); ImageView image = new ImageView(con); image.setId(View.generateViewId()); image.setImageResource(con.getResources().getIdentifier(imageName, "drawable", con.getPackageName())); image.setLayoutParams(lp); image.setX(x); image.setY(y); map.addView(image); set.clone(map); set.connect(image.getId(), ConstraintSet.TOP, map.getId(), ConstraintSet.TOP, 0); set.applyTo(map); return image; } public ImageView addImage(String layoutName, String imageName, float x, float y, Integer width, Integer height) { int id = con.getResources().getIdentifier(layoutName, "id", con.getPackageName()); ConstraintLayout map = ((Activity)con).findViewById(id); ConstraintSet set = new ConstraintSet(); ConstraintLayout.LayoutParams lp = new ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.WRAP_CONTENT, ConstraintLayout.LayoutParams.WRAP_CONTENT); ImageView image = new ImageView(con); image.setId(View.generateViewId()); image.setImageResource(con.getResources().getIdentifier(imageName, "drawable", con.getPackageName())); image.setLayoutParams(lp); image.setX(x); image.setY(y); if (width != null) { image.setScaleType(ImageView.ScaleType.CENTER_CROP); image.getLayoutParams().width = width; } if (height != null) { image.setScaleType(ImageView.ScaleType.CENTER_CROP); image.getLayoutParams().height = height; } map.addView(image); set.clone(map); set.connect(image.getId(), ConstraintSet.TOP, map.getId(), ConstraintSet.TOP, 0); set.applyTo(map); return image; } }
package com.jim.multipos.ui.reports.hourly_sales; import android.os.Bundle; import android.view.Gravity; import com.github.angads25.filepicker.model.DialogConfigs; import com.github.angads25.filepicker.model.DialogProperties; import com.github.angads25.filepicker.view.FilePickerDialog; import com.github.mjdev.libaums.fs.UsbFile; import com.jim.mpviews.ReportView; import com.jim.mpviews.utils.ReportViewConstants; import com.jim.multipos.R; import com.jim.multipos.core.BaseTableReportFragment; import com.jim.multipos.utils.ExportToDialog; import com.jim.multipos.utils.ExportUtils; import java.io.File; import javax.inject.Inject; import static com.jim.multipos.utils.ExportUtils.EXCEL; public class HourlySalesReportFragment extends BaseTableReportFragment implements HourlySalesReportView { @Inject HourlySalesReportPresenter presenter; private ReportView.Builder builder; private ReportView reportView; private String titles[]; private int dataType[] = { ReportViewConstants.NAME, ReportViewConstants.QUANTITY, ReportViewConstants.QUANTITY, ReportViewConstants.AMOUNT, ReportViewConstants.AMOUNT, ReportViewConstants.NAME}; private int weights[] = {2, 2, 2, 2, 2, 1}; private int aligns[] = {Gravity.CENTER, Gravity.CENTER, Gravity.CENTER, Gravity.RIGHT, Gravity.RIGHT, Gravity.CENTER}; @Override protected void init(Bundle savedInstanceState) { description = getContext().getString(R.string.hourly_sales_description); init(presenter); disableFilter(); disableSearch(); initDefaults(); setSingleTitle(getString(R.string.hourly_sales_report)); builder = new ReportView.Builder() .setContext(getContext()) .setTitles(titles) .setDataTypes(dataType) .setWeight(weights) .setDataAlignTypes(aligns) .build(); reportView = new ReportView(builder); presenter.onCreateView(savedInstanceState); } @Override public void initTable(Object[][] objects) { reportView.getBuilder().init(objects); setTable(reportView.getBuilder().getView()); } @Override public void updateTable(Object[][] objects) { reportView.getBuilder().update(objects); setTable(reportView.getBuilder().getView()); } String description; @Override public void exportTableToExcel(String fileName, String path, Object[][] objects, String date) { ExportUtils.exportToExcel(getContext(), path, fileName, description, date, "", "", objects, titles, weights, dataType, null); } @Override public void exportTableToPdf(String fileName, String path, Object[][] objects, String date) { ExportUtils.exportToPdf(getContext(), path, fileName, description, date, "", "", objects, titles, weights, dataType, null); } ExportToDialog exportDialog; @Override public void openExportDialog(int mode) { exportDialog = new ExportToDialog(getContext(), mode, getString(R.string.hourly_sales_report), new ExportToDialog.OnExportListener() { @Override public void onFilePickerClicked() { openFilePickerDialog(); } @Override public void onSaveToUSBClicked(String filename, UsbFile root) { if (mode == EXCEL) presenter.exportExcelToUSB(filename, root); else presenter.exportPdfToUSB(filename, root); } @Override public void onSaveClicked(String fileName, String path) { if (mode == EXCEL) presenter.exportExcel(fileName, path); else presenter.exportPdf(fileName, path); } }); exportDialog.show(); } private void openFilePickerDialog() { DialogProperties properties = new DialogProperties(); properties.selection_mode = DialogConfigs.SINGLE_MODE; properties.selection_type = DialogConfigs.DIR_SELECT; properties.root = new File(DialogConfigs.DEFAULT_DIR); properties.error_dir = new File(DialogConfigs.DEFAULT_DIR); properties.offset = new File(DialogConfigs.DEFAULT_DIR); properties.extensions = null; FilePickerDialog dialog = new FilePickerDialog(getContext(), properties); dialog.setNegativeBtnName(getContext().getString(R.string.cancel)); dialog.setPositiveBtnName(getContext().getString(R.string.select)); dialog.setTitle(getContext().getString(R.string.select_a_directory)); dialog.setDialogSelectionListener(files -> { exportDialog.setPath(files); }); dialog.show(); } @Override public void exportExcelToUSB(String filename, UsbFile root, Object[][] objects, String date) { ExportUtils.exportToExcelToUSB(getContext(), root, filename, description, date, "", "", objects, titles, weights, dataType, null); } @Override public void exportTableToPdfToUSB(String fileName, UsbFile path, Object[][] objects, String date) { ExportUtils.exportToPdfToUSB(getContext(), path, fileName, description, date, "", "", objects, titles, weights, dataType, null); } private void initDefaults() { titles = new String[]{getContext().getString(R.string.time_interval), getContext().getString(R.string.transactions), getContext().getString(R.string.sold_items), getContext().getString(R.string.avg_sales), getContext().getString(R.string.sales_summary), getContext().getString(R.string.percent_sales)}; } }
public class ConcreteImplementor2 implements Implementor { @Override public void doSomething() { System.out.println("ConcreteImplementor2 do something..."); } @Override public void doAnything() { System.out.println("ConcreteImplementor2 do anything..."); } }
/** * OpenKM, Open Document Management System (http://www.openkm.com) * Copyright (c) 2006-2015 Paco Avila & Josep Llort * * No bytes were intentionally harmed during the development of this application. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.openkm.frontend.client.widget.chat; import java.util.ArrayList; import java.util.List; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.DialogBox; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.HTMLTable.CellFormatter; import com.google.gwt.user.client.ui.HasAlignment; import com.google.gwt.user.client.ui.HorizontalPanel; import com.google.gwt.user.client.ui.ScrollPanel; import com.google.gwt.user.client.ui.VerticalPanel; import com.openkm.frontend.client.Main; import com.openkm.frontend.client.bean.GWTUser; import com.openkm.frontend.client.service.OKMChatService; import com.openkm.frontend.client.service.OKMChatServiceAsync; /** * Online popup * * @author jllort * */ public class OnlineUsersPopup extends DialogBox { private final OKMChatServiceAsync chatService = (OKMChatServiceAsync) GWT.create(OKMChatService.class); public static final int ACTION_NONE = -1; public static final int ACTION_NEW_CHAT = 0; public static final int ACTION_ADD_USER_TO_ROOM = 1; private VerticalPanel vPanel; private HorizontalPanel hPanel; private Button cancel; private Button accept; private ExtendedFlexTable table; private ScrollPanel scrollPanel; private int action = ACTION_NONE; private String room = ""; private List<String> usersInChat; /** * Online users popup */ public OnlineUsersPopup() { // Establishes auto-close when click outside super(false,true); setText(Main.i18n("user.online")); usersInChat = new ArrayList<String>(); vPanel = new VerticalPanel(); cancel = new Button(Main.i18n("button.cancel"), new ClickHandler() { @Override public void onClick(ClickEvent event) { hide(); } }); accept = new Button(Main.i18n("button.accept"), new ClickHandler() { @Override public void onClick(ClickEvent event) { executeAction(); } }); hPanel = new HorizontalPanel(); hPanel.add(cancel); HTML space = new HTML(""); hPanel.add(space); hPanel.add(accept); hPanel.setCellWidth(space, "25px"); table = new ExtendedFlexTable(); table.setBorderWidth(0); table.setCellPadding(2); table.setCellSpacing(0); table.setWidth("100%"); scrollPanel = new ScrollPanel(table); scrollPanel.setSize("240px", "300px"); vPanel.add(scrollPanel); vPanel.add(hPanel); vPanel.setCellHeight(scrollPanel, "300px"); vPanel.setCellHeight(hPanel, "25px"); vPanel.setCellHorizontalAlignment(scrollPanel, HasAlignment.ALIGN_CENTER); vPanel.setCellHorizontalAlignment(hPanel, HasAlignment.ALIGN_CENTER); vPanel.setCellVerticalAlignment(scrollPanel, HasAlignment.ALIGN_MIDDLE); vPanel.setCellVerticalAlignment(hPanel, HasAlignment.ALIGN_MIDDLE); scrollPanel.setStyleName("okm-PanelSelected"); scrollPanel.addStyleName("okm-Input"); table.addStyleName("okm-DisableSelect"); cancel.setStyleName("okm-NoButton"); accept.setStyleName("okm-YesButton"); vPanel.setWidth("250px"); vPanel.setHeight("350px"); super.hide(); setWidget(vPanel); } /** * refreshOnlineUsers */ public void refreshOnlineUsers() { table.removeAllRows(); // Remove all table values enableAcceptButton(); String actualUser = Main.get().workspaceUserProperties.getUser().getId(); for (GWTUser user : Main.get().mainPanel.bottomPanel.userInfo.getConnectedUserList()) { int rows = table.getRowCount(); // Only we add other user than actual UI user connected ( you can not chat yourself ) // Evaluate case new chat or existing chat if (action == ACTION_NEW_CHAT && !user.getId().equals(actualUser)) { table.setHTML(rows, 0, user.getUsername()); table.setHTML(rows, 1, user.getId()); table.getCellFormatter().setVisible(rows, 1, false); table.getRowFormatter().setStyleName(rows, "okm-Table-Row"); setRowWordWarp(rows, 1, false); } else if (!user.getId().equals(actualUser) && !usersInChat.contains(user)) { table.setHTML(rows, 0, user.getUsername()); table.setHTML(rows, 1, user.getId()); table.getCellFormatter().setVisible(rows, 1, false); table.getRowFormatter().setStyleName(rows, "okm-Table-Row"); setRowWordWarp(rows, 1, false); } } } /** * Set the WordWarp for all the row cells * * @param row The row cell * @param columns Number of row columns * @param warp */ private void setRowWordWarp(int row, int columns, boolean warp) { CellFormatter cellFormatter = table.getCellFormatter(); for (int i=0; i<columns; i++) { cellFormatter.setWordWrap(row, i, warp); } } /** * Language refresh */ public void langRefresh() { cancel.setHTML(Main.i18n("button.cancel")); accept.setHTML(Main.i18n("button.accept")); setText(Main.i18n("user.online")); } /** * enableAcceptButton */ public void enableAcceptButton() { accept.setEnabled((table.getSelectedRow()>=0)); } /** * createNewChatRoom */ public void createNewChatRoom() { if (table.getSelectedRow()>=0) { final String user = table.getHTML(table.getSelectedRow(), 1); chatService.createNewChatRoom(user, new AsyncCallback<String>() { @Override public void onSuccess(String result) { ChatRoomPopup chatRoomPopup = new ChatRoomPopup(user, result); chatRoomPopup.center(); chatRoomPopup.getPendingMessage(result); Main.get().mainPanel.bottomPanel.userInfo.addChatRoom(chatRoomPopup); } @Override public void onFailure(Throwable caught) { Main.get().showError("GetCreateNewChatRoom", caught); } }); } } /** * addUserToRoom */ public void addUserToRoom() { if (table.getSelectedRow()>=0) { String user = table.getHTML(table.getSelectedRow(), 1); chatService.addUserToChatRoom(room, user, new AsyncCallback<Object>() { @Override public void onSuccess(Object result) { } @Override public void onFailure(Throwable caught) { Main.get().showError("AddUserToChatRoom", caught); } }); } } /** * setAction * * @param action */ public void setAction(int action) { setAction(action,""); } /** * setAction * * @param action */ public void setAction(int action, String room) { this.action = action; this.room = room; } /** * executeAction */ public void executeAction() { hide(); switch (action) { case ACTION_NEW_CHAT: createNewChatRoom(); break; case ACTION_ADD_USER_TO_ROOM: addUserToRoom(); break; } } /** * setUsersInChat * * @param usersInChat */ public void setUsersInChat(List<String> usersInChat) { this.usersInChat = usersInChat; } }
package sellwin.db; // SellWin http://sourceforge.net/projects/sellwincrm //Contact support@open-app.com for commercial help with SellWin //This software is provided "AS IS", without a warranty of any kind. /** * This class is a general application level exception that is thrown * in the database code to indicate that a not found occurred on a * select */ public class SellwinNotFoundException extends java.lang.Exception { public SellwinNotFoundException() { super(); } public SellwinNotFoundException(String s) { super(s); } }
/********************************************************************************************** * Distributed computing spring 2014 group 4 //Alex Ryder//Nick Champagne//Hue Moua// * //Daniel Gedge//Corey Jones// * Project 2 Peer2Peer client/server ***********************************************************************************************/ /********************************************************************************************** * This class is the main server class that controls all server functions. it keeps track of * which clients have which files. ***********************************************************************************************/ import javax.swing.*; import java.net.*; import java.io.*; import java.util.ArrayList; import java.util.Random; public class Main extends Thread { protected Socket clientSocket; public static syncArrayList<serverFile> clientfiles; //list of client files and the host who have them public static int numClients; public static int serverID; public static syncArrayList<serverLoads> servers; public static void main(String[] args) throws IOException { servers = new syncArrayList<serverLoads>(); Random rand = new Random(); serverID = rand.nextInt(5000); numClients = 0; ServerSocket serverSocket = null; BCthread clientConnector = new BCthread(); //spawn the client broadcast authenticator thread serverFileQuery sFQ = new serverFileQuery(); //spawn the thread that responds to file queries sFQ.start(); clientConnector.start(); serverServerFileQuery sSFQ = new serverServerFileQuery(); sSFQ.start(); serverLoadBalancer SLB = new serverLoadBalancer(); SLB.start(); GuiRunner gr = new GuiRunner(); gr.start(); clientfiles = new syncArrayList<serverFile>(); //start as a new list try { serverSocket = new ServerSocket(6666); //create a socet for clients to connect to System.out.println ("data socket created"); try { while (true) //forever { System.out.println ("Waiting for a connection...."); new Main(serverSocket.accept()); //if they connect to us spawn thread } } catch (IOException execp) { System.out.println("something went wrong accepting connection : "+execp); } } catch (IOException execp) { System.out.println("something went wrong creating port: " + execp); } } private Main(Socket clientSoc) { clientSocket = clientSoc; //with new connection start thread start(); } public void run() { try { BufferedReader Istream = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); String temp = Istream.readLine(); //get the first message OutputStream Ostream = clientSocket.getOutputStream(); if (!temp.equals("SER")) { //server will never send its file list dont try and receive node tempNode = new node(); //temporary new representation of a client node tempNode.IPaddress = (clientSocket.getInetAddress().getHostAddress()); //get the ip address of this client if (temp.substring(0, 3).equals("###"))//if its the port number { tempNode.port = Integer.parseInt(temp.substring(3, temp.length())); //get the port number } else tempNode.port = 8888; //some how we errored and didnt get the port first... so use the default System.out.println("We have a client messaging from " + tempNode.IPaddress + ":" + tempNode.port); serverFile tempSF; //create a temporary new file representation clientSocket.setSoTimeout(100000); //to account for deleted files, remove all records of this client for (int i = 0; i < clientfiles.size(); ++i) //for all file names { for (int j = 0; j < clientfiles.get(i).hosts.size(); ++j) //for all clients that host it { if (clientfiles.get(i).hosts.get(j).IPaddress.equals(tempNode.IPaddress)) //if this client is a host { clientfiles.get(i).hosts.remove(j); //remove them as a host } } if (clientfiles.get(i).hosts.isEmpty())//if no one hosts this file remove it { clientfiles.remove(i); } } while (true) //while there are still files { tempSF = new serverFile(); //temp new server file tempSF.hosts = new ArrayList<node>(); //with a new arraylist initialization tempSF.fName = Istream.readLine(); //get the file name // System.out.println("The client sent : "+tempSF.fName); if (tempSF.fName.equals("EOF")) //if its the end of the list break the loop { break; } tempSF.hosts.add(tempNode); //this new file obviously came from our temp client node boolean existing = false; //if its an existing file name or not for (int i = 0; i < clientfiles.size(); ++i) //for all file names { if (clientfiles.get(i).fName.equals(tempSF.fName)) //if we have the file name already { // System.out.println("We already have this file on record"); existing = true; //it already exists if (!clientfiles.get(i).hosts.contains(tempNode)) //if we dont have this client listed (we shouldnt) { // System.out.println("but not on this host"); clientfiles.get(i).hosts.add(tempNode); //add this host to the list for that file break; } else //else it already existed.... some how? { // System.out.println("We already have this file and host on record"); break; } } } if (!existing) //if we didnt find it add it. { // System.out.println("We had no record, adding it now"); clientfiles.add(tempSF); } } temp = ""; for (int i = 0; i < servers.size(); ++i) //get the list from another server { if ((serverID != servers.get(i).idNum) && (!servers.get(i).serverIP.equals(clientSocket.getInetAddress().getHostAddress()))) {//if its not me or the server requesting the file Socket otherServers = new Socket(servers.get(i).serverIP, 6666); BufferedReader inpstream = new BufferedReader(new InputStreamReader(otherServers.getInputStream())); OutputStream oupstream = otherServers.getOutputStream(); temp = "SER\n"; System.out.println("We are asking the server at "+servers.get(i).serverIP+" for their file list"); oupstream.write(temp.getBytes()); //trigger the server to send us its list back while (true) { temp = inpstream.readLine(); //read each received line if (temp.equals("EOF")) //if its the end from the server break the while loop break; temp+="\n"; System.out.print("Received : "+temp); Ostream.write(temp.getBytes());//forward it on to the client! } Ostream.flush(); inpstream.close(); oupstream.close(); otherServers.close(); } } } for(int i = 0; i<clientfiles.size(); ++i) //for all files, { temp = clientfiles.get(i).fName+"\n"; System.out.print("Sending file name: " + temp); Ostream.write(temp.getBytes()); //tell the client the list we have on record } System.out.println("Finished sending out list to the client"); temp = "EOF\n"; //send end of list escape sequence Ostream.write(temp.getBytes()); Istream.close(); //close everything Ostream.close(); System.out.println("sent an EOF"); clientSocket.close(); } catch (Exception e) { System.err.println("Problem with Server :"+e); } } }
package de.zarncke.lib.lang.gen; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import de.zarncke.lib.io.IOTools; import de.zarncke.lib.lang.ClassTools; /** * loads/creates Classes on demand. */ public class DemandClassLoader extends ClassLoader { private File rootDirectory; private final List creators = new ArrayList(); private final Map classes = new HashMap(); public DemandClassLoader(final File rootDirectory) { init(rootDirectory); } public DemandClassLoader(final File rootDirectory, final ClassLoader parent) { super(parent); init(rootDirectory); } private void init(final File rootDirectory) { if (!rootDirectory.exists()) { rootDirectory.mkdirs(); } if (!rootDirectory.isDirectory()) { throw new IllegalArgumentException("rootDirectory " + rootDirectory + "must be dir!"); } this.rootDirectory = rootDirectory; registerCreator(new LoadingCreator(rootDirectory)); } public final void registerCreator(final ClassBinaryCreator creator) { this.creators.add(creator); } /** * @return true if newly stored, false if already present (not stored) */ private boolean storeBinary(final String name, final byte[] data) throws IOException { FileOutputStream fos = null; try { File file = new File(this.rootDirectory, ClassTools.classNameToFileName(name)); if (file.exists()) { return false; } file.getParentFile().mkdirs(); fos = new FileOutputStream(file); fos.write(data); fos.flush(); } finally { IOTools.forceClose(fos); } return true; } @Override public Class findClass(final String name) throws ClassNotFoundException { Class cl = (Class) this.classes.get(name); if (cl != null) { return cl; } for (Iterator it = this.creators.iterator(); it.hasNext();) { byte[] bs = ((ClassBinaryCreator) it.next()).createBinary(name); if (bs != null) { try { storeBinary(name, bs); } catch (IOException ioe) { throw new ClassNotFoundException("cannot store generated class binary " + name + " due to " + ioe); } try { cl = super.defineClass(name, bs, 0, bs.length); } catch (Throwable error) { // NOPMD throw new ClassNotFoundException("cannot create class " + name + " due to generation error ", error); } this.classes.put(name, cl); return cl; } } throw new ClassNotFoundException("Class " + name + " cannot be created on demand."); } @Override public String toString() { return "DemandClassLoader with creators " + this.creators; } }
package my.Project; import java.util.InputMismatchException; import java.util.Scanner; /** * 自定义异常类 * @author cyg * @version 1.0 */ class NumberOutOfBoundsException extends Exception { private static final long serialVersionUID = 1L; NumberOutOfBoundsException() { super("数字范围错误"); } } /** * 抛出异常测试 * @author cyg * @version 1.0 */ public class Main { public static void main(String[] args) throws NumberOutOfBoundsException { @SuppressWarnings("resource") Scanner sc = new Scanner(System.in); int[] array = new int[3]; int count = 0; while(true) { try { System.out.print("请输入数字:"); int i = sc.nextInt(); if(i < 0 || i > 100) { throw new NumberOutOfBoundsException(); } array[count] = i; count++; } catch(NumberOutOfBoundsException e) { System.err.println(e.getMessage()); } } } }
package banyuan.day04.morning.practice01.P05; public class Test { public static void main(String[] args) { Teacher teacher = new Teacher(); teacher.setName("陈浩"); teacher.setHeight(1.7); teacher.setAge(34); teacher.setSex('男'); teacher.setId(1123); System.out.println(teacher.ShowData()); } }
package ru.kappers.exceptions; import lombok.extern.slf4j.Slf4j; @Slf4j public class MoneyTransferException extends RuntimeException { protected static final String DEFAULT_MESSAGE = "Money transfer Exception"; public MoneyTransferException(Exception e) { super(DEFAULT_MESSAGE, e); log.error(DEFAULT_MESSAGE, e); } }
package wx.realware.grp.pt.pb.respority.service; public interface JobService { public void start(); }