text
stringlengths
10
2.72M
package com.senac.apps.SelectionQuickSort.model; public class T4 { private int comparacoes = 0; private int trocas = 0; public int getComparacoes() { return comparacoes; } public void addComparacoes() { this.comparacoes++; } public int getTrocas() { return trocas; } public void addTrocas() { this.trocas++; } public void setComparacoes(int comparacoes) { this.comparacoes = comparacoes; } public void setTrocas(int trocas) { this.trocas = trocas; } }
package com.example.android.booklistingapp; import android.content.AsyncTaskLoader; import android.content.Context; import java.util.List; /** * Created by sksho on 11-Apr-17. */ public class BooksLoader extends AsyncTaskLoader<List<Books>> { final private String url; public BooksLoader(Context context, String url) { super(context); this.url = url; } @Override protected void onStartLoading() { forceLoad(); } @Override public List<Books> loadInBackground() { // Perform the network request, parse the response, and extract a list of Books. List<Books> books = QueryUtils.fetchBooksData(url); return books; } }
//package home.videotogif; // // //import android.graphics.Bitmap; //import android.graphics.drawable.AnimationDrawable; //import android.media.MediaMetadataRetriever; //import android.media.MediaPlayer; //import android.net.Uri; //import android.os.Environment; // //import java.io.File; //import java.util.ArrayList; // //public class Convert { // // // // Get your video file // // File myVideo = new File // (Environment.getExternalStorageDirectory().getAbsolutePath(), // "YOUR_FILE.mp4"); // // URI to your video file // Uri myVideoUri = Uri.parse(myVideo.toString()); // // //создаем объект MediaMetadataRetriever // MediaMetadataRetriever mediaMetadataRetriever = new MediaMetadataRetriever(); // mediaMetadataRetriever.setDataSource(myVideo.getAbsolutePath()); // // // Array list to hold your frames // ArrayList<Bitmap> frames = new ArrayList<Bitmap>(); // // //Create a new Media Player // MediaPlayer mp = MediaPlayer.create(getBaseContext(), myVideoUri); // // // Some kind of iteration to retrieve the frames and add it to Array list // Bitmap bitmap = mmRetriever.getFrameAtTime(TIME IN MICROSECONDS); // frames.add(bitmap); // // AnimationDrawable animatedGIF = new AnimationDrawable(); // // animationDrawable.addFrame("FIRST FRAME", 50); // animationDrawable.addFrame("SECOND FRAME", 50); // ... // animationDrawable.addFrame("LAST FRAME ", 50); // //}
package com.ssm.wechatpro.controller; import org.springframework.stereotype.Controller; @Controller public class WechatAdminLoginMationController { }
package pe.edu.upeu.hotel.daoImp; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.BeanPropertyRowMapper; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import pe.edu.upeu.hotel.dao.PersonaDao; import pe.edu.upeu.hotel.entity.Persona; @Repository public class PersonaDaoImp implements PersonaDao { @Autowired private JdbcTemplate jdbcTemplate; @Override public List<Persona> readAll() { // TODO Auto-generated method stub return jdbcTemplate.query("Select * from personas", BeanPropertyRowMapper.newInstance(Persona.class)); } @Override public int create(Persona person) { // TODO Auto-generated method stub String sql = "INSERT INTO personas (nombre, dni, fechanacimiento) VALUES (?,?,?);"; return jdbcTemplate.update(sql, new Object[] {person.getNombre(), person.getDni(), person.getFechanacimiento()}); } @Override public int edit(Persona person) { // TODO Auto-generated method stub String sql = "UPDATE personas SET nombre = ?, dni = ?, fechanacimiento = ? WHERE idpersona = ?;"; return jdbcTemplate.update(sql, person.getNombre(), person.getDni(), person.getFechanacimiento(), person.getIdpersona()); } @Override public int delete(int id) { // TODO Auto-generated method stub String sql = "DELETE FROM personas where idpersona = ?"; return jdbcTemplate.update(sql, new Object[] {id}); } @Override public Persona read(int id) { // TODO Auto-generated method stub String sql = "Select * from personas where idpersona = ?"; return jdbcTemplate.queryForObject(sql, new Object[] {id}, BeanPropertyRowMapper.newInstance(Persona.class)); } }
package com.rbysoft.myovertimebd.Layout; import android.animation.ObjectAnimator; import android.content.Intent; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.os.Handler; import android.view.Window; import android.view.WindowManager; import android.widget.ImageView; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.rbysoft.myovertimebd.LoginSignup; import com.rbysoft.myovertimebd.MyMainActivity; import com.rbysoft.myovertimebd.R; import com.rbysoft.myovertimebd.Saving; public class SplashScrn extends AppCompatActivity { ImageView iv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_splash_scrn); iv=findViewById(R.id.iv); FirebaseUser user= FirebaseAuth.getInstance().getCurrentUser(); // // Animation mine= AnimationUtils.loadAnimation(this,R.anim.transition); // iv.startAnimation(mine); ObjectAnimator animation = ObjectAnimator.ofFloat(iv, "translationY", -300f); animation.setDuration(1000); animation.start(); boolean notFirsttime=Saving.getAboolean(this,"isFirstTime"); final Intent i; if (user==null&& notFirsttime==false){ Saving.SaveABoolean(this,"isFirstTime",true); i=new Intent(this, LoginSignup.class); }else { i=new Intent(this,MyMainActivity.class); } Handler handler=new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { startActivity(i); finish(); } },1500); } }
package action; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import pojo.Users; import service.UsersService; import service.impl.UsersServiceImpl; import util.GetMD5Byte; import core.ActionForm; import core.ActionForward; import core.DispatcherAction; import form.RegisterForm; public class RegisterAction extends DispatcherAction{ UsersService us = new UsersServiceImpl(); public ActionForward register(HttpServletRequest request, HttpServletResponse reponse, ActionForm form) throws ServletException, IOException { RegisterForm rf = (RegisterForm)form; String uname = rf.getUname(); uname = new String(uname.getBytes("ISO8859-1"),"UTF-8"); String upass = rf.getUpass(); String tel = rf.getTel(); byte[] pass = GetMD5Byte.getMD5Byte(upass); String headimage=rf.getHeadimage(); headimage = new String(headimage.getBytes("ISO8859-1"),"UTF-8"); Users users = new Users(); System.out.println("姓名"+uname +"密码"+ pass.toString()+"电话:"+tel+"头像:"+headimage); //主键生成 /* users.setUid(PrimaryKeyUUID.getPrimaryKey()); */ //用户名转码 users.setUname(uname); //密码加密 users.setUpass(pass); users.setTel(tel); users.setHeadimage(headimage); boolean f = us.addUsers(users); if(f){ request.setAttribute("msg","注册成功!"); return new ActionForward("login1"); }else{ request.setAttribute("msg","注册失败"); return new ActionForward(true,"register1"); } } public ActionForward checktel(HttpServletRequest request, HttpServletResponse reponse, ActionForm form) throws ServletException, IOException { System.out.println("checktel"); RegisterForm rf = (RegisterForm)form; String tel = rf.getTel(); System.out.println(tel); PrintWriter pw = reponse.getWriter(); boolean f = us.lookupUser(tel); System.out.println(f); if(!f){ pw.write("bcw"); request.setAttribute("msg","电话可以注册"); }else{ pw.write("cw"); request.setAttribute("msg","电话已经注册"); } return null; } }
package szallasok.model; import javax.persistence.*; /** * Created by Stefyy on 2017.05.25.. */ @Entity public class Felhasznalok { @GeneratedValue(strategy = GenerationType.IDENTITY) @Id private int id; private String felhasznalonev; private String teljesnev; private String jelszo; private String jelszoujra; public Felhasznalok(){ } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFelhasznalonev() { return felhasznalonev; } public void setFelhasznalonev(String felhasznalonev) { this.felhasznalonev = felhasznalonev; } public String getTeljesnev() { return teljesnev; } public void setTeljesnev(String teljesnev) { this.teljesnev = teljesnev; } public String getJelszo() { return jelszo; } public void setJelszo(String jelszo) { this.jelszo = jelszo; } public String getJelszoujra() { return jelszoujra; } public void setJelszoujra(String jelszoujra) { this.jelszoujra = jelszoujra; } }
package com.oxycab.provider.ui.activity.regsiter; import com.oxycab.provider.base.MvpView; import com.oxycab.provider.data.network.model.MyOTP; import com.oxycab.provider.data.network.model.User; public interface RegisterIView extends MvpView { void onSuccess(MyOTP otp); void onError(Throwable e); }
# priyav import java.io.*; public class Asci { public void getChars() { int x=0; String str=""; //boolean contain=false; try { System.out.print("Enter a Char: "); BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); str=in.readLine(); System.out.println("Str is: "+str); x=Integer.valueOf(str).intValue(); System.out.println("int value is: "+x); int i = (int) x; System.out.println("Ascii value is :"+i); System.out.println(i); }catch(Exception e) {System.out.println(e);} } public static void main(String[] args) { Asci as=new Asci(); as.getChars(); } }
package il.co.xsites.developertest.base.ro; import java.io.Serializable; import java.util.Objects; public abstract class BaseRO implements Serializable { // ------------------------ Constants ----------------------- private static final long serialVersionUID = 1L; // ------------------------ Fields -------------------------- private long id; private long creationTime; // ------------------------ Public methods ------------------ // ------------------------ Constructors -------------------- public BaseRO() { } public BaseRO(long id) { this.id = id; } // ------------------------ Field's handlers ---------------- public long getId() { return id; } public void setId(long id) { this.id = id; } public long getCreationTime() { return creationTime; } public void setCreationTime(long creationTime) { this.creationTime = creationTime; } @Override public boolean equals(Object o) { if(this == o) { return true; } if(o == null || getClass() != o.getClass()) { return false; } BaseRO baseRO = (BaseRO) o; return id == baseRO.id && creationTime == baseRO.creationTime; } @Override public int hashCode() { return Objects.hash(id, creationTime); } // ------------------------ Private methods ----------------- }
package com.github.abryb.bsm; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; public class NoteActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); App app = (App) getApplicationContext(); setContentView(R.layout.activity_note); try { ((EditText) findViewById(R.id.note)).setText(app.getNote()); } catch (AppException e) { e.printStackTrace(); Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show(); } } public void saveNote(View view) { EditText editText = findViewById(R.id.note); String note = editText.getText().toString(); try { App app = (App) getApplicationContext(); app.saveNote(note); Toast.makeText(this, "Note saved.", Toast.LENGTH_SHORT).show(); } catch (AppException e) { e.printStackTrace(); Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show(); } } public void changePassword(View view) { Intent intent = new Intent(this, ChangePasswordActivity.class); startActivity(intent); } }
package com.bulldozer.domain.site; public interface ClearableBlock { void clear(SiteCleaner visitor); void markCleared(); boolean isCleared(); void setProtectedTreeDestroyed(); boolean isProtectedTreeDestroyed(); }
package com.testing.class7; import com.alibaba.fastjson.JSON; import com.alibaba.fastjson.JSONObject; import java.util.HashMap; import java.util.Map; public class JsonText { public static void main(String[] args) { String ipStr="/**/jQuery110205334450459806954_1596263095138({\"status\":\"0\",\"t\":\"1596263113247\",\"set_cache_time\":\"\",\"data\":[{\"location\":\"美国 亚马逊云\",\"titlecont\":\"IP地址查询\",\"origip\":\"3.3.3.3\",\"origipquery\":\"3.3.3.3\",\"showlamp\":\"1\",\"showLikeShare\":1,\"shareImage\":1,\"ExtendedLocation\":\"\",\"OriginQuery\":\"3.3.3.3\",\"tplt\":\"ip\",\"resourceid\":\"6006\",\"fetchkey\":\"3.3.3.3\",\"appinfo\":\"\",\"role_id\":0,\"disp_type\":0}]});"; // 获取字符串中第一个指定字体的下标 // System.out.println(ipStr.indexOf("{")); //截取{}之前的json的内容 String ip=ipStr.substring(ipStr.indexOf("{"),ipStr.length()-2); // System.out.println(ip); //解析字符串ip为一个json对象ipJson JSONObject ipJson = JSON.parseObject(ip); //创建一个ipMap<String,Object> 用于存储解析过来的json内容 Map<String,Object> ipMap=new HashMap<>(); for (String key:ipJson.keySet()){ System.out.println("ip中的键为:"+key+"ip中的键值为:"+ipJson.get(key)); ipMap.put(key,ipJson.get(key)); } //创建一个ipMapNew<String,String> 用于存储解析过来的json内容 Map<String,String> ipMapNew=new HashMap<>(); for (String s:ipJson.keySet()){ System.out.println("ipMapNew的键为:"+s+"ipMapNew的键值为:"+ipJson.get(s)); ipMapNew.put(s,ipJson.get(s).toString()); } System.out.println("ipMap的结果为:"+ipMap); System.out.println("ipMapNew的结果为:"+ipMapNew); //将data的值解析存为Map System.out.println("data的键值:"+ipMap.get("data")); String dataText=ipMap.get("data").toString(); String dataValue=dataText.substring(1,dataText.length()-1); // System.out.println(dataText); //创建一个dataMap用在存入data的内容 Map<String,Object> dataMap=new HashMap<>(); JSONObject dataNew = JSON.parseObject(dataValue); for (String s:dataNew.keySet()){ // System.out.println("data中的键为:"+s+"data中的键值为:"+dataNew.get(s)); dataMap.put(s,dataNew.get(s)); } System.out.println("dataMap值为:"+dataMap); //通过parse方法,解析出来的是一个object对象,直接强转为Map<String,Object> Map<String ,Object> ipFormMap = (Map<String, Object>) JSON.parse(ip); System.out.println("ip强制转换为Map的结果为:"+ipFormMap); //强制转换data Map<String ,Object> dataForm = (Map<String, Object>) JSON.parse(dataValue); System.out.println("data强制转换为Map的结果为:"+dataForm); //接的Map内容为一个字符串 String ipNew="{"; for (String s:ipMap.keySet()){ String firstPart="\""+s+"\""; String maohao=":"; String valuePart=""; if (ipMap.get(s) instanceof String){ //如果键值是字符串,则需要加上”“ valuePart="\""+ipMap.get(s)+"\""; }else { //如果键值是不是字符串,则不需要 valuePart = ipMap.get(s).toString(); } ipNew+=firstPart+maohao+valuePart+","; } ipNew+="}"; //最后多一个“,”,替换掉 ipNew= ipNew.replace(",}","}"); System.out.println("ipNew的值:"+ ipNew); } }
package com.wuyan.masteryi.admin.controller; import com.wuyan.masteryi.admin.service.OrderService; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.Map; /** * @Author: Zhao Shuqing * @Date: 2021/7/8 15:17 * @Description: */ @RestController @RequestMapping("/order") @Api(tags ="订单管理接口") public class OrderController { @Autowired OrderService orderService; @PostMapping("/getallorder") @ApiOperation(value="获取全部订单信息", notes="获取全部订单信息") public Map<String,Object> getAllOrder(){ return orderService.getAllOrder(); } @PostMapping("/getoneuserorder") @ApiOperation(value="获取某用户订单信息", notes="获取某用户订单信息") public Map<String,Object> getOneUserOrder(Integer userId){ return orderService.getOneUserOrder(userId); } @PostMapping("/getorderitem") @ApiOperation(value="获取订单子项", notes="获取订单子项") public Map<String,Object> getOrderItem(Integer orderId){ return orderService.getOrderItem(orderId); } @PostMapping("/dealrefund") @ApiOperation(value="处理退款订单", notes="处理退款订单") public Map<String,Object> dealRefund(Integer orderId, Boolean agree){ return orderService.dealRefund(orderId, agree); } @PostMapping("/delorder") @ApiOperation(value = "删除某订单",notes = "删除某订单") public Map<String,Object> delOrder(int orderId){ return orderService.delOrder(orderId); } }
package Tasks.LessonTwo; public class TaskEleven { // Выведите на экран все положительные делители натурального числа, введённого пользователем с клавиатуры. public static void wtf(int a) { for (int i = 1; i <= a; i++){ if (a % i == 0){ System.out.print(i + " "); } } } }
package com.yahoo.random; public class ArrayIndex { /** * @param args */ public static void main(String[] args) { //int[] a = {d,a,c,f,f,b,}; int [] a = new int[5]; //here we can take 5 int values. Note local Array default init to 0 //a[5]=1; // throws java.lang.ArrayIndexOutOfBoundsException: 5 a[4]=1; //ok String s = "dsdd"; System.out.println(s.length()); //gives 4 System.out.println(a.length);//gives 5 //In a for loop over Array use a.length but < and not <= for(int i=0;i<a.length;i++){ System.out.print(a[i]); } //In a loop over String chars also System.out.println(); for(int i=0;i<s.length();i++){ System.out.print(s.charAt(i)); } //complement (bitwise complement. ) of b a given integer System.out.println("\ncompliment:"); int num = 15;int val = num^0xffffffff; System.out.println(num|1); System.out.println(num^1); System.out.println(Integer.toBinaryString(val)); } }
package com.bookapp.model.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.bookapp.dao.Book; import com.bookapp.dao.BookDao; @Service(value = "bookService") public class BookServiceImpl implements BookService{ @Autowired private BookDao dao; public List<Book> getAllBooks() { return dao.getAllBooks(); } public Book addBook(Book book) { // TODO Auto-generated method stub return null; } public void deleteBook(int id) { // TODO Auto-generated method stub } public void updateBook(int id, Book book) { dao.updateBook(id, book); } public Book getBookById(int id) { return dao.getBookById(id); } }
package webprotocol; import lombok.SneakyThrows; import java.util.List; public class Main { @SneakyThrows public static void main(String[] args) { Integer idUser = 7; User createdUser = HttpUtilClient.postRequest(newUser()); System.out.println("1.1) creating a new user :\n" + createdUser); System.out.println("---------------------------------------------"); User user = HttpUtilClient.getRequest(idUser); user.setName("John"); user.setUserName("Doe"); user = HttpUtilClient.putRequest(user.getId(), user); System.out.println("---------------------------------------------"); int statusResponse = HttpUtilClient.deleteRequest(idUser); System.out.println("status response is: " + statusResponse); System.out.println("---------------------------------------------"); List<User> users = HttpUtilClient.getRequestAllUsers(); users.forEach(System.out::println); System.out.println("---------------------------------------------"); User getUserById = HttpUtilClient.getRequestByUserId(idUser); System.out.println("user info by id :" + idUser + "\n" + getUserById); System.out.println("---------------------------------------------"); users = HttpUtilClient.getRequestUserByName(getUserById.getUserName()); System.out.println("user info by Name :" + getUserById.getUserName() + "\n" + users); System.out.println("---------------------------------------------"); String allCommentToLastPostOfUser = HttpUtilClient.getRequestCommentsOfLastPost(user); System.out.println(allCommentToLastPostOfUser); System.out.println("---------------------------------------------"); List<UserTask> allOpenedTaskOfUser = HttpUtilClient.getRequestByTasks(user); allOpenedTaskOfUser.forEach(System.out::println); } public static User newUser() { return new User.UserBuilder() .id(13) .name("Roman Petrenko") .userName("Romchansky") .email("petrenko.roman@hotmail.com") .address(new Address.AddressBuilder() .street("St Claude Ave") .apartment("Apt. 4808") .city("New Orleans") .zipcode("704545") .geo(new Geo.GeoBuilder() .latitude(29.58) .longitude(90.06) .build()) .build()) .phoneNumber("+38066666666") .website("https://github.com/Romchansky") .company(new Company.CompanyBuilder() .nameCompany("Sun microsystems") .catchPhrase("Hello world") .bs("Java").build()) .build(); } }
package com.herbet.ffm.control; import com.herbet.ffm.repository.CustomerRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @Controller public class CustomerController { @Autowired private CustomerRepository repository; @GetMapping("/customer/{id}") public String customer(@PathVariable Long id, Model model) { model.addAttribute("customer", repository.findOne(id)); return "customer"; } @GetMapping("/customers") public String customersList(Model model) { model.addAttribute("customers", repository.findAll()); return "customers"; } }
package com.project.group14.document; import org.springframework.data.annotation.Id; import org.springframework.data.mongodb.core.mapping.Document; @Document(collection = "job") public class JobInfo { @Id private String id; private String Job_Name; private String Company_Name; private String Address; private String[] Salary; private String Level; private String Form; private String Deadline; private String[] Describe; private String[] Requirement; private String[] Type_Job; public JobInfo() { } public String getId() { return id; } public void setId(String id) { this.id = id; } public String getJob_Name() { return Job_Name; } public void setJob_Name(String job_Name) { Job_Name = job_Name; } public String getCompany_Name() { return Company_Name; } public void setCompany_Name(String company_Name) { Company_Name = company_Name; } public String getAddress() { return Address; } public void setAddress(String address) { Address = address; } public String[] getSalary() { return Salary; } public void setSalary(String[] salary) { Salary = salary; } public String getLevel() { return Level; } public void setLevel(String level) { Level = level; } public String getForm() { return Form; } public void setForm(String form) { Form = form; } public String getDeadline() { return Deadline; } public void setDeadline(String deadline) { Deadline = deadline; } public String[] getDescribe() { return Describe; } public void setDescribe(String[] describe) { Describe = describe; } public String[] getRequirement() { return Requirement; } public void setRequirement(String[] requirement) { Requirement = requirement; } public String[] getType_Job() { return Type_Job; } public void setType_Job(String[] type_Job) { Type_Job = type_Job; } public JobInfo(String id, String job_Name, String company_Name, String address, String[] salary, String level, String form, String deadline, String[] describe, String[] requirement, String[] type_Job) { super(); this.id = id; Job_Name = job_Name; Company_Name = company_Name; Address = address; Salary = salary; Level = level; Form = form; Deadline = deadline; Describe = describe; Requirement = requirement; Type_Job = type_Job; } }
/** * Ein eigener Datentyp, zum komfortableren Programmieren des Spiels. * @author Pascal Weiß (s0544768) */ package othello.Miscellaneous; public class OthelloLocation { public int row; public int column; /** * Initialisierung von row und column. * @param row Zeile. * @param column Spalte. */ public OthelloLocation (int row, int column) { this.row = row; this.column = column; } /** * Initialisierung von row und column mit jeweils 0. */ public OthelloLocation () { row = 0; column = 0; } /** * Editieren von row, und column. * @param row Zeile. * @param column Spalte. */ public void setValues(int row, int column) { this.row = row; this.column = column; } }
import java.util.*; import java.io.*; class lapalin{ public static void main(String args[]){ Scanner sc= new Scanner(System.in); int testcase; testcase=sc.nextInt(); while (testcase-->0) { //String s; //s=sc.nextLine(); StringBuffer s=new StringBuffer("gaga"); int len=s.length(); String a=s.substring(0,(len +1)/2); String b=s.substring(len-(len + 1)/2,(len+1)/2); sort(a.begin(),a.end()); sort(b.begin(),b.end()); if (a==b) { System.out.println("Yes"); } else { System.out.println("No"); } } } }
package com.snab.tachkit; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.text.Editable; import android.text.Html; import android.text.InputType; import android.text.TextWatcher; import android.view.View; import android.widget.EditText; import android.widget.TextView; import com.snab.tachkit.asyncTaskCustom.LoginTask; import com.snab.tachkit.dialogs.ErrorMessage; import com.snab.tachkit.widget.BtnColorItemMenu; import com.snab.tachkit.globalOptions.Global; import org.apache.http.NameValuePair; import org.apache.http.message.BasicNameValuePair; import com.snab.tachkit.actionBar.ActivityWithActionBarBack; import com.snab.tachkit.dialogs.SelectDialogFragment; import java.util.ArrayList; import java.util.List; /** * Форма входа пользователя в личный кабинет */ public class LoginActivity extends ActivityWithActionBarBack implements View.OnClickListener { String loginText = null, passwordText = null; EditText editLogin, editPassword; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); actionBarTitle = R.string.title_activity_login; icon_type = 1; initForm(); if(savedInstanceState != null) { editLogin.setText(loginText); editPassword.setText(passwordText); } } protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); } public void initForm(){ editLogin = (EditText) findViewById(R.id.edit_text_email_phone); editPassword = (EditText) findViewById(R.id.edit_text_password); ((TextView) findViewById(R.id.name_edit_text_email_phone)).setText(Html.fromHtml(getResources().getString(R.string.phone_or_email) + " <font color=red>*</font>")); editLogin.setInputType(InputType.TYPE_CLASS_TEXT); editLogin.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { loginText = s.length() == 0 ? null : s.toString(); } @Override public void afterTextChanged(Editable s) { } }); ((TextView) findViewById(R.id.name_edit_text_password)).setText(Html.fromHtml(getResources().getString(R.string.password) + " <font color=red>*</font>")); editPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); editPassword.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { passwordText = s.length() == 0 ? null : s.toString(); } @Override public void afterTextChanged(Editable s) { } }); BtnColorItemMenu btnLogin = (BtnColorItemMenu) findViewById(R.id.submit); btnLogin.setOnClickListener(this); } @Override public void onClick(View v) { if(v.getId() == R.id.submit) { if (loginText != null && passwordText != null) { visibilityElements(); new LoginFormTask(this, getNameValuePairs()).execute(); } else { ErrorMessage errorMessage = (ErrorMessage) SelectDialogFragment.customInstance(null, new ErrorMessage()); errorMessage.setTextMessage("Поле " + loginText == null ? getResources().getString(R.string.phone_or_email) : getResources().getString(R.string.password) + " пустое"); errorMessage.show(getSupportFragmentManager(), "Dialog"); } } } public List<NameValuePair> getNameValuePairs(){ List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1); nameValuePairs.add(new BasicNameValuePair("app_key", Global.appKey)); nameValuePairs.add(new BasicNameValuePair("login", loginText)); nameValuePairs.add(new BasicNameValuePair("password", passwordText)); return nameValuePairs; } public void visibilityElements(){ findViewById(R.id.login_form).setVisibility(View.GONE); findViewById(R.id.loadingPanel).setVisibility(View.VISIBLE); } private class LoginFormTask extends LoginTask{ public LoginFormTask(Context context, List<NameValuePair> nameValuePairs) { super(context, nameValuePairs); } @Override public void okLoginDo() { Intent output = new Intent(); output.putExtra("login", true); activity.setResult(((Activity) context).RESULT_OK, output); activity.finish(); } @Override public void reloadLogin() { setContentView(R.layout.activity_login); initForm(); editLogin.setText(loginText); editPassword.setText(passwordText); visibilityElements(); new LoginFormTask(context, getNameValuePairs()).execute(); } @Override public void notLoginDo() { findViewById(R.id.login_form).setVisibility(View.VISIBLE); findViewById(R.id.loadingPanel).setVisibility(View.GONE); ErrorMessage errorMessage = (ErrorMessage) SelectDialogFragment.customInstance(null, new ErrorMessage()); errorMessage.setTextMessage(loginOptions.getData().getLogin() != null ? loginOptions.getData().getLogin()[0] : loginOptions.getData().getPassword()[0]); errorMessage.show(getSupportFragmentManager(), "Dialog"); } } }
import java.io.IOException; public class App { public static void main(String[] args) throws IOException, InterruptedException { Lotto lotto = new Lotto(); lotto.Start(); } }
package utils; public class ConvertUtil { // 次の9文字は使用不可(< > : * ? " / \ |). final static String FORBIDDEN1 = "<"; final static String FORBIDDEN2 = ">"; final static String FORBIDDEN3 = ":"; final static String FORBIDDEN4 = "*"; final static String FORBIDDEN5 = "?"; final static String FORBIDDEN6 = "\""; final static String FORBIDDEN7 = "/"; final static String FORBIDDEN8 = "\\"; final static String FORBIDDEN9 = "|"; final static String FORBIDDEN10 = " "; final static String FORBIDDEN11 = " "; // 返却する文字列. final static String LESS_THAN = "小なり"; final static String GREATER_THAN = "大なり"; final static String COLON = "コロン"; final static String ASTERISK = "アスタリスク"; final static String QUESTION = "クエスチョン"; final static String DOUBLE_QUORTATION = "ダブルクォーテーション"; final static String SLASH = "スラッシュ"; final static String BACK_SLASH = "バックスラッシュ"; final static String BAR = "パイプライン"; final static String SPACE_EM = "スペース(全角)"; final static String SPACE_HALF = "スペース(半角)"; public static String convert(String string) { // 禁則文字に該当すれば変換した文字列を、該当しなければそのまま返却. switch (string) { case FORBIDDEN1: return LESS_THAN; case FORBIDDEN2: return GREATER_THAN; case FORBIDDEN3: return COLON; case FORBIDDEN4: return ASTERISK; case FORBIDDEN5: return QUESTION; case FORBIDDEN6: return DOUBLE_QUORTATION; case FORBIDDEN7: return SLASH; case FORBIDDEN8: return BACK_SLASH; case FORBIDDEN9: return BAR; case FORBIDDEN10: return SPACE_EM; case FORBIDDEN11: return SPACE_HALF; default : return string; } } }
package com.tencent.tencentmap.mapsdk.a; import com.qq.jutil.j4log.Logger; public class ax { static final Logger a = Logger.getLogger("jceClient"); static int b = 15; public static void a(String str) { a.info(str); } public static void a(String str, Throwable th) { a.info(str, th); } public static void b(String str) { a.error(str); } public static void b(String str, Throwable th) { a.error(str, th); } public static void c(String str) { a.debug(str); } }
package com.handsome.android.designpattern.strategy; import com.handsome.android.designpattern.strategy.impl.FlyBehavior; import com.handsome.android.designpattern.strategy.impl.QuackBehavior; /** * 利用继承 缺点: * 代码在多个子类中重复 * 运行时的行为不容易改变 * 很难知道所有鸭子的全部行为 * 改变会牵一发动全身,造成其他子类不想要的改变 * <p/> * Created with Andrid Studio. * User:shuaizhimin * Date:16/5/4 * Time:下午10:27 * <p/> * <p/> * 并不是所有的鸭子都具备这些功能,想要这些功能 * <p/> * 把会变化的跟不变化的分开 */ public abstract class Duck { QuackBehavior quackBehavior; FlyBehavior flyBehavior; public abstract void display(); public void performFly() { flyBehavior.fly(); } public void performQuack() { quackBehavior.quack(); } public void swim(){ } }
package httpResponseStatus; import http.HttpResponseStatus; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * Created by cenk on 01/01/15. */ public class HttpResponseStatusTest { @Test public void testGetStatus() throws NoSuchFieldException, InstantiationException, IllegalAccessException { System.out.println("@Test Starts - testGetStatus"); Object acceptedCode = HttpResponseStatus.getStatus("ACCEPTED"); assertEquals(202, acceptedCode); Object okCode = HttpResponseStatus.getStatus("OK"); assertEquals(200, okCode); Object notModifiedCode = HttpResponseStatus.getStatus("NOT_MODIFIED"); assertEquals(304, notModifiedCode); System.out.println("@Test Ends - testGetStatus"); } }
package fr.doranco.ecommerce.metier; import fr.doranco.ecommerce.entity.pojo.Categorie; public class CategorieMetier implements ICategorieMetier{ @Override public void addCategorie(Categorie categorie) throws Exception { // TODO Auto-generated method stub } @Override public Categorie getCategorieById(Integer id) throws Exception { // TODO Auto-generated method stub return null; } @Override public Categorie getCategorieByEmail(String email) throws Exception { // TODO Auto-generated method stub return null; } @Override public void updateCategorie(Categorie categorie) throws Exception { // TODO Auto-generated method stub } @Override public void removeCategorie(Categorie categorie) throws Exception { // TODO Auto-generated method stub } }
package com.tencent.mm.plugin.radar.b; import b.c.b.e; import com.tencent.mm.g.a.mg; import com.tencent.mm.kernel.c.a; import com.tencent.mm.kernel.g; import com.tencent.mm.plugin.messenger.foundation.a.i; import com.tencent.mm.sdk.b.b; import com.tencent.mm.sdk.b.c; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.storage.ab; import com.tencent.mm.storage.ay; import com.tencent.mm.storage.bd.d; public final class c$i extends c<mg> { final /* synthetic */ c mjy; c$i(c cVar) { this.mjy = cVar; } public final /* synthetic */ boolean a(b bVar) { mg mgVar = (mg) bVar; e.i(mgVar, "event"); String str = mgVar.bWU.bWW; ab a = c.a(d.YY(str)); c.a(this.mjy, a); c cVar = this.mjy; e.h(str, "msgContent"); c.a(cVar, a, str); a l = g.l(i.class); e.h(l, "service(IMessengerStorage::class.java)"); ay FR = ((i) l).FR(); if (!FR.Yi(a.wR())) { FR.S(a); } c.b bVar2 = c.mju; x.d(c.access$getTAG$cp(), "receive verify mssage %s, encypt %s", a.getUsername(), a.wR()); c.b(this.mjy, a); return false; } }
package websearch.indexing; import java.io.BufferedInputStream; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.PriorityQueue; import queryProcessingUtils.BM25Scorer; import queryProcessingUtils.DocumentScore; import queryProcessingUtils.WordFrequencyEntry; import dataStructures.Lexicon; import mergeUtils.IndexReader; import dataStructures.DocumentInfo; import mergeUtils.IndexEntry; import dataStructures.CorpusStatistics; import mergeUtils.WrapperIndexEntry; public class QueryProcessor { IndexReader indexReader; Lexicon lexicon; Map<String,Integer> wordMap ; Map<Integer, DocumentInfo> documentMap ; double avgDocumentLength; public QueryProcessor(IndexReader indexReader, Lexicon lexicon, Map<String,Integer> wordMap,Map<Integer, DocumentInfo> documentMap, double avgDocumentLength) { super(); this.indexReader = indexReader; this.lexicon = lexicon; this.wordMap = wordMap; this.documentMap = documentMap; this.avgDocumentLength = avgDocumentLength; } public DocumentScore[] search(List<String> tokens, int numberOfResults) throws FileNotFoundException, IOException { List<WordFrequencyEntry> tokenList = new ArrayList<WordFrequencyEntry>(tokens.size()); List<String> newTokens = new ArrayList<String>(tokens.size()); for(String token:tokens){ newTokens.add(token); if(wordMap.containsKey(token)) { int wordID = wordMap.get(token); //System.out.println(wordID); IndexEntry indexEntry = indexReader.openList(wordID); //System.out.println(indexEntry); tokenList.add(new WordFrequencyEntry(wordID, indexEntry.getDocVectorSize())); } else { newTokens.remove(token); } } if(tokenList.size() == 0) { return new DocumentScore[0]; } if(tokens.size() != newTokens.size() && newTokens.size() != 0) { System.out.print("Some words not found!! Showing results for: \""); for(String token:newTokens) { System.out.print(token + " "); } System.out.print("\" instead.\n"); } Collections.sort(tokenList); return processQuery(tokenList, numberOfResults); } private DocumentScore[] processQuery(List<WordFrequencyEntry> wordFrequencyEntries, int numberOfResults) throws FileNotFoundException, IOException{ PriorityQueue<DocumentScore> documentHeap = new PriorityQueue<DocumentScore>( numberOfResults, new Comparator<DocumentScore>() { @Override public int compare(DocumentScore o1, DocumentScore o2) { if(o1.getScore()==o2.getScore()) return 0; return( (o1.getScore()-o2.getScore())>0 )?1:-1; } }); //Assumes a sorted array of wordIDs ArrayList<WrapperIndexEntry> indexEntries = new ArrayList<WrapperIndexEntry>(wordFrequencyEntries.size()); for( WordFrequencyEntry wordFrequencyEntry : wordFrequencyEntries ){ int wordID = wordFrequencyEntry.getWordID(); IndexEntry temp = indexReader.openList(wordID); if(temp!=null){ indexEntries.add(new WrapperIndexEntry(temp) ); } } int maxdocID = indexEntries.get(0).getMaxDocID(); //for(WrapperIndexEntry indexEntry:indexEntries) // System.out.println(indexEntry.toString()); int documentID = 0; while (documentID <= maxdocID) { /* get next post from shortest list */ documentID = WrapperIndexEntry.nextGEQ(indexEntries.get(0), documentID); /* see if you find entries with same docID in other lists */ int d=0; for (int i=1; (i<indexEntries.size()) && ((d=WrapperIndexEntry.nextGEQ(indexEntries.get(i), documentID)) == documentID); i++); if (d > documentID) { documentID = d; /* not in intersection and we move to the next possible id*/ } else { List<Integer> frequency = new ArrayList<Integer>(indexEntries.size()) ; List<Integer> globalFrequencies = new ArrayList<Integer>(indexEntries.size()); BM25Scorer scorer = new BM25Scorer(1.2, 0.75); /* docID is in intersection; now get all frequencies */ for (int i=0; i<indexEntries.size(); i++) { //frequency[i] = indexEntries.get(i).getFrequency(did);} frequency.add( WrapperIndexEntry.currentFrequency(indexEntries.get(i))); globalFrequencies.add(indexEntries.get(i).getDocVectorSize()); } /* compute BM25 score from frequencies and other data */ double score = scorer.score(documentMap.size(), globalFrequencies, frequency, documentMap.get(documentID).getDocumentLength(), avgDocumentLength); //Get Total Documents N from the documentRegistrar //int globalFrequency = lexiconSingleton.ge //Get Totol Frequency F from the LexiconRegistrar or the indexEntity //Length of document d from the documentRegistrar //AverageDocumentLenght |d| from the documentRegistrar //k & b are constants //add it to the heap documentHeap.offer(new DocumentScore(documentID, score)); if(documentHeap.size()>numberOfResults) documentHeap.remove(); documentID++; /* and increase did to search for next post */ } } DocumentScore[] a = {}; return documentHeap.toArray(a); // return heap results. } public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException{ System.out.println("Loading Lexicon..."); ObjectInputStream objectInputStream = new ObjectInputStream( new BufferedInputStream(new FileInputStream( "/Users/Walliee/Documents/workspace/indexing/temp50/FinalIndexLexicon"))); Lexicon lexicon = (Lexicon) objectInputStream.readObject(); objectInputStream.close(); System.out.println("Lexicon loading complete"); Map<String,Integer> wordMap = new HashMap<String, Integer>(50000); Map<Integer, DocumentInfo> documentMap = new HashMap<Integer, DocumentInfo>(500000); BufferedReader wordIdReader = new BufferedReader( new FileReader("/Users/Walliee/Documents/workspace/indexing/temp50/WordID") ); System.out.println("Loading DocID references..."); BufferedReader docIdReader = new BufferedReader( new FileReader("/Users/Walliee/Documents/workspace/indexing/temp50/DocumentID") ); String wordLine; while(null != (wordLine = wordIdReader.readLine())){ String[] split = wordLine.split("\\$\\$"); wordMap.put(split[0], Integer.valueOf(split[1])); } while(null != (wordLine = docIdReader.readLine())){ String[] split = wordLine.split("\\$\\$"); documentMap.put(Integer.valueOf(split[1]),new DocumentInfo(split[0],Integer.valueOf(split[2]))); } objectInputStream = new ObjectInputStream( new BufferedInputStream(new FileInputStream( "/Users/Walliee/Documents/workspace/indexing/temp50/IndexStatistics"))); CorpusStatistics corpusStatistics = (CorpusStatistics) objectInputStream.readObject(); double avgDocumentLength = ((double)corpusStatistics.getTotalPostings())/((double) corpusStatistics.getTotalDocuments()); IndexReader indexReader = new IndexReader(lexicon, 1, "/Users/Walliee/Documents/workspace/indexing/temp50/FinalIndex", true); QueryProcessor queryProcessor = new QueryProcessor(indexReader, lexicon, wordMap,documentMap,avgDocumentLength); boolean toContinue = true; while(toContinue){ try{ System.out.println("Enter Your Query : "); BufferedReader bufferReader = new BufferedReader(new InputStreamReader(System.in)); String string = bufferReader.readLine(); string = string.toLowerCase(); //String[] tokens = string.split(" "); List<String> tokens = new ArrayList<String>(Arrays.asList(string.split(" "))); //int[] termIDArray = new int[0]; System.out.println("How many pages do you want?"); string = bufferReader.readLine(); int numberOfResults =Integer.valueOf(string); Long startTime = System.currentTimeMillis(); List<DocumentScore> documentScores = new ArrayList<DocumentScore>(Arrays.asList(queryProcessor.search(tokens, numberOfResults))); Long stopTime= System.currentTimeMillis(); //Collections.reverse(Collections.sort(documentScores)); Collections.sort(documentScores, Collections.reverseOrder()); if(documentScores.size()>0){ // for(DocumentScore documentScore: documentScores){ // } System.out.println("Found " + documentScores.size() + " matching documents in " + (stopTime-startTime) + " milliSeconds"); System.out.println("####################################################################################"); for(DocumentScore documentScore:documentScores){ System.out.println(documentMap.get(documentScore.getDocID()).getUrl()+ " : "+documentScore.getScore()); } } else System.out.println("Sorry!! No Matches Found for the given query"); System.out.println("####################################################################################"); //System.out.println("Found "+documentScores.length+" matching documents in "+(stopTime-startTime)+" milliSeconds"); System.out.println("Do you want to continue? type Y to continue:"); string = bufferReader.readLine(); if(!(string.equalsIgnoreCase("yes")|| string.equalsIgnoreCase("y"))){ System.out.println("Invalid Input. Exiting"); toContinue = false; } } catch(IOException e) { e.printStackTrace(); } finally { wordIdReader.close(); docIdReader.close(); } } } }
package com.ifre.util.encrypte; import java.io.BufferedInputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; import sun.misc.BASE64Decoder; import sun.misc.BASE64Encoder; /** * Protect class file from decompile. * * @author Yan Sun * @version 1.0 */ public class ClassGuarder { private String strKeyAlg = "AES"; private int nKeySize = 128; private String strCipherAlg = "AES/CBC/PKCS5Padding"; private static final String fileSeparator = "/"; private SecretKey key = null; private byte[] baIv = new byte[128]; private static ClassGuarder classGuarder = null; public static synchronized ClassGuarder getInstance() { if (classGuarder == null) { classGuarder = new ClassGuarder(); } return classGuarder; } public static synchronized ClassGuarder getInstance(String seedName) { if (classGuarder == null) { classGuarder = new ClassGuarder(seedName); } return classGuarder; } private ClassGuarder(String seedName) { try { InputStream inputStream = getClass().getClassLoader().getResourceAsStream(seedName); inputStream.read(baIv); byte[] baKey = new byte[nKeySize / 8]; baKey = Arrays.copyOf(baIv, nKeySize / 8); key = new SecretKeySpec(baKey, strKeyAlg); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } finally { } } private ClassGuarder() { // Put the seed file in the working directory. String path = fileSeparator+"com"+fileSeparator+"ifre"+fileSeparator+"util"+fileSeparator+"encrypte"+fileSeparator+"IfreClassLoader.class"; try { BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(path)); inputStream.read(baIv); byte[] baKey = new byte[nKeySize / 8]; baKey = Arrays.copyOf(baIv, nKeySize / 8); key = new SecretKeySpec(baKey, strKeyAlg); inputStream.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { } } private InputStream loadClassData(String name) { // Opening the file InputStream stream = getClass().getClassLoader().getResourceAsStream(name); /* int size = stream.available(); byte buff[] = new byte[size]; DataInputStream in = new DataInputStream(stream); // Reading the binary data in.readFully(buff); in.close(); return buff;*/ return stream; } private void initKey(BufferedInputStream inputStream) { try { inputStream.read(baIv); byte[] baKey = new byte[nKeySize / 8]; baKey = Arrays.copyOf(baIv, nKeySize / 8); key = new SecretKeySpec(baKey, strKeyAlg); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } finally { } } /** * Encrypt a file. * * @param classFile * @return encrypted bytes */ public byte[] encryptClass(File classFile) { byte[] encoded = null; try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(classFile))) { encoded = doCrypto(key, baIv, inputStream, Cipher.ENCRYPT_MODE, strCipherAlg); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } return encoded; } /** * Decrypt a byte array * * @param encodedClass * @return decrypted bytes. */ public byte[] decryptClass(byte[] encodedClass) { byte[] decodedByte = null; ByteArrayInputStream bai = new ByteArrayInputStream(encodedClass); try { decodedByte = doCrypto(key, baIv, bai, Cipher.DECRYPT_MODE, strCipherAlg); } catch (Exception e) { e.printStackTrace(); } return decodedByte; } /** * Performs the cryptographic operation on the specified IO Streams. This * function is private and is not meant to be called directly. * * @param key * The secret key used in the crypto operation. * @param baIv * The initialization vector used in the crypto operation. * @param in * InputStream to from which data is read. * @param nMode * Operation mode; either Cipher.DECRYPT_MODE or * Cipher.ENCRYPT_MODE * @param strCipherAlg * The encryption algorithm; this must correspond to something * that makes sense with the specified secret key * @throws Exception */ private byte[] doCrypto(SecretKey key, byte[] baIv, InputStream in, int nMode, String strCipherAlg) throws Exception { ByteArrayOutputStream out = new ByteArrayOutputStream(); Cipher cipher = Cipher.getInstance(strCipherAlg); cipher.init(nMode, key, new IvParameterSpec(baIv, 0, cipher.getBlockSize())); CipherInputStream cis = new CipherInputStream(in, cipher); byte[] baBuff = new byte[1024]; int nBytesRead = -1; while ((nBytesRead = cis.read(baBuff)) != -1) { out.write(baBuff, 0, nBytesRead); } byte[] result = out.toByteArray(); cis.close(); in.close(); out.flush(); out.close(); return result; } /** * Decrypt a byte array with base64 algorithm. * * @param encodedClass * @return decrypted bytes. */ private byte[] base64Decrypt(byte[] encodedClass) { byte[] decodedByte = null; BASE64Decoder decoder = new BASE64Decoder(); ByteArrayInputStream bai = new ByteArrayInputStream(encodedClass); try { decodedByte = decoder.decodeBuffer(bai); } catch (IOException e) { e.printStackTrace(); } return decodedByte; } /** * Encrypt a file with base64 algorithm. * * @param classFile * @return encrypted bytes */ private byte[] base64Encrypt(File classFile) { byte[] encoded = null; try (BufferedInputStream inputStream = new BufferedInputStream(new FileInputStream(classFile))) { // System.out.println("Available bytes from the file // :"+inputStream.available()); byte toBeEncoded[] = new byte[inputStream.available()]; inputStream.read(toBeEncoded); BASE64Encoder base64Encoder = new BASE64Encoder(); encoded = base64Encoder.encode(toBeEncoded).getBytes(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } return encoded; } }
package ru.kappers.exceptions; import org.junit.Test; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.*; public class BetParserExceptionTest { @Test public void constructorWithMessageOnly() { final String testMessage = "test message"; BetParserException exception = new BetParserException(testMessage); assertThat(exception.getMessage(), is(testMessage)); assertThat(exception.getCause(), is(nullValue())); } @Test public void constructorWithMessageAndException() { final String testMessage = "test message2"; final Exception testException = new Exception(); BetParserException exception = new BetParserException(testMessage, testException); assertThat(exception.getMessage(), is(testMessage)); assertThat(exception.getCause(), is(testException)); } }
package patterns.command; public class OpenFileCommand implements ICommand { private IFileSystemReceiver fileSystem; @Override public void execute() { // open command is forwarding request to openFile method this.fileSystem.openFile(); } public OpenFileCommand(IFileSystemReceiver fileSystem) { this.fileSystem = fileSystem; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.inftel.scrum.modelXML; import java.io.Serializable; import java.math.BigDecimal; /** * @author migueqm */ public class Historico implements Serializable { private static final long serialVersionUID = 1L; private BigDecimal id; private Usuario usuario; private Grupo grupo; public Historico() { } public Historico(BigDecimal id) { this.id = id; } public BigDecimal getId() { return id; } public void setId(BigDecimal id) { this.id = id; } public Usuario getUsuario() { return usuario; } public void setUsuario(Usuario usuario) { this.usuario = usuario; } public Grupo getGrupo() { return grupo; } public void setGrupo(Grupo grupo) { this.grupo = grupo; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are // not set if (!(object instanceof Historico)) { return false; } Historico other = (Historico) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "org.inftel.scrum.model.Historico[ id=" + id + " ]"; } }
/* * 文 件 名: BTree.java * 描 述: B树数据结构算法实现 * 修 改 人: root * 修改时间: 2014-10-30 * 跟踪单号: <跟踪单号> * 修改单号: <修改单号> * 修改内容: <修改内容> */ package com.henry.tree; /** * * <功能详细描述> * * @author root * @version [版本号, 2014-10-30] * @see [相关类/方法] * @since [产品/模块版本] */ public class BTree { //树的根节点 private BTreeNode root; private int t; public BTree(int t){ this.t=t; BTreeNode x = new BTreeNode(this.t); this.root=x; } public BTreeNode getRoot() { return root; } public void setRoot(BTreeNode root) { this.root = root; } public int getT() { return t; } }
package com.example.recyclerview.Adaptador; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.TextView; import com.example.recyclerview.Modelos.Persona; import com.example.recyclerview.R; import java.util.List; public class AdaptadorPersona extends RecyclerView.Adapter<AdaptadorPersona.ViewHolder> { List<Persona> lp; public AdaptadorPersona(List<Persona> lp) { this.lp = lp; } @NonNull @Override public ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View v=LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.itemrcd,viewGroup,false); ViewHolder vh=new ViewHolder(v); return vh; } @Override public void onBindViewHolder(@NonNull AdaptadorPersona.ViewHolder viewHolder, int i) { viewHolder.txtnombre.setText(lp.get(i).getNombre()); viewHolder.txtapellido.setText(lp.get(i).getApellido()); viewHolder.txtedad.setText(lp.get(i).getEdad().toString()); } @Override public int getItemCount() { return lp.size(); } public class ViewHolder extends RecyclerView.ViewHolder { TextView txtnombre; TextView txtapellido; TextView txtedad; public ViewHolder(@NonNull View itemView) { super(itemView); txtnombre=itemView.findViewById(R.id.txtNombre); txtapellido=itemView.findViewById(R.id.txtApellido); txtedad=itemView.findViewById(R.id.txtEdad); } } }
package codesum.lm.topicsum; public class Term { private String term; private Double score; public String getTerm() { return term; } public void setTerm(String term) { this.term = term; } public Double getScore() { return score; } public void setScore(Double score) { this.score = score; } }
package com.xxl.job.executor.jobhandler; import com.xxl.job.core.biz.model.ReturnT; import com.xxl.job.core.handler.IJobHandler; import com.xxl.job.core.handler.annotation.JobHandler; import com.xxl.job.core.log.XxlJobLogger; import com.xxl.job.executor.service.MaintAlertService; import com.xxl.job.executor.util.ListUtil; import net.tycmc.bulb.common.util.DateUtil; import org.apache.commons.collections.MapUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; /** * 任务Handler示例(Bean模式) * * 开发步骤: * 1、继承"IJobHandler":“com.xxl.job.core.handler.IJobHandler”; * 2、注册到Spring容器:添加“@Component”注解,被Spring容器扫描为Bean实例; * 3、注册到执行器工厂:添加“@JobHandler(value="自定义jobhandler名称")”注解,注解value值对应的是调度中心新建任务的JobHandler属性的值。 * 4、执行日志:需要通过 "XxlJobLogger.log" 打印执行日志; * * @author xuxueli 2015-12-19 19:43:36 */ @JobHandler(value="MaintAlertJobHandler") @Component public class MaintAlertJobHandler extends IJobHandler { @Autowired private MaintAlertService maintAlertService; /* * 1:东区 * param 1,0,6 * (non-Javadoc) * @see com.xxl.job.core.handler.IJobHandler#execute(java.lang.String) */ @Override public ReturnT<String> execute(String param) throws Exception { XxlJobLogger.log("保养提醒统计开始:"+param); String dateStr=DateUtil.addDay(-1); Map<String,Object>paramRe=new HashMap<String,Object>(); paramRe.put("condition",param); List<Map<String,Object>>listresult=maintAlertService.getLastMaintAlertPerVcl(paramRe); //获取每台车的累积工作时长 List<Map<String,Object>>listWorkHour=maintAlertService.getLJWorkHourPerVcl( dateStr); Map<String,List<Map<String,Object>>>MapWorkHour=new ListUtil().groupByOrder("PfVehicleId", listWorkHour); //获取每台车不同规则的保养提醒信息 List<Map<String,Object>>listPerRuler=maintAlertService.getMaintInfoPerVclDiffRuler(); Map<String,List<Map<String,Object>>>mapPerRuler=new ListUtil().groupByOrder("pfvehicleid", listPerRuler); if(listresult!=null&&listresult.size()>0){ List<Future<String>>futures=new ArrayList<Future<String>>(); List<String>sqlList=new ArrayList<String>(); for(Map<String,Object>mapresult:listresult){ String PfVehicleid=MapUtils.getString(mapresult, "PfVehicleid"); String ma_vclid=MapUtils.getString(mapresult, "ma_vclid"); String mri_ma_id=MapUtils.getString(mapresult, "mri_ma_id"); mapresult.put("alertDate", dateStr); if(StringUtils.isNotBlank(ma_vclid)){//说明存在最新一条保养提醒 //判断是否被保养了 if(StringUtils.isNotBlank(mri_ma_id)){//存在从键,说明被保养了,继续判断保养逻辑 Future<String> future=maintAlertService.execMaintAlertService(mapresult,MapWorkHour.get(PfVehicleid) , mapPerRuler.get(PfVehicleid)); futures.add(future); }else{//最新一条未被保养,不考虑保养逻辑 continue; } }else{//说明不存在最新的一条,继续判断保养逻辑 Future<String> future=maintAlertService.execMaintAlertService(mapresult,MapWorkHour.get(PfVehicleid) , mapPerRuler.get(PfVehicleid)); futures.add(future); } } for(Future<String> futureRe:futures){ String sql=futureRe.get(); if(StringUtils.isNotBlank(sql)){ sqlList.add(sql); } } //判断sqllist的size if(sqlList.size()>0){ //开始执行批量插入 boolean flag=maintAlertService.execBatch(sqlList); if(true==flag){ XxlJobLogger.log("执行成功,本次成功统计的sql条数为:"+sqlList.size()); }else{ XxlJobLogger.log("执行失败,本次应统计的sql条数为:"+sqlList.size()); } }else{ XxlJobLogger.log("执行成功,本次成功统计的sql条数为:"+0); } } return SUCCESS; } }
package com.linsr.mvpdemo; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import com.linsr.mvpdemo.service.MyIntentService; import com.linsr.mvpdemo.service.MyService; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Log.d("===", "===MainActivity curr[" + Thread.currentThread().getName() + "]"); startActivity(new Intent(this, com.linsr.mvpdemo.main.MainActivity.class)); startService(new Intent(this, MyIntentService.class)); startService(new Intent(this, MyService.class)); } }
import java.awt.datatransfer.SystemFlavorMap; import java.util.Scanner; public class Main { public static void main(String[] args) { /* Shape rectangle=new Rectangle(10,20); System.out.println("\nRectangle"); System.out.println("Area is:"+ rectangle.calculateArea()); System.out.println("Perimeter is:"+ rectangle.calculatePerimeter()); Shape square=new Square(10); System.out.println("\nSquare"); System.out.println("Area is:"+ square.calculateArea()); System.out.println("Perimeter is:"+ square.calculatePerimeter()); Shape circle=new Circle(10); System.out.println("\nCircle"); System.out.println("Area is:" + circle.calculateArea()); System.out.println("Perimeter is:" + circle.calculatePerimeter()); */ Shape shape; FactoryShape factoryShape=new FactoryShape(); System.out.println("Select the shape you want to perform operations"); System.out.println("1.Rectangle"); System.out.println("2.Square"); System.out.println("3.Circle"); System.out.println("4.Exit"); int choice; Scanner sc=new Scanner(System.in); choice=sc.nextInt(); switch(choice) { case 1: System.out.println("Enter the length"); double length=sc.nextDouble(); System.out.println("Enter the breadth"); double breadth=sc.nextDouble(); shape=factoryShape.createRectangle(length,breadth); System.out.println("\nRectangle"); System.out.println("Area is:" + shape.calculateArea()); System.out.println("Perimeter is:" + shape.calculatePerimeter()); break; case 2: System.out.println("Enter the side"); double side = sc.nextDouble(); shape=factoryShape.createSquare(side); System.out.println("\nSquare"); System.out.println("Area is:"+ shape.calculateArea()); System.out.println("Perimeter is:"+ shape.calculatePerimeter()); break; case 3: System.out.println("Enter the radius"); double radius = sc.nextDouble(); shape=factoryShape.createCircle(radius); System.out.println("\nCircle"); System.out.println("Area is:"+ shape.calculateArea()); System.out.println("Perimeter is:"+ shape.calculatePerimeter()); break; case 4:break; } } }
package com.mideas.rpg.v2.game.unit; import java.util.ArrayList; import com.mideas.rpg.v2.Mideas; import com.mideas.rpg.v2.chat.ChatFrame; import com.mideas.rpg.v2.chat.Message; import com.mideas.rpg.v2.chat.MessageType; import com.mideas.rpg.v2.game.CharacterStuff; import com.mideas.rpg.v2.game.Party; import com.mideas.rpg.v2.game.SocialFrameMenu; import com.mideas.rpg.v2.game.auction.AuctionHouse; import com.mideas.rpg.v2.game.classes.Wear; import com.mideas.rpg.v2.game.guild.Guild; import com.mideas.rpg.v2.game.guild.GuildRank; import com.mideas.rpg.v2.game.item.Item; import com.mideas.rpg.v2.game.item.ItemType; import com.mideas.rpg.v2.game.item.bag.Bag; import com.mideas.rpg.v2.game.item.container.ContainerManager; import com.mideas.rpg.v2.game.item.gem.Gem; import com.mideas.rpg.v2.game.item.gem.GemManager; import com.mideas.rpg.v2.game.item.stuff.Stuff; import com.mideas.rpg.v2.game.item.stuff.StuffManager; import com.mideas.rpg.v2.game.item.weapon.WeaponManager; import com.mideas.rpg.v2.game.item.weapon.WeaponType; import com.mideas.rpg.v2.game.preamade_group.PremadeGroup; import com.mideas.rpg.v2.game.profession.Profession; import com.mideas.rpg.v2.game.profession.ProfessionManager; import com.mideas.rpg.v2.game.race.Race; import com.mideas.rpg.v2.game.shortcut.Shortcut; import com.mideas.rpg.v2.game.social.Friend; import com.mideas.rpg.v2.game.social.Ignore; import com.mideas.rpg.v2.hud.LogChat; import com.mideas.rpg.v2.hud.PartyFrame; import com.mideas.rpg.v2.hud.SpellBarFrame; import com.mideas.rpg.v2.hud.social.SocialFrame; import com.mideas.rpg.v2.hud.social.friends.FriendsFrame; public class Joueur extends Unit { public final static int MAXIMUM_AMOUNT_IGNORES = 50; public final static int MAXIMUM_AMOUNT_FRIENDS = 50; private ArrayList<Friend> friendList; private ArrayList<Ignore> ignoreList; private Profession secondProfession; private Profession firstProfession; private final AuctionHouse auctionHouse; private WeaponType[] weaponType; private ArrayList<Integer> spellUnlockedList; private PremadeGroup premadeGroup; private int numberYellowGem; private GuildRank guildRank; private Bag bag = new Bag(); private long GCDStartTimer; private int numberBlueGem; private String guildTitle; private int defaultArmor; private long GCDEndTimer; private int numberRedGem; private Stuff[] stuff; private int critical; private int strength; private Unit target; private Party party; private int baseExp; private float armor; private Guild guild; private Wear wear; private long gold; private int copperPiece; private String copperPieceString; private int silverPiece; private String silverPieceString; private int goldPiece; private String goldPieceString; private long exp; private final static String warrior = "Guerrier"; private final static String hunter = "Hunter"; private final static String mage = "Mage"; private final static String paladin = "Paladin"; private final static String priest = "Priest"; private final static String rogue = "Rogue"; private final static String shaman = "Shaman"; private final static String warlock = "Warlock"; private final static String druid = "Druid"; public Joueur(ClassType classType, int id, String name, Wear wear, WeaponType[] weaponType, int stamina, int mana, int strength, int armor, int defaultArmor, int critical, int maxStamina, int maxMana) { super(id, stamina, maxStamina, mana, maxMana, 1, "", classType); this.strength = strength; this.armor = armor; this.defaultArmor = defaultArmor; this.name = name; this.critical = critical; this.spellUnlockedList = new ArrayList<Integer>(); this.weaponType = weaponType; this.stuff = new Stuff[19]; this.wear = wear; this.firstProfession = ProfessionManager.getProfession(0); this.auctionHouse = new AuctionHouse(); //this.classString = convClassTypeToString(this.classType); this.friendList = new ArrayList<Friend>(); this.friendList.add(new Friend(5, "Test")); this.friendList.add(new Friend(5, "Test")); this.friendList.add(new Friend(5, "Test")); this.friendList.add(new Friend(5, "Test")); this.friendList.add(new Friend(5, "Test")); this.friendList.add(new Friend(5, "Test")); this.friendList.add(new Friend(5, "Test")); this.friendList.add(new Friend(5, "Test")); this.friendList.add(new Friend(5, "Test")); this.friendList.add(new Friend(5, "Test")); this.friendList.add(new Friend(5, "Test")); this.friendList.add(new Friend(5, "Test")); this.friendList.add(new Friend(5, "Test")); this.friendList.add(new Friend(5, "Test")); this.friendList.add(new Friend(5, "Test")); this.friendList.add(new Friend(5, "Test")); this.friendList.add(new Friend(5, "Test")); this.friendList.add(new Friend(5, "Test")); this.friendList.add(new Friend(5, "Test")); this.friendList.add(new Friend(5, "Test")); this.friendList.add(new Friend(5, "Test")); this.friendList.add(new Friend(5, "Test")); this.friendList.add(new Friend(5, "Test")); this.friendList.add(new Friend(5, "Test")); this.friendList.add(new Friend(5, "Test")); this.friendList.add(new Friend(5, "Test")); this.friendList.add(new Friend(5, "Test")); this.friendList.add(new Friend(5, "Test")); this.friendList.add(new Friend(5, "Test")); this.ignoreList = new ArrayList<Ignore>(); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "Test")); this.ignoreList.add(new Ignore(1, "THEEND")); } public Joueur(Joueur joueur) { super(joueur.id, joueur.stamina, joueur.maxStamina, joueur.mana, joueur.maxMana, joueur.level, joueur.name, joueur.classType); this.spellUnlockedList = joueur.spellUnlockedList; this.auctionHouse = joueur.auctionHouse; this.defaultArmor = joueur.defaultArmor; this.classString = joueur.classString; this.weaponType = joueur.weaponType; this.friendList = joueur.friendList; this.ignoreList = joueur.ignoreList; this.strength = joueur.strength; this.critical = joueur.critical; this.stuff = joueur.stuff; this.armor = joueur.armor; this.mana = joueur.mana; this.wear = joueur.wear; } /*public void tick() throws SQLException { if(Mideas.getCurrentPlayer()) { attack(this.target); SpellBarFrame.setIsCastingSpell(false); } } public boolean cast(Spell spell) throws SQLException { if(spell.getType() == SpellType.DAMAGE) { SpellBarFrame.setIsCastingSpell(false); if(!spell.hasMana()) { attack(Mideas.target()); } else { spell.cast(Mideas.target(), Mideas.joueur1(), spell); //LogChat.setStatusText("Le joueur 1 a enlevée "+spell.getDamage()+" hp au "+Mideas.target().getClasse()+", "+Mideas.target().getStamina()+" hp restant"); return true; } } else if(spell.getType() == SpellType.HEAL) { SpellBarFrame.setIsCastingSpell(false); if(!spell.hasMana()) { attack(Mideas.target()); } else { if(Mideas.joueur1().getStamina()+spell.getHeal() >= Mideas.joueur1().getMaxStamina()) { int diff = Mideas.joueur1().getMaxStamina()-Mideas.joueur1().getStamina(); spell.healMax(Mideas.joueur1(), spell); LogChat.setStatusText("Vous vous êtes rendu "+diff+" hp, vous avez maintenant "+Mideas.joueur1().getStamina()+" hp"); return true; } else { spell.heal(Mideas.joueur1(), spell); LogChat.setStatusText("Vous vous êtes rendu "+spell.getHeal()+" hp, vous avez maintenant "+Mideas.joueur1().getStamina()+" hp"); return true; } } } return false; }*/ /*public void attack(Joueur joueur) throws SQLException { double damage = Mideas.joueur1().getStrength()*ThreadLocalRandom.current().nextDouble(.9, 1.1); SpellBarFrame.setIsCastingSpell(false); if(Math.random() < this.critical/100.) { damage*= 2; } joueur.setStamina(joueur.getStamina()-damage); //LogChat.setStatusText("Le joueur 1 a enlevé "+Math.round(damage)+" hp au "+joueur.getClasse()+", "+joueur.getStamina()+" hp restant"); //and "+Mideas.joueur2.getMana()+" mana left"); if(Mideas.joueur1().getStamina() <= 0) { LogChat.setStatusText("Le joueur 2 a gagné !"); LogChat.setStatusText2(""); y = 1; return; } else if(Mideas.target().getStamina() <= 0) { LogChat.setStatusText("Le joueur 1 a gagné !"); LogChat.setStatusText2(""); z = 1; return; } }*/ /*public void attackUI(Spell spell) { double damage = Mideas.joueur2().getStrength()*ThreadLocalRandom.current().nextDouble(.9, 1.1); float rand = (float)Math.random(); if(rand < Mideas.joueur2().getCritical()/100.) { damage*= 2; } if(spell.getType() == SpellType.HEAL && spell.hasMana()) { if(Mideas.joueur2().getStamina() < Mideas.joueur2().getMaxStamina()) { if(Mideas.joueur2().getStamina()+spell.getHeal() >= Mideas.joueur2().getMaxStamina()) { int diff = Mideas.joueur2().getMaxStamina()-Mideas.joueur2().getStamina(); spell.healMax(Mideas.joueur2(), spell); LogChat.setStatusText2("Le joueur2 s'est rendu "+diff+" hp, il a maintenant "+Mideas.joueur2().getStamina()+" hp"); } else { spell.heal(Mideas.joueur2(), spell); LogChat.setStatusText2("Le joueur2 s'est rendu "+spell.getHeal()+" hp, il a maintenant "+Mideas.joueur2().getStamina()+" hp"); } } } else if(spell.getType() == SpellType.DAMAGE) { Spell cast = Spell.getRandomSpell(); if(rand > .2 && rand <= .4 && cast.hasMana()) { cast.cast(Mideas.joueur1(), Mideas.joueur2(), spell); LogChat.setStatusText2("Le joueur 2 a enlevée "+cast.getDamage()+" hp au "+Mideas.joueur1().getClasse()+", "+Mideas.joueur1().getStamina()+" hp restant"); } else { Mideas.joueur1().setStamina(Mideas.joueur1().getStamina()-damage); LogChat.setStatusText2("Le joueur 2 a enlevée "+Math.round(damage)+" hp au "+Mideas.joueur1().getClasse()+", "+Mideas.joueur1().getStamina()+" hp restant"); } } }*/ /*public void loadStuff() { int i = 0; Interface.setStuffFullyLoaded(true); while(i < Mideas.joueur1().getStuff().length) { if(Mideas.joueur1().getStuff(i) != null && !Mideas.joueur1().getStuff(i).getIsLoaded()) { if(StuffManager.exists(Mideas.joueur1().getStuff(i).getId())) { Gem gem1 = Mideas.joueur1().getStuff(i).getEquippedGem(0); Gem gem2 = Mideas.joueur1().getStuff(i).getEquippedGem(1); Gem gem3 = Mideas.joueur1().getStuff(i).getEquippedGem(2); Mideas.joueur1().setStuff(i, StuffManager.getClone(Mideas.joueur1().getStuff(i).getId())); Mideas.joueur1().getStuff(i).setEquippedGem(0, gem1); Mideas.joueur1().getStuff(i).setEquippedGem(1, gem2); Mideas.joueur1().getStuff(i).setEquippedGem(2, gem3); ConnectionManager.getItemRequested().remove(Mideas.joueur1().getStuff(i).getId()); Mideas.joueur1().getStuff(i).setIsLoaded(true); i++; continue; } else if(WeaponManager.exists(Mideas.joueur1().getStuff(i).getId())) { Gem gem1 = Mideas.joueur1().getStuff(i).getEquippedGem(0); Gem gem2 = Mideas.joueur1().getStuff(i).getEquippedGem(1); Gem gem3 = Mideas.joueur1().getStuff(i).getEquippedGem(2); Mideas.joueur1().setStuff(i, WeaponManager.getClone(Mideas.joueur1().getStuff(i).getId())); Mideas.joueur1().getStuff(i).setEquippedGem(0, gem1); Mideas.joueur1().getStuff(i).setEquippedGem(1, gem2); Mideas.joueur1().getStuff(i).setEquippedGem(2, gem3); ConnectionManager.getItemRequested().remove(Mideas.joueur1().getStuff(i).getId()); Mideas.joueur1().getStuff(i).setIsLoaded(true); i++; continue; } Interface.setStuffFullyLoaded(false); } else if(Mideas.joueur1().getStuff(i) != null && !checkGemLoaded(Mideas.joueur1().getStuff(i))) { int j = 0; while(j < Mideas.joueur1().getStuff(i).getEquippedGems().length) { if(Mideas.joueur1().getStuff(i).getEquippedGem(j) != null && !Mideas.joueur1().getStuff(i).getEquippedGem(j).getIsLoaded()) { if(GemManager.exists(Mideas.joueur1().getStuff(i).getEquippedGem(j).getId())) { Mideas.joueur1().getStuff(i).setEquippedGem(j, GemManager.getClone(Mideas.joueur1().getStuff(i).getEquippedGem(j).getId())); } } else { Interface.setStuffFullyLoaded(false); } j++; } } i++; } }*/ /*private static boolean checkGemLoaded(Stuff stuff) { int i = 0; while(i < stuff.getEquippedGems().length) { if(stuff.getEquippedGem(i) != null && !stuff.getEquippedGem(i).getIsLoaded()) { return false; } i++; } return true; }*/ /*public void loadBag() { int i = 0; Interface.setBagFullyLoaded(true); while(i < this.bag.getBag().length) { if(this.bag.getBag(i) != null && !this.bag.getBag(i).getIsLoaded()) { if(StuffManager.exists(this.bag.getBag(i).getId())) { Gem gem1 = ((Stuff)this.bag.getBag(i)).getEquippedGem(0); Gem gem2 = ((Stuff)this.bag.getBag(i)).getEquippedGem(1); Gem gem3 = ((Stuff)this.bag.getBag(i)).getEquippedGem(2); this.bag.setBag(i, StuffManager.getClone(this.bag.getBag(i).getId())); ((Stuff)this.bag.getBag(i)).setEquippedGem(0, gem1); ((Stuff)this.bag.getBag(i)).setEquippedGem(1, gem2); ((Stuff)this.bag.getBag(i)).setEquippedGem(2, gem3); ConnectionManager.getItemRequested().remove(this.bag.getBag(i).getId()); this.bag.getBag(i).setIsLoaded(true); } else if(WeaponManager.exists(this.bag.getBag(i).getId())) { Gem gem1 = ((Stuff)this.bag.getBag(i)).getEquippedGem(0); Gem gem2 = ((Stuff)this.bag.getBag(i)).getEquippedGem(1); Gem gem3 = ((Stuff)this.bag.getBag(i)).getEquippedGem(2); this.bag.setBag(i, WeaponManager.getClone(this.bag.getBag(i).getId())); ((Stuff)this.bag.getBag(i)).setEquippedGem(0, gem1); ((Stuff)this.bag.getBag(i)).setEquippedGem(1, gem2); ((Stuff)this.bag.getBag(i)).setEquippedGem(2, gem3); ConnectionManager.getItemRequested().remove(this.bag.getBag(i).getId()); this.bag.getBag(i).setIsLoaded(true); } else if(GemManager.exists(this.bag.getBag(i).getId())) { this.bag.setBag(i, GemManager.getClone(this.bag.getBag(i).getId())); ConnectionManager.getItemRequested().remove(this.bag.getBag(i).getId()); this.bag.getBag(i).setIsLoaded(true); } else if(ContainerManager.exists(this.bag.getBag(i).getId())) { this.bag.setBag(i, ContainerManager.getClone(this.bag.getBag(i).getId())); ConnectionManager.getItemRequested().remove(this.bag.getBag(i).getId()); this.bag.getBag(i).setIsLoaded(true); } else if(PotionManager.exists(this.bag.getBag(i).getId())) { int number = this.bag.getBag(i).getAmount(); this.bag.setBag(i, PotionManager.getClone(this.bag.getBag(i).getId()), number); ConnectionManager.getItemRequested().remove(this.bag.getBag(i).getId()); this.bag.getBag(i).setIsLoaded(true); } else { Interface.setBagFullyLoaded(false); } } if(this.bag.getBag(i) != null && (this.bag.getBag(i).isStuff() || this.bag.getBag(i).isWeapon())) { int j = 0; while(j < ((Stuff)this.bag.getBag(i)).getEquippedGems().length) { if(((Stuff)this.bag.getBag(i)).getEquippedGem(j) != null && !((Stuff)this.bag.getBag(i)).getEquippedGem(j).getIsLoaded()) { if(GemManager.exists(((Stuff)this.bag.getBag(i)).getEquippedGem(j).getId())) { ((Stuff)this.bag.getBag(i)).setEquippedGem(j, GemManager.getClone(((Stuff)this.bag.getBag(i)).getEquippedGem(j).getId())); } else { Interface.setBagFullyLoaded(false); } } j++; } } i++; } if(Interface.getBagFullyLoaded()) { if(Mideas.joueur1().getFirstProfession() != null) { Mideas.joueur1().getFirstProfession().updateNumberPossibleCraft(); } else if(Mideas.joueur1().getSecondProfession() != null) { Mideas.joueur1().getSecondProfession().updateNumberPossibleCraft(); } } }*/ /*public void loadSpellbar() { int i = 0; Interface.setSpellbarFullyLoaded(true); while(i < Mideas.joueur1().getSpells().length) { if(Mideas.joueur1().getSpells(i) != null && !Mideas.joueur1().getSpells(i).getIsLoaded()) { if(StuffManager.exists(Mideas.joueur1().getSpells(i).getId())) { Mideas.joueur1().setSpells(i, new StuffShortcut(StuffManager.getClone(Mideas.joueur1().getSpells(i).getId()))); ConnectionManager.getItemRequested().remove(Mideas.joueur1().getSpells(i).getId()); Mideas.joueur1().getSpells(i).setIsLoaded(true); i++; continue; } else if(WeaponManager.exists(Mideas.joueur1().getSpells(i).getId())) { Mideas.joueur1().setSpells(i, new StuffShortcut(WeaponManager.getClone(Mideas.joueur1().getSpells(i).getId()))); ConnectionManager.getItemRequested().remove(Mideas.joueur1().getSpells(i).getId()); Mideas.joueur1().getSpells(i).setIsLoaded(true); i++; continue; } else if(PotionManager.exists(Mideas.joueur1().getSpells(i).getId())) { Mideas.joueur1().setSpells(i, new PotionShortcut(PotionManager.getClone(Mideas.joueur1().getSpells(i).getId()))); ConnectionManager.getItemRequested().remove(Mideas.joueur1().getSpells(i).getId()); Mideas.joueur1().getSpells(i).setIsLoaded(true); i++; continue; } Interface.setSpellbarFullyLoaded(false); } i++; } }*/ public boolean addItem(Item item, int amount) { if(amount == 1) { return addSingleItem(item, amount); } else if(amount > 1) { if(item.isStackable()) { return addSingleItem(item, amount); } return addMultipleUnstackableItem(item.getId(), amount); } return false; } private boolean addSingleItem(Item item, int amount) { int i = 0; if(!item.isStackable()) { while(i < this.bag.getBag().length && amount > 0) { if(this.bag.getBag(i) == null) { this.bag.setBag(i, item); amount --; } i++; } //CharacterStuff.setBagItems(); } else { while(i < this.bag.getBag().length) { if(this.bag.getBag(i) != null && this.bag.getBag(i).equals(item)) { this.bag.setBag(i, item, this.bag.getBag(i).getAmount()+amount); //CharacterStuff.setBagItems(); return true; } i++; } i = 0; while(i < this.bag.getBag().length) { if(this.bag.getBag(i) == null) { this.bag.setBag(i, item, amount); //CharacterStuff.setBagItems(); return true; } i++; } } LogChat.setStatusText3("Votre inventaire est pleins"); return false; } private boolean addMultipleUnstackableItem(int id, int number) { int i = 0; boolean returns = false; ItemType type = null; if(WeaponManager.exists(id) || StuffManager.exists(id) || GemManager.exists(id) || ContainerManager.exists(id)) { if(WeaponManager.exists(id)) { type = ItemType.WEAPON; } else if(StuffManager.exists(id)) { type = ItemType.STUFF; } else if(GemManager.exists(id)) { type = ItemType.GEM; } else if(ContainerManager.exists(id)) { type = ItemType.CONTAINER; } while(i < this.bag.getBag().length && number > 0) { if(this.bag.getBag(i) == null) { if(type == ItemType.WEAPON) { this.bag.setBag(i, WeaponManager.getClone(id)); } else if(type == ItemType.STUFF) { this.bag.setBag(i, StuffManager.getClone(id)); } else if(type == ItemType.GEM) { this.bag.setBag(i, GemManager.getClone(id)); } else { this.bag.setBag(i, ContainerManager.getClone(id)); } number--; returns = true; } i++; } //CharacterStuff.setBagItems(); } return returns; } public void deleteItem(Item item, int amount) { int i = 0; if(!item.isStackable()) { while(i < this.bag.getBag().length && amount > 0) { if(this.bag.getBag(i) != null && this.bag.getBag(i).equals(item)) { this.bag.setBag(i, null); amount--; } i++; } //CharacterStuff.setBagItems(); } else { while(i < this.bag.getBag().length && amount > 0) { if(this.bag.getBag(i) != null && this.bag.getBag(i).equals(item)) { int temp = amount; amount-= this.bag.getBag(i).getAmount(); this.bag.setBag(i, this.bag.getBag(i), Math.max(0, this.bag.getBag(i).getAmount()-temp)); } i++; } //CharacterStuff.setBagItems(); } } public boolean canWear(Stuff stuff) { if(stuff != null) { if(this.wear == Wear.PLATE) { return true; } if(this.wear == Wear.MAIL) { if(stuff.getWear() == Wear.PLATE) { return false; } return true; } if(this.wear == Wear.LEATHER) { if(stuff.getWear() == Wear.PLATE || stuff.getWear() == Wear.MAIL) { return false; } return true; } if(this.wear == Wear.CLOTH) { if(stuff.getWear() == Wear.CLOTH || stuff.getWear() == Wear.NONE) { return true; } return false; } } return false; } public boolean canEquipStuff(Stuff stuff) { if(Mideas.joueur1().getLevel() >= stuff.getLevel() && canWear(stuff) && stuff.canEquipTo(Joueur.convStringToClassType(Mideas.joueur1().getClasseString()))) { return true; } return false; } public void addFriend(Friend friend) { if(this.friendList.size() < MAXIMUM_AMOUNT_FRIENDS) { this.friendList.add(friend); sortFriendList(); ChatFrame.addMessage(new Message(friend.getName()+" is now in your friend list.", false, MessageType.SELF, true)); } } public void addFriendNoSort(Friend friend) { if(this.friendList.size() < MAXIMUM_AMOUNT_FRIENDS) { this.friendList.add(friend); } } public void removeFriend(int id) { int i = 0; while(i < this.friendList.size()) { Friend friend = this.friendList.get(i); if(friend.getCharacterId() == id) { ChatFrame.addMessage(new Message(friend.getName()+" is no longer in your friend list.", false, MessageType.SELF, true)); this.friendList.remove(i); if(this.friendList.size() == 0 || FriendsFrame.getSelectedFriend() == i) { FriendsFrame.resetSelectedFriend(); } return; } i++; } } public Friend getFriend(int id) { int i = 0; while(i < this.friendList.size()) { Friend friend = this.friendList.get(i); if(friend.getCharacterId() == id) { return friend; } i++; } return null; } public void sortFriendList() { int i = 0; int j = 0; Friend temp; while(i < this.friendList.size()) { j = i; while(j < this.friendList.size()) { if((this.friendList.get(i).isOnline() && this.friendList.get(j).isOnline() && this.friendList.get(i).getName().compareTo(this.friendList.get(j).getName()) > 0) || (!this.friendList.get(i).isOnline() && !this.friendList.get(j).isOnline() && this.friendList.get(i).getName().compareTo(this.friendList.get(j).getName()) > 0) || (this.friendList.get(j).isOnline() && !this.friendList.get(i).isOnline())) { temp = this.friendList.get(j); this.friendList.set(j, this.friendList.get(i)); this.friendList.set(i, temp); } j++; } i++; } } public ArrayList<Friend> getFriendList() { return this.friendList; } public void addIgnore(Ignore ignore) { if(this.ignoreList.size() < MAXIMUM_AMOUNT_IGNORES) { this.ignoreList.add(ignore); sortIgnoreList(); } } public void addIgnoreNoSort(Ignore ignore) { if(this.ignoreList.size() < MAXIMUM_AMOUNT_IGNORES) { this.ignoreList.add(ignore); } } public void removeIgnore(int id) { int i = 0; while(i < this.ignoreList.size()) { if(this.ignoreList.get(i).getId() == id) { this.ignoreList.remove(i); return; } i++; } } public void sortIgnoreList() { int i = 0; int j = 0; Ignore temp; while(i < this.ignoreList.size()) { j = i; while(j < this.ignoreList.size()) { if(this.ignoreList.get(i).getName().compareTo(this.ignoreList.get(j).getName()) > 0) { temp = this.ignoreList.get(j); this.ignoreList.set(j, this.ignoreList.get(i)); this.ignoreList.set(i, temp); } j++; } i++; } } public PremadeGroup getPremadeGroup() { return (this.premadeGroup); } public void setPremadeGroup(PremadeGroup group) { this.premadeGroup = group; } public ArrayList<Ignore> getIgnoreList() { return this.ignoreList; } public String getGuildTitle() { return this.guildTitle; } public GuildRank getGuildRank() { return this.guildRank; } public void setGuildRank(GuildRank guildRank) { this.guildRank = guildRank; this.guildTitle = guildRank.getName()+" of "+this.guild.getName(); } public Guild getGuild() { return this.guild; } public void setGuild(Guild guild) { this.guild = guild; if(this.guild == null) { SocialFrame.setSelectedMenu(SocialFrameMenu.FRIEND_FRAME); } } public AuctionHouse getAuctionHouse() { return this.auctionHouse; } public void setParty(Party party) { if(party == null) { PartyFrame.setDisplayMember(-1); } this.party = party; } public boolean canInvitePlayerInParty(int id) { return id != this.id && ((this.party == null) || (this.party.isPartyLeader(this))); } public Party getParty() { return this.party; } public Unit getTarget() { return this.target; } public void setTarget(Unit target) { this.target = target; } public void setGCDStartTimer(long timer) { this.GCDStartTimer = timer; } public long getGCDStartTimer() { return this.GCDStartTimer; } public void setGCDEndTimer(long timer) { this.GCDEndTimer = timer; } public long getGCDEndTimer() { return this.GCDEndTimer; } public void setFirstProfession(Profession profession) { this.firstProfession = profession; } public Profession getFirstProfession() { return this.firstProfession; } public Profession getSecondProfession() { return this.secondProfession; } public void setSecondProfession(Profession profession) { this.secondProfession = profession; } public void setStuffArmor(int armor) { this.armor+= armor; } public void setStuffStrength(int strengh) { this.strength+= strengh; } public void setStuffStamina(int stamina) { this.maxStamina+= stamina; this.stamina+= stamina; this.hasHpChanged = true; } public void setStuffCritical(int critical) { this.critical+= critical; } public void setStuffMana(int mana) { this.maxMana+= mana; this.mana+= mana; this.hasManaChanged = true; } public void setNumberRedGem(int nb) { this.numberRedGem = nb; } public int getNumberRedGem() { return this.numberRedGem; } public void setNumberBlueGem(int nb) { this.numberBlueGem = nb; } public int getNumberBlueGem() { return this.numberBlueGem; } public void setNumberYellowGem(int nb) { this.numberYellowGem = nb; } public int getNumberYellowGem() { return this.numberYellowGem; } public float getArmor() { return this.armor; } public Wear getWear() { return this.wear; } public int getCritical() { return this.critical; } public int getStrength() { return this.strength; } public int getSpellsListSize() { return SpellBarFrame.getButtonList().length; } public Shortcut getSpells(int i) { return SpellBarFrame.getButton(i).getShortcut(); } public void setSpells(int i, Shortcut spell) { SpellBarFrame.setShortcut(i, spell); } public ArrayList<Integer> getSpellUnlocked() { return this.spellUnlockedList; } public void addSpellUnlocked(int id) { this.spellUnlockedList.add(id); } public void removeSpellUnlocked(int id) { int i = this.spellUnlockedList.size(); while(--i >= 0) { if(this.spellUnlockedList.get(i) == id) { this.spellUnlockedList.remove(i); return; } } } public Stuff[] getStuff() { return this.stuff; } public Stuff getStuff(int i) { return this.stuff[i]; } public void setStuff(int i, Item tempItem) { //TODO : add stats calculation if(this.stuff[i] != null) { } if(tempItem == null) { this.stuff[i] = null; } else if(tempItem.isStuff() || tempItem.isWeapon()) { if(this.stuff[i] != null) { SpellBarFrame.updateEquippedItem(this.stuff[i].getId(), false); } this.stuff[i] = (Stuff)tempItem; SpellBarFrame.updateEquippedItem(this.stuff[i].getId(), true); } else { System.out.println("Error on setStuff, tried to wear an item that isn't a Stuff"); } } public void updateStuff(int slot, Item item) { if(item == null) { System.out.println("Error updateStuff slot "+slot); return; } if(item.isStuff() || item.isWeapon()) { item.setIsLoaded(true); if(this.stuff[slot] == null) { this.stuff[slot] = (Stuff)item; } else { int i = 0; while(i < this.stuff[slot].getEquippedGems().length) { ((Stuff)item).setEquippedGem(i, this.stuff[slot].getEquippedGem(i)); i++; } this.stuff[slot] = (Stuff)item; } } } public void updateStuffGem(int slot, int gemSlot, Item item) { if(item == null) { System.out.println("Error updateStuffGem slot "+slot); return; } if(item.isGem()) { item.setIsLoaded(true); if(this.stuff[slot] == null) { return; } this.stuff[slot].setEquippedGem(gemSlot, (Gem)item); } } public Bag bag() { return this.bag; } public long getExp() { return this.exp; } public int getBaseExp() { return this.baseExp; } public void setArmor(float number) { this.armor = (Math.round(100*(this.armor+number))/100.f); } public int getDefaultArmor() { return this.defaultArmor; } public long getGold() { return this.gold; } public void setGold(long gold) { this.gold = gold; calcGoldPiece(); calcSilverPiece(); calcCopperPiece(); } private void calcGoldPiece() { this.goldPiece = (int)Math.floorDiv(this.gold, 10000); this.goldPieceString = String.valueOf(this.goldPiece); } private void calcSilverPiece() { this.silverPiece = (int)Math.floorDiv(this.gold % 10000, 100); this.silverPieceString = String.valueOf(this.silverPiece); } private void calcCopperPiece() { this.copperPiece = (int)this.gold % 100; this.copperPieceString = String.valueOf(this.copperPiece); } public static int getGoldPiece(int gold) { return Math.floorDiv(gold, 10000); } public static int getSilverPiece(int gold) { return Math.floorDiv(gold%10000, 100); } public static int getCopperPiece(int gold) { return gold%100; } public int getGoldPiece() { return this.goldPiece; } public String getGoldPieceString() { return this.goldPieceString; } public int getSilverPiece() { return this.silverPiece; } public String getSilverPieceString() { return this.silverPieceString; } public int getCopperPiece() { return this.copperPiece; } public String getCoppierPieceString() { return this.copperPieceString; } public void setExp(int baseExp, int expGained ) { this.exp = baseExp+expGained; } public void setExp(long exp) { this.exp = exp; this.level = Mideas.getLevel(this.exp); } public WeaponType[] getWeaponType() { return this.weaponType; } public WeaponType getweaponType(int i) { if(i < this.weaponType.length) { return this.weaponType[i]; } return null; } public static String convClassTypeToString(ClassType type) { if(type == ClassType.DRUID) { return druid; } if(type == ClassType.GUERRIER) { return warrior; } if(type == ClassType.HUNTER) { return hunter; } if(type == ClassType.MAGE) { return mage; } if(type == ClassType.PALADIN) { return paladin; } if(type == ClassType.PRIEST) { return priest; } if(type == ClassType.ROGUE) { return rogue; } if(type == ClassType.SHAMAN) { return shaman; } if(type == ClassType.WARLOCK) { return warlock; } return null; } public static ClassType convStringToClassType(String classType) { if(classType.equals(warrior)) { return ClassType.GUERRIER; } if(classType.equals(druid)) { return ClassType.DRUID; } if(classType.equals(hunter)) { return ClassType.HUNTER; } if(classType.equals(mage)) { return ClassType.MAGE; } if(classType.equals(paladin)) { return ClassType.PALADIN; } if(classType.equals(priest)) { return ClassType.PRIEST; } if(classType.equals(rogue)) { return ClassType.ROGUE; } if(classType.equals(shaman)) { return ClassType.SHAMAN; } if(classType.equals(warlock)) { return ClassType.WARLOCK; } return null; } public static String convRaceToString(Race race) { if(race == Race.BLOODELF) { return "Bloodelf"; } if(race == Race.DRAENEI) { return "Draenei"; } if(race == Race.DWARF) { return "Dwarf"; } if(race == Race.GNOME) { return "Gnome"; } if(race == Race.HUMAN) { return "Human"; } if(race == Race.NIGHTELF) { return "Nightelf"; } if(race == Race.ORC) { return "Orc"; } if(race == Race.TAUREN) { return "Tauren"; } if(race == Race.TROLL) { return "Troll"; } if(race == Race.UNDEAD) { return "Undead"; } return null; } }
package ad.joyplus.com.myapplication.entity; /** * 返回信息的数据模型 * Created by UPC on 2016/8/31. */ public class AdModel<T>{ /** * 版本号 */ public String VersonCode; /** * 返回码(1为正确返回或0错误返回) */ public String Code; /** * 返回为0时的错误信息 * 错误信息 */ public String msg; /** * 返回正确时,返回的data数据 */ public T data; }
package cc.protea.foundation.template.model; import java.sql.ResultSet; import java.util.List; import org.skife.jdbi.v2.Handle; import com.fasterxml.jackson.annotation.JsonIgnore; import cc.protea.foundation.integrations.DatabaseUtil; import cc.protea.platform.ProteaUser; import cc.protea.platform.UserUtil; public class TemplateUser extends ProteaUser { public String profilePictureUrl; @JsonIgnore public String getUserTableName() { return "template_user"; } public static TemplateUser select(Long id) { return DatabaseUtil.get(h -> select(h, id)); } public static TemplateUser select(Handle h, Long id) { return UserUtil.getProteaUser(h, id); } public static List<TemplateUser> selectAll() { return DatabaseUtil.get(h -> selectAll(h)); } public static List<TemplateUser> selectAll(Handle h) { return h.createQuery("SELECT * FROM profound_user LEFT JOIN template_user ON template_user.user_key = profound_user.user_key") .map(TemplateUser.mapper) .list(); } @Override public void update(Handle h) { super.update(h); h.createStatement("update template_user set" + " user_key = user_key, " + " profile_picture_url = :profilePictureUrl " + " where user_key = :id") .bind("profilePictureUrl", profilePictureUrl) .bind("id", id) .execute(); } @Override public Mapper<TemplateUser> mapper() { return mapper; } @JsonIgnore public static Mapper<TemplateUser> mapper = new ProteaUser.Mapper<TemplateUser> () { @Override public void fill(TemplateUser out, final ResultSet rs) { super.fill(out, rs); out.profilePictureUrl = DatabaseUtil.getString(rs, "profile_picture_url"); } }; public void delete() { if(this.id == null) { return; } UserUtil.remove(id); DatabaseUtil.transaction(h -> { h.execute("DELETE FROM " + getUserTableName() + " WHERE user_key = ?", id); }); } public void insert(Handle h) { // no-op use UserUtil instead } }
package edu.kit.pse.osip.simulation.view.main; import edu.kit.pse.osip.core.model.base.Pipe; import org.junit.Test; /** * A class testing PipeDrawer. */ public class PipeDrawerTest { /** * Checks for InvalidWayPointsException if there are too few points. */ @Test(expected = InvalidWaypointsException.class) public void pipeDrawerShortList() { Point2D[] waypoints = {}; new PipeDrawer(waypoints, null, 1); } /** * Checks for InvalidWayPointsException if the points are not properly aligned. */ @Test(expected = InvalidWaypointsException.class) public void pipeDrawerMisPlacedPoints() { Point2D[] waypoints = { new Point2D(1, 1), new Point2D(2, 2) }; new PipeDrawer(waypoints, null, 1); } /** * Tests whether there is no exception thrown if all parameters are properly * initialized. */ @Test public void pipeDrawerValidPoints() { Point2D[] waypoints = { new Point2D(1, 1), new Point2D(1, 2), new Point2D(2, 2) }; Pipe pipe = new Pipe(1f, 1, (byte) 1); new PipeDrawer(waypoints, pipe, 1); } }
package it.dstech.film.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; 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.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import it.dstech.film.model.Genere; import it.dstech.film.service.GenereService; @RestController @RequestMapping("/genere") public class GenereController { @Autowired GenereService service; /** * Find Genere by Id */ @ResponseStatus(HttpStatus.OK) @RequestMapping(value = { "/get/id={id}" }, method = RequestMethod.GET) public Genere getGenereById(@PathVariable("id") Integer id) { return service.findById(id); } @ResponseStatus(HttpStatus.OK) @RequestMapping(value = { "/new" }, method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE) public void save(@RequestBody Genere genere) { service.save(genere); } }
package org.rocksdb.memtable; import org.rocksdb.Options; import org.rocksdb.VectorMemTableConfig; /** * @fileName: MemTableConfig.java * @description: MemTableConfig.java类说明 * @author: huangshimin * @date: 2021/10/13 8:04 下午 */ public class MemTableConfigFeature { public static void main(String[] args) { Options options = new Options(); // 指定memtable底层实现,默认为skiplist,支持hashSkipList,hashlinked,vector等 options.setMemTableConfig(new VectorMemTableConfig()); // 单个memtable大小 默认大小64MB // options.setWriteBufferSize() // 最多的memtable个数默认为2,超过会刷新到sst file中 options.setMaxWriteBufferNumber(2); // 保留的历史的memtable options.setMaxWriteBufferNumberToMaintain(0); } }
package com.tencent.mm.plugin.appbrand.q; import com.tencent.mm.y.g.a; public final class d { public long bJC; public a bXA; public long bYu; public String bgo; public String desc; public String dyT; public String gBq; public String imagePath; public String nickname; public long timestamp; public String title; public int type; public String username; public d(long j, int i, String str, long j2, String str2, String str3, String str4, String str5, String str6, a aVar, long j3) { this.timestamp = j; this.type = i; this.title = str; this.bJC = j2; this.username = str2; this.nickname = str3; this.bgo = str4; this.gBq = str5; this.dyT = str6; this.bXA = aVar; this.bYu = j3; } }
/* * Copyright 2013 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.overlord.rtgov.analytics.situation.store.elasticsearch; import java.util.List; import java.util.Set; import java.util.Map.Entry; import java.util.logging.Level; import java.util.logging.Logger; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.action.search.SearchType; import org.elasticsearch.common.unit.TimeValue; import org.elasticsearch.index.query.BoolQueryBuilder; import org.elasticsearch.index.query.FilterBuilder; import org.elasticsearch.index.query.FilterBuilders; import org.elasticsearch.index.query.QueryBuilder; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.search.SearchHit; import org.overlord.commons.services.ServiceClose; import org.overlord.commons.services.ServiceInit; import org.overlord.rtgov.analytics.situation.Situation; import org.overlord.rtgov.analytics.situation.store.SituationStore; import org.overlord.rtgov.analytics.situation.store.SituationsQuery; import org.overlord.rtgov.analytics.situation.store.AbstractSituationStore; import org.overlord.rtgov.analytics.situation.store.ResolutionState; import org.overlord.rtgov.analytics.util.SituationUtil; import org.overlord.rtgov.common.elasticsearch.ElasticsearchClient; import org.overlord.rtgov.common.util.RTGovProperties; /** * This class provides the Elastcsearch based implementation of the SituationsStore * interface. * */ public class ElasticsearchSituationStore extends AbstractSituationStore implements SituationStore { private static final Logger LOG = Logger.getLogger(ElasticsearchSituationStore.class.getName()); private static String SITUATIONSTORE_UNIT_INDEX = "SituationStore.Elasticsearch.index"; private static String SITUATIONSTORE_UNIT_TYPE = "SituationStore.Elasticsearch.type"; private static String SITUATIONSTORE_RESPONSE_SIZE = "SituationStore.Elasticsearch.responseSize"; private static String SITUATIONSTORE_TIMEOUT = "SituationStore.Elasticsearch.timeout"; private static final int PROPERTY_VALUE_MAX_LENGTH = 250; private static int DEFAULT_RESPONSE_SIZE = 100000; private static long DEFAULT_TIMEOUT = 10000L; private int _responseSize; private long _timeout; private ElasticsearchClient _client=new ElasticsearchClient(); /** * Constructor. */ public ElasticsearchSituationStore() { } /** * Initialize the situation store. */ @ServiceInit public void init() { _client.setIndex(RTGovProperties.getProperty(SITUATIONSTORE_UNIT_INDEX, "rtgov")); _client.setType(RTGovProperties.getProperty(SITUATIONSTORE_UNIT_TYPE, "situation")); _responseSize = RTGovProperties.getPropertyAsInteger(SITUATIONSTORE_RESPONSE_SIZE, DEFAULT_RESPONSE_SIZE); _timeout = RTGovProperties.getPropertyAsLong(SITUATIONSTORE_TIMEOUT, DEFAULT_TIMEOUT); try { _client.init(); } catch (Exception e) { LOG.log(Level.SEVERE, java.util.PropertyResourceBundle .getBundle("situation-store-elasticsearch.Messages").getString("SITUATION-STORE-ELASTICSEARCH-1"), e); } } /** * This method sets the response size. * * @param size The size */ protected void setResponseSize(int size) { _responseSize = size; } /** * This method sets the response size. * * @return The size */ protected int getResponseSize() { return (_responseSize); } /** * {@inheritDoc} */ protected void doStore(final Situation situation) throws Exception { if (_client != null) { _client.add(situation.getId(), ElasticsearchClient.convertTypeToJson(situation)); } } /** * {@inheritDoc} */ protected Situation doGetSituation(final String id) { Situation ret=null; if (LOG.isLoggable(Level.FINEST)) { LOG.finest("Get situation: "+id); //$NON-NLS-1$ } if (_client != null) { String json=_client.get(id); if (json != null) { try { ret = SituationUtil.deserializeSituation(json.getBytes()); } catch (Exception e) { LOG.log(Level.SEVERE, java.util.PropertyResourceBundle .getBundle("situation-store-elasticsearch.Messages").getString("SITUATION-STORE-ELASTICSEARCH-2"), e); } } } if (LOG.isLoggable(Level.FINEST)) { LOG.finest("Situation="+ret); //$NON-NLS-1$ } return (ret); } /** * {@inheritDoc} */ public List<Situation> getSituations(final SituationsQuery sitQuery) { List<Situation> situations = new java.util.ArrayList<Situation>(); SearchResponse response=_client.getElasticsearchClient().prepareSearch(_client.getIndex()) .setTypes(_client.getType()) .setSearchType(SearchType.DFS_QUERY_THEN_FETCH) .setTimeout(TimeValue.timeValueMillis(_timeout)) .setSize(_responseSize) .setQuery(getQueryBuilder(sitQuery)) .execute().actionGet(); long num=response.getHits().getTotalHits(); if (num > _responseSize) { num = _responseSize; } for (int i=0; i < num; i++) { SearchHit hit=response.getHits().getAt(i); try { situations.add(SituationUtil.deserializeSituation(hit.getSourceAsString().getBytes())); } catch (Exception e) { LOG.log(Level.SEVERE, java.util.PropertyResourceBundle .getBundle("situation-store-elasticsearch.Messages").getString("SITUATION-STORE-ELASTICSEARCH-2"), e); } } if (LOG.isLoggable(Level.FINEST)) { LOG.finest("Situations="+situations); //$NON-NLS-1$ } return (situations); } protected QueryBuilder getQueryBuilder(SituationsQuery sitQuery) { QueryBuilder qb=QueryBuilders.matchAllQuery(); FilterBuilder filter=null; if (sitQuery != null) { BoolQueryBuilder bool=QueryBuilders.boolQuery(); if (!isNullOrEmpty(sitQuery.getResolutionState())) { if (sitQuery.getResolutionState().equalsIgnoreCase(ResolutionState.UNRESOLVED.name())) { filter = FilterBuilders.missingFilter("properties."+SituationStore.RESOLUTION_STATE_PROPERTY); } else if (sitQuery.getResolutionState().equalsIgnoreCase(ResolutionState.OPEN.name())) { bool.mustNot(QueryBuilders.matchQuery("properties."+SituationStore.RESOLUTION_STATE_PROPERTY, ResolutionState.RESOLVED.name())); } else { bool.must(QueryBuilders.matchQuery("properties."+SituationStore.RESOLUTION_STATE_PROPERTY, sitQuery.getResolutionState())); } } if (sitQuery.getProperties() != null && !sitQuery.getProperties().isEmpty()) { Set<Entry<Object,Object>> entrySet = sitQuery.getProperties().entrySet(); for (Entry<Object, Object> entry : entrySet) { Object key = entry.getKey(); Object value = entry.getValue(); if (value instanceof String) { bool.must(QueryBuilders.fuzzyLikeThisFieldQuery("properties."+key).likeText((String)value)); } else { bool.must(QueryBuilders.matchQuery("properties."+key, value)); } } } if (!isNullOrEmpty(sitQuery.getDescription())) { bool.must(QueryBuilders.fuzzyLikeThisFieldQuery("description").likeText(sitQuery.getDescription())); } if (!isNullOrEmpty(sitQuery.getSubject())) { bool.must(QueryBuilders.fuzzyLikeThisFieldQuery("subject").likeText(sitQuery.getSubject())); } if (!isNullOrEmpty(sitQuery.getType())) { bool.must(QueryBuilders.fuzzyLikeThisFieldQuery("type").likeText(sitQuery.getType())); } if (sitQuery.getSeverity() != null) { bool.must(QueryBuilders.matchQuery("severity", sitQuery.getSeverity().name())); } if (sitQuery.getFromTimestamp() > 0 || sitQuery.getToTimestamp() > 0) { long from=(sitQuery.getFromTimestamp() > 0 ? sitQuery.getFromTimestamp() : 0); long to=(sitQuery.getToTimestamp() > 0 ? sitQuery.getToTimestamp() : System.currentTimeMillis()+2000); bool.must(QueryBuilders.rangeQuery("timestamp").from(from).to(to)); } if (bool.hasClauses()) { qb = bool; } } if (filter != null) { return (QueryBuilders.filteredQuery(qb, filter)); } return (qb); } /** * Check if the supplied string is null or empty (after removing * whitespaces). * * @param str The string to test * @return Whether the supplied string is null or empty */ protected boolean isNullOrEmpty(String str) { return (str == null || str.trim().length() == 0); } /** * {@inheritDoc} */ public void assignSituation(final String situationId, final String userName) { Situation sit=getSituation(situationId); if (sit != null) { doAssignSituation(sit, userName); // Save the updated situation _client.update(situationId, ElasticsearchClient.convertTypeToJson(sit)); } } /** * {@inheritDoc} */ public void unassignSituation(final String situationId) { Situation sit=getSituation(situationId); if (sit != null) { doUnassignSituation(sit); // Save the updated situation _client.update(situationId, ElasticsearchClient.convertTypeToJson(sit)); } } /** * {@inheritDoc} */ public void updateResolutionState(final String situationId, final ResolutionState resolutionState) { Situation sit=getSituation(situationId); if (sit != null) { doUpdateResolutionState(sit, resolutionState); // Save the updated situation _client.update(situationId, ElasticsearchClient.convertTypeToJson(sit)); } } @Override public void recordSuccessfulResubmit(final String situationId, final String userName) { Situation sit=getSituation(situationId); if (sit != null) { doRecordSuccessfulResubmit(sit, userName); // Save the updated situation _client.update(situationId, ElasticsearchClient.convertTypeToJson(sit)); } } @Override public void recordResubmitFailure(final String situationId, final String errorMessage, final String userName) { Situation sit=getSituation(situationId); if (sit != null) { String message = (errorMessage == null ? "" : errorMessage); if (message.length() > PROPERTY_VALUE_MAX_LENGTH) { message = message.substring(0, PROPERTY_VALUE_MAX_LENGTH); } doRecordResubmitFailure(sit, message, userName); // Save the updated situation _client.update(situationId, ElasticsearchClient.convertTypeToJson(sit)); } } /** * This method deletes the supplied situation. * * @param situation The situation */ protected void doDelete(final Situation situation) { if (_client != null) { try { _client.remove(situation.getId()); } catch (Exception e) { throw new RuntimeException(e); } } } /** * This method returns the elasticsearch client. * * @return The client */ protected ElasticsearchClient getClient() { return (_client); } /** * Close the situation store. */ @ServiceClose public void close() { if (_client != null) { _client.close(); _client = null; } } }
package pers.student.dao; import pers.student.entity.Student; import java.sql.*; import java.util.ArrayList; import java.util.List; //数据访问层,原子性的增删改查 public class StudentDao { //数据库连接数据 private final String DRIVER = "com.mysql.cj.jdbc.Driver"; private final String DB = "javadb"; private final String USER = "java"; private final String PWD = "123456"; private final String URL = "jdbc:mysql://localhost:3306/"+DB+"?useUnicode = true&" + "characterEncoding = utf-8&useSSL = false&serverTimezone = GMT&allowPublicKeyRetrieval=true"; /** * 根据学号查询此人是否存在 * @param sno * @return */ public boolean isExit(String sno) { return queryStudentBySno(sno) != null; } /** * 根据学号查询学生 * @param sno * @return 返回一个学生对象 */ public Student queryStudentBySno(String sno) { Student student = null; Connection connection = null; PreparedStatement pstmt = null; ResultSet rs = null; try { Class.forName(DRIVER); connection = DriverManager.getConnection(URL, USER, PWD); String sql = "select * from stu where sno = ?"; pstmt = connection.prepareStatement(sql); pstmt.setString(1, sno); rs = pstmt.executeQuery(); if (rs.next()) { String no = rs.getString("sno"); String name = rs.getString("sname"); int age = rs.getInt("sage"); String address = rs.getString("saddress"); student = new Student(no, name, age, address); } return student; } catch (ClassNotFoundException e) { e.printStackTrace(); return null; } catch (SQLException e) { e.printStackTrace(); return null; } catch (Exception e) { e.printStackTrace(); return null; } finally { try { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); if (connection != null) connection.close(); } catch (SQLException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } /** * 查询所有学生数据 * @return */ public List<Student> queryAllStudent() { List<Student> studentList = new ArrayList<Student>(); Student student = null; Connection connection = null; PreparedStatement pstmt = null; ResultSet rs = null; try { Class.forName(DRIVER); connection = DriverManager.getConnection(URL, USER, PWD); String sql = "select * from stu"; pstmt = connection.prepareStatement(sql); rs = pstmt.executeQuery(); while (rs.next()) { String no = rs.getString("sno"); String name = rs.getString("sname"); int age = rs.getInt("sage"); String address = rs.getString("saddress"); student = new Student(no, name, age, address); studentList.add(student); } return studentList; } catch (ClassNotFoundException e) { e.printStackTrace(); return null; } catch (SQLException e) { e.printStackTrace(); return null; } catch (Exception e) { e.printStackTrace(); return null; } finally { try { if (rs != null) rs.close(); if (pstmt != null) pstmt.close(); if (connection != null) connection.close(); } catch (SQLException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } /** * 增加、插入学生 * @param student * @return 返回是否成功 */ public boolean addStudent(Student student) { Connection connection = null; PreparedStatement pstmt = null; try { Class.forName(DRIVER); connection = DriverManager.getConnection(URL, USER, PWD); String sql = "insert into stu values (?,?,?,?)"; pstmt = connection.prepareStatement(sql); pstmt.setString(1, student.getSno()); pstmt.setString(2, student.getSname()); pstmt.setInt(3, student.getAge()); pstmt.setString(4, student.getAddress()); int count = pstmt.executeUpdate(); return count > 0; } catch (ClassNotFoundException e) { e.printStackTrace(); return false; } catch (SQLException e) { e.printStackTrace(); return false; } catch (Exception e) { e.printStackTrace(); return false; } finally { try { if (pstmt != null) pstmt.close(); if (connection != null) connection.close(); } catch (SQLException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } /** * 根据学号删除 * @param sno * @return */ public boolean deleteStudentBySno(String sno) { Connection connection = null; PreparedStatement pstmt = null; try { Class.forName(DRIVER); connection = DriverManager.getConnection(URL, USER, PWD); String sql = "delete from stu where sno = ?"; pstmt = connection.prepareStatement(sql); pstmt.setString(1, sno); int count = pstmt.executeUpdate(); return count > 0; } catch (ClassNotFoundException e) { e.printStackTrace(); return false; } catch (SQLException e) { e.printStackTrace(); return false; } catch (Exception e) { e.printStackTrace(); return false; } finally { try { if (pstmt != null) pstmt.close(); if (connection != null) connection.close(); } catch (SQLException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } /** * 根据学号修改学生 * @param sno */ public boolean updateStudentBySno(String sno, Student student) { Connection connection = null; PreparedStatement pstmt = null; try { Class.forName(DRIVER); connection = DriverManager.getConnection(URL, USER, PWD); String sql = "update stu set sname = ?, sage = ?, saddress = ? where sno = ?"; pstmt = connection.prepareStatement(sql); //修改后内容 pstmt.setString(1, student.getSname()); pstmt.setInt(2, student.getAge()); pstmt.setString(3, student.getAddress()); pstmt.setString(4, sno); int count = pstmt.executeUpdate(); return count > 0; } catch (ClassNotFoundException e) { e.printStackTrace(); return false; } catch (SQLException e) { e.printStackTrace(); return false; } catch (Exception e) { e.printStackTrace(); return false; } finally { try { if (pstmt != null) pstmt.close(); if (connection != null) connection.close(); } catch (SQLException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } } }
package com.tdd; /** * Created by Sylvester on 3/4/2017. */ public class Dollar extends Money { private String currency; Dollar(int amount, String currency) { super(amount, currency); } //Money times(int multiplier) { // return Money.dollar(amount * multiplier); //} //Money times(int multiplier) { // return new Money(amount * multiplier, currency); //} String currency() { return "USD"; } }
package com.victoriachan.algorithmn; /** * @program: algorithm * @description: * 编写一个高效的算法来搜索 m x n 矩阵 matrix 中的一个目标值 target。该矩阵具有以下特性: * 每行的元素从左到右升序排列。 * 每列的元素从上到下升序排列。 * 示例: 现有矩阵 matrix 如下: * [ * [1, 4, 7, 11, 15], * [2, 5, 8, 12, 19], * [3, 6, 9, 16, 22], * [10, 13, 14, 17, 24], * [18, 21, 23, 26, 30] * ] * 给定 target = 5,返回 true。 * 给定 target = 20,返回 false。 * * @author: VictoriaChan * @create: 2020/03/11 23:52 **/ public class A1_SearchMatrix { public static void main(String[] args) { A1_SearchMatrix ASearchMatrix = new A1_SearchMatrix(); System.out.println(ASearchMatrix.searchMatrix(new int[][]{{1, 4, 7, 11, 15}, {2, 5, 8, 12, 19}, {3, 6, 9, 16, 22}, {10, 13, 14, 17, 24}, {18, 21, 23, 26, 30}}, 20)); } /** * 解题思路: * 二维数组是有规律的:右上角的数字是一列中最小的、一行中最大的,通过这个数字和 target 进行对比, * 可以将一行或者一列作为候选区域排出,那么 target 可能存在的范围缩小,最终得出结果。 * @param matrix * @param target * @return */ public boolean searchMatrix(int[][] matrix, int target) { if (matrix.length == 0) { return false; } int row = 0; int column = matrix[0].length - 1; while (row < matrix.length && column >= 0) { System.out.println(matrix[row][column]); if (target == matrix[row][column]) return true; else if (target < matrix[row][column]) column--; else row++; } return false; } }
package com.apri.test.service; import com.apri.test.entity.MataKuliah; import java.util.List; public interface MataKuliahService extends BaseService<MataKuliah>{ List<MataKuliah> findByMataKuliah(MataKuliah param); }
package com.tencent.mm.plugin.facedetect.ui; import android.os.Bundle; class FaceDetectPrepareUI$b { String Yy; int errCode; int errType; Bundle extras; final /* synthetic */ FaceDetectPrepareUI iRf; private FaceDetectPrepareUI$b(FaceDetectPrepareUI faceDetectPrepareUI) { this.iRf = faceDetectPrepareUI; } /* synthetic */ FaceDetectPrepareUI$b(FaceDetectPrepareUI faceDetectPrepareUI, byte b) { this(faceDetectPrepareUI); } }
package com.java.smart_garage.controllers.rest; import com.java.smart_garage.contracts.serviceContracts.EmailService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mail.javamail.JavaMailSender; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/smartgarage/sendemail") public class EmailController { private EmailService emailService; @Autowired private JavaMailSender mailSender; @PostMapping public String sendEmail() { //emailService.sendMailForCredentials(); return "Email sent successfully"; } }
package com.vilio.ppms.glob; /** * Created by dell on 2017/7/7. */ public class Fields { /* 当前系统编号 */ public final static String SYSTEM_NO = "ppms"; /* 参数传递消息,错误号字段 */ public final static String PARAM_MESSAGE_ERR_CODE = "returnCode"; /* 参数传递消息,错误信息 */ public final static String PARAM_MESSAGE_ERR_MESG = "returnMessage"; public final static String PARAM_MESSAGE_HEAD = "head"; /* 上游系统编码*/ public final static String PARAM_SOURCE_SYSTEM = "sourceSystem"; /* 接口功能号*/ public final static String PARAM_FUNCTION_NO = "functionNo"; public final static String PARAM_MESSAGE_BODY = "body"; }
package com.meridal.examples.recordcollection.domain.discogs; public class Track { private String duration; private String position; private String title; public String getDuration() { return duration; } public void setDuration(String duration) { this.duration = duration; } public String getPosition() { return position; } public void setPosition(String position) { this.position = position; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } @Override public String toString() { return this.position + " " + this.title + " " + this.duration; } }
package com.softwarica.drinknepal.Activities; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.os.Handler; import com.softwarica.drinknepal.R; public class DrinkSplash extends AppCompatActivity { SharedPreferences preferences; private SharedPreferences.Editor editor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_drink_splash); getSupportActionBar().hide(); preferences = getSharedPreferences("APP", MODE_PRIVATE); editor=preferences.edit(); String val=preferences.getString("token", ""); if(!val.isEmpty()){ // final Intent intent1=new Intent(this,ViewProduct.class); // startActivity(intent1); }else{ final Intent intent = new Intent(DrinkSplash.this, Login.class); new Handler().postDelayed(new Runnable() { @Override public void run() { startActivity(intent); } },5000); } } }
import java.util.Scanner; import java.math.BigInteger; // one comment public class Mission1_wrongOutput { public static void main(String[] args) { String text = "Ahhh my bits are showing"; String binary = new BigInteger(text.getBytes()).toString(2); System.out.println(binary); System.out.print("My favorite movie is Alan Turing"); } }
package eu.precode.TestApp.controllers; import eu.precode.TestApp.services.UsersService; import eu.precode.TestApp.models.User; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Page; import org.springframework.web.bind.annotation.*; import org.springframework.data.domain.Pageable; @RestController public class UsersController { @Autowired UsersService service; @GetMapping("/users") public Page<User> getUsers(Pageable pageable) { return service.getUsers(pageable); } @PostMapping("/users") public User create(@RequestBody User user) { return service.create(user); } @PostMapping("/addTestUser") public User addTestUser(@RequestBody User user){ return service.create(user); } }
package cb; //Program that shows the True False Boolean public class TrueFalseComparison { public static void main(String[] args) { int a=10; int b=20; System.out.println("The fact that a=b is "+(a==b)+" !!!"); System.out.println("The fact that a is different than b is "+(a!=b)+" !!!"); System.out.println("The fact that a>b is "+(a>b)+" !!!"); System.out.println("The fact that a<b is "+(a<b)+" !!!"); System.out.println("The fact that b>=a is "+(b>=a)+" !!!"); System.out.println("The fact that b<=a is "+(b<=a)+" !!!"); } }
package com.zilker.contact.beanClass; /* * Contact Bean. */ public class Contact_Detail { private String firstName, lastName, mailId; public Contact_Detail(String fName, String sName, String mId) { this.firstName = fName; this.lastName = sName; this.mailId = mId; } public void setFirstName(String fName) { this.firstName = fName; } public void setLastName(String sName) { this.lastName = sName; } public void setMailId(String mail) { this.mailId = mail; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public String getMail() { return mailId; } }
package com.research.cep; import org.apache.flink.streaming.api.functions.AssignerWithPeriodicWatermarks; import org.apache.flink.streaming.api.watermark.Watermark; import javax.annotation.Nullable; /** * @fileName: Watermarks.java * @description: Watermarks.java类说明 * @author: by echo huang * @date: 2020-04-03 11:37 */ public class Watermarks implements AssignerWithPeriodicWatermarks<Event> { /** * 最大延迟时间 */ private final long maxOutOfOrderness = 350000; /** * 当前最大时间 */ private long currentMaxTimestamp; @Nullable @Override public Watermark getCurrentWatermark() { //获得当前水印为当前最大时间减去最大延迟时间 return new Watermark(currentMaxTimestamp - maxOutOfOrderness); } /** * 抽取timestamp * * @param element * @param previousElementTimestamp * @return */ @Override public long extractTimestamp(Event element, long previousElementTimestamp) { long time = System.currentTimeMillis(); currentMaxTimestamp = Math.max(time, currentMaxTimestamp); return time; } }
package com.warehouse.mapper; import com.warehouse.entity.InStockMasterEntity; import java.util.List; import java.util.Map; public interface InStockMasterMapper { List<InStockMasterEntity> findList(Map<String, Object> params); InStockMasterEntity findInfo(Map<String, Object> params); Integer doInsert(InStockMasterEntity inStockMasterEntity); Integer doUpdate(InStockMasterEntity inStockMasterEntity); Integer doDelete(int inStockId); }
package com.tencent.mm.plugin.aa.a.c; import com.tencent.mm.plugin.aa.a.a; import com.tencent.mm.protocal.c.o; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.vending.g.g; import com.tencent.mm.vending.h.e; public class g$a implements e<o, Long> { final /* synthetic */ g eBH; public g$a(g gVar) { this.eBH = gVar; } public final /* synthetic */ Object call(Object obj) { Long l = (Long) obj; f fVar = this.eBH.eBA; long longValue = l.longValue(); String stringExtra = fVar.uPN.getStringExtra("bill_no"); String stringExtra2 = fVar.uPN.getStringExtra("chatroom"); int i = fVar.uPN.getIntExtra("enter_scene", 0) == 1 ? a.ezU : a.ezV; x.i("MicroMsg.PaylistAAInteractor", "aaPay, payAmount: %s, billNo: %s, chatroom: %s", new Object[]{Long.valueOf(longValue), stringExtra, stringExtra2}); g.a(g.a(stringExtra, Long.valueOf(longValue), Integer.valueOf(i), stringExtra2).c(fVar.eBx.eAs)); return null; } public final String xr() { return "Vending.LOGIC"; } }
package gr.athena.innovation.fagi.core.similarity; import gr.athena.innovation.fagi.specification.SpecificationConstants; import java.math.BigDecimal; import java.math.RoundingMode; import org.apache.commons.text.similarity.JaroWinklerDistance; /** * Class for computing the Jaro-Winkler Distance. * * @author nkarag */ public final class JaroWinkler { /** * Computes the Jaro Winkler Distance which indicates the similarity score between two strings. * <a href="http://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance"> * http://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance</a>. * * @param a The first string. * @param b The second string. * @return The distance. Range is between [0,1]. */ public static double computeSimilarity(String a, String b){ //The class is named Distance, but it returns similarity score. //TODO: check issue progress at https://issues.apache.org/jira/browse/TEXT-104 for any change JaroWinklerDistance jaroWinkler = new JaroWinklerDistance(); double result = jaroWinkler.apply(a, b); if(result > SpecificationConstants.Similarity.SIMILARITY_MAX){ return 1; } else if(result < SpecificationConstants.Similarity.SIMILARITY_MIN){ return 0; } else { double roundedResult = new BigDecimal(result). setScale(SpecificationConstants.Similarity.ROUND_DECIMALS_3, RoundingMode.HALF_UP).doubleValue(); return roundedResult; } } /** * Computes the Jaro Winkler Distance using the complement of * {@link gr.athena.innovation.fagi.core.similarity.JaroWinkler#computeSimilarity(String, String) computeSimilarity}. * <a href="http://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance"> * http://en.wikipedia.org/wiki/Jaro%E2%80%93Winkler_distance</a>. * * @param a The first string. * @param b The second string. * @return The distance. Range is between [0,1]. */ public static double computeDistance(String a, String b){ return 1 - computeSimilarity(a,b); } }
package com.duanxr.yith.midium; /** * @author 段然 2021/3/12 */ public class BaZiFuChuanZhuanHuanChengZhengShuLcof { /** * English description is not available for the problem. * * 写一个函数 StrToInt,实现把字符串转换成整数这个功能。不能使用 atoi 或者其他类似的库函数。 * *   * * 首先,该函数会根据需要丢弃无用的开头空格字符,直到寻找到第一个非空格的字符为止。 * * 当我们寻找到的第一个非空字符为正或者负号时,则将该符号与之后面尽可能多的连续数字组合起来,作为该整数的正负号;假如第一个非空字符是数字,则直接将其与之后连续的数字字符组合起来,形成整数。 * * 该字符串除了有效的整数部分之后也可能会存在多余的字符,这些字符可以被忽略,它们对于函数不应该造成影响。 * * 注意:假如该字符串中的第一个非空格字符不是一个有效整数字符、字符串为空或字符串仅包含空白字符时,则你的函数不需要进行转换。 * * 在任何情况下,若函数不能进行有效的转换时,请返回 0。 * * 说明: * * 假设我们的环境只能存储 32 位大小的有符号整数,那么其数值范围为 [−231,  231 − 1]。如果数值超过这个范围,请返回  INT_MAX (231 − 1) 或 INT_MIN (−231) 。 * * 示例 1: * * 输入: "42" * 输出: 42 * 示例 2: * * 输入: " -42" * 输出: -42 * 解释: 第一个非空白字符为 '-', 它是一个负号。 *   我们尽可能将负号与后面所有连续出现的数字组合起来,最后得到 -42 。 * 示例 3: * * 输入: "4193 with words" * 输出: 4193 * 解释: 转换截止于数字 '3' ,因为它的下一个字符不为数字。 * 示例 4: * * 输入: "words and 987" * 输出: 0 * 解释: 第一个非空字符是 'w', 但它不是数字或正、负号。 * 因此无法执行有效的转换。 * 示例 5: * * 输入: "-91283472332" * 输出: -2147483648 * 解释: 数字 "-91283472332" 超过 32 位有符号整数范围。 *   因此返回 INT_MIN (−231) 。 *   * * 注意:本题与主站 8 题相同:https://leetcode-cn.com/problems/string-to-integer-atoi/ * */ class Solution { public int strToInt(String str) { int n = 0; int overFlowCheck = Integer.MAX_VALUE / 10; boolean negative = false; boolean hasPS = false; boolean hasCount = false; char[] chars = str.toCharArray(); for (int i = 0; i < chars.length; i++) { char c = chars[i]; if (c == ' ') { if (hasCount) { break; } continue; } if (c == '-' || c == '+') { if (hasPS || hasCount) { break; } hasCount = true; hasPS = true; negative = c == '-'; continue; } if (c < '0' || c > '9') { break; } hasCount = true; int num = c - '0'; if ((n > overFlowCheck) || (n == overFlowCheck && num >= 7) || (n < -overFlowCheck) || ( n == -overFlowCheck && num >= 8)) { return negative ? Integer.MIN_VALUE : Integer.MAX_VALUE; } n *= 10; if (negative) { n -= num; } else { n += num; } } return n; } } }
package com.koreait.model.member; 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; import com.koreait.dao.MDao; import com.koreait.dto.MemberDto; @WebServlet("/ajaxSearchId.me") public class AjaxSearchId extends HttpServlet { private static final long serialVersionUID = 1L; public AjaxSearchId() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 1. 전달 받은 파라미터 처리( data: "mEmail=" + $("mEmail").val(), ) request.setCharacterEncoding("utf-8"); String mEmail = request.getParameter("mEmail"); // 2. MDao 생성 MDao mDao = MDao.getInstance(); // 3. MDao 의 getMemberBymEmail() 메소드 호출 MemberDto mDto = mDao.getMemberBymEmail(mEmail); //4. 결과 String result = null; if(mDto == null) { result = "NO"; }else { result = mDto.getmId(); } // 5. result 를 응답 response.setContentType("text/html; charset=utf-8"); PrintWriter out = response.getWriter(); out.println(result); // result 가 $.ajax ({,,, success(data)}) 의 data 로 전달 ~ } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
package com.feelyou.manager; import android.app.Dialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import com.feelyou.R; import com.feelyou.receiver.CallReceiver; import com.feelyou.util.DialogUtil; import com.feelyou.util.SystemUtil; public class CallManager { public static void call(Context context, String phoneNo, boolean isDirectCall) { Dialog dialog = null; if (!isDirectCall) { String msg = SystemUtil.getString(context, R.string.call_service_notify_waitcall); dialog = DialogUtil.showProgressDialog(context, msg); dialog.show(); } else { new NotifyManager(context).notifyWaitCall(); } BroadcastReceiver broadcastReceiver = CallReceiver.registerCallReceiver(context, dialog); Intent intent = new Intent("skymeetingcall"); intent.putExtra("phone", phoneNo); intent.putExtra("isDirectCall", isDirectCall); context.startService(intent); } }
import textio.TextIO; /* * This program will take a line inputted by the user and will print out 25 * characters for each character in the line. For example, if the input is "boy" * then there will be 25 characters of the letter 'b', 25 characters of the letter 'o', * and 25 letters of the character 'y'. */ public class StringRepeaterMethods { /* * Preconditions: User must be able to input a line of text. * Postconditions: This main method will take a line of text from the user, then will run * the printLineOfText method. The method will then ask the user if they would like to run * the program again. */ public static void main (String [] args) { String line; boolean tryAgain; System.out.println ("This program will print out 25 characters for each character of any line of text of your choosing."); do { System.out.println ("Please enter a line of text."); line = TextIO.getln (); printLineOfText (line); System.out.println ("Do you want to try again?"); tryAgain = TextIO.getBoolean (); } while (tryAgain == true); System.out.println ("Goodbye."); System.out.println (); } /* * Preconditions: Must have received the line parameter from the main method. * Postconditions: This method will take the line parameter and reprint it with 25 characters * per inputted character. */ private static void printLineOfText (String line) { int i; for (i = 0; i < line.length (); i ++) { printTwentyFiveCharacters (line.charAt (i), 25); } } /* * Preconditions: This method relies on printLineOfText where that method must currently be on a character. * Postconditions: This method will print out 25 copies of whatever character printLineOfText is currently at. */ private static void printTwentyFiveCharacters (char ch, int n) { int i; for (i = 0; i < n; i ++) { System.out.print (ch); } } }
package cs455.deleter; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.apache.hadoop.mapreduce.lib.input.FileInputFormat; import org.apache.hadoop.mapreduce.lib.input.TextInputFormat; import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat; import org.apache.hadoop.mapreduce.lib.output.TextOutputFormat; public class Deleter { public static void main(String[] args) throws Exception { if (args.length <= 2) { DeleteMapper.setSentence("It was a dark rock and stormy night"); } else { DeleteMapper.setSentence(args[2]); } // Create a new job Configuration jobConf = new Configuration(); Job deletion = Job.getInstance(jobConf); deletion.setInputFormatClass(TextInputFormat.class); deletion.setOutputFormatClass(TextOutputFormat.class); deletion.setOutputKeyClass(Text.class); deletion.setOutputValueClass(Text.class); deletion.setJarByClass(Deleter.class); deletion.setJobName("Deleter"); deletion.setMapperClass(DeleteMapper.class); deletion.setReducerClass(DeleteReducer.class); FileInputFormat.addInputPath(deletion, new Path(args[0])); FileOutputFormat.setOutputPath(deletion, new Path(args[1])); // Submit the job, poll for progress until it completes deletion.waitForCompletion(true); } }
package com.order.classes; import org.bson.types.ObjectId; public class Order{ public String recipientName; public String streetAddress; public String city; public String state; public String zipCode; public String phoneNumber; public String product; public String quantity; public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getRecipientName() { return recipientName; } public void setRecipientName(String recipientName) { this.recipientName = recipientName; } public String getStreetAddress() { return streetAddress; } public void setStreetAddress(String streetAddress) { this.streetAddress = streetAddress; } public String getZipCode() { return zipCode; } public void setZipCode(String zipCode) { this.zipCode = zipCode; } public String getPhoneNumber() { return phoneNumber; } public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber; } public String getProduct() { return product; } public void setProduct(String product) { this.product = product; } public String getQuantity() { return quantity; } public void setQuantity(String quantity) { this.quantity = quantity; } public String toString(){ return recipientName + " " + streetAddress + " " + city + " " + state + " " + zipCode + " " + phoneNumber + " " + product + " " + quantity; } }
package Folha_De_Pagamento_Brenne; import java.util.Calendar; public class Data { Calendar dataLimite; public void setdata(String data) { String[] arrayData = data.split("/"); int[] arrayDiaEMes = new int[2]; arrayDiaEMes[0] = Integer.valueOf(arrayData[0]); arrayDiaEMes[1] = Integer.valueOf(arrayData[1]); this.dataLimite = Calendar.getInstance(); this.dataLimite.set(Calendar.DAY_OF_MONTH, arrayDiaEMes[0]); this.dataLimite.set(Calendar.MONTH, arrayDiaEMes[1]); } @Override public String toString() { return this.dataLimite.get(Calendar.DAY_OF_MONTH) + "/" + this.dataLimite.get(Calendar.MONTH); } Data(String data){ setdata(data); } }
/* * This software is licensed under the MIT License * https://github.com/GStefanowich/MC-Server-Protection * * Copyright (c) 2019 Gregory Stefanowich * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package net.theelm.sewingmachine.chat.config; import net.theelm.sewingmachine.chat.objects.ChatFormat; import net.theelm.sewingmachine.config.ConfigOption; /** * Created on Jun 08 2023 at 8:31 PM. * By greg in sewingmachine */ public final class SewChatConfig { private SewChatConfig() {} /* * Naming */ public static final ConfigOption<Boolean> DO_PLAYER_NICKS = ConfigOption.json("player.nicks", true); public static final ConfigOption<Integer> NICKNAME_COST = ConfigOption.json("player.nick_cost", 0); /* * Chat Booleans */ public static final ConfigOption<Boolean> CHAT_MODIFY = ConfigOption.json("chat.modify", true); public static final ConfigOption<Boolean> CHAT_SHOW_TOWNS = ConfigOption.json("chat.show_towns", true); public static final ConfigOption<ChatFormat> CHAT_WHISPER_FORMAT = ConfigChatOption.chat("chat.formatting.whisper", "&7&o[Whisper] ${nick}&r&o: ${message}"); public static final ConfigOption<ChatFormat> CHAT_GLOBAL_FORMAT = ConfigChatOption.chat("chat.formatting.global", "[${world}] &b${nick}&r: ${message}"); public static final ConfigOption<ChatFormat> CHAT_LOCAL_FORMAT = ConfigChatOption.chat("chat.formatting.local", "&9[Local] &b${nick}&r: ${message}"); public static final ConfigOption<ChatFormat> CHAT_TOWN_FORMAT = ConfigChatOption.chat("chat.formatting.town", "&a[${town}] &2${nick}&r: ${message}"); //public static final ConfigOption<ChatFormat> CHAT_SERVER_FORMAT = SewConfig.addConfig(ConfigOption.chat("chat.formatting.server", "&7Server&r: ${message}")); public static final ConfigOption<Boolean> CHAT_MUTE_SELF = ConfigOption.json("chat.mute.personal_mute", true); public static final ConfigOption<Boolean> CHAT_MUTE_OP = ConfigOption.json("chat.mute.moderator_mute", true); }
/* * 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 DAL; import DTO.dto_LopHoc; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; /** * * @author ThinkPro */ public class dal_LopHoc extends DBConnect { public ArrayList<dto_LopHoc> layDsLop(int trangThai) { ArrayList<dto_LopHoc> dsLop = new ArrayList<dto_LopHoc>(); dto_LopHoc lop = null; String sql = ""; if (trangThai == 0) { sql = "SELECT ma_lop, lop.ma_ct, ma_nv, ten_lop, ngay_bd, ngay_kt, gv, phong, lop.trang_thai,chuong_trinh.ten_ct " + "FROM lop, chuong_trinh " + "WHERE lop.ma_ct = chuong_trinh.ma_ct AND lop.trang_thai = 1"; } else if (trangThai == 1) { sql = "SELECT ma_lop, lop.ma_ct, ma_nv, ten_lop, ngay_bd, ngay_kt, gv, phong, lop.trang_thai,chuong_trinh.ten_ct " + "FROM lop, chuong_trinh " + "WHERE lop.ma_ct = chuong_trinh.ma_ct " + "ORDER BY lop.trang_thai DESC"; } try { PreparedStatement preStmt = conn.prepareStatement(sql); ResultSet rs = preStmt.executeQuery(); while (rs.next()) { lop = new dto_LopHoc(); lop.setMaLop(rs.getInt(1)); lop.setMaCT(rs.getInt(2)); lop.setMaNV(rs.getInt(3)); lop.setTenLop(rs.getString(4)); lop.setNgayBD(rs.getDate(5)); lop.setNgayKT(rs.getDate(6)); lop.setGiaoVien(rs.getString(7)); lop.setPhong(rs.getString(8)); lop.setTrangThai(rs.getInt(9)); //lop.setTenCt(rs.getString(10)); dsLop.add(lop); } conn.close(); return dsLop; } catch (Exception ex) { ex.printStackTrace(); return dsLop; } } }
package IDecoratorSimple; public class DecoratorTest { public static void main(String[] args) { ConcreteComponent concreteComponent = new ConcreteComponent(); concreteComponent.print("Test"); System.out.println(); ConcreteDecoratorLeftBracket concreteDecoratorLeftBracket = new ConcreteDecoratorLeftBracket(concreteComponent); concreteDecoratorLeftBracket.print("Test"); System.out.println(); ConcreteDecoratorRightBracket concreteDecoratorRightBracket = new ConcreteDecoratorRightBracket(concreteDecoratorLeftBracket); concreteDecoratorRightBracket.print("Test"); System.out.println(); ConcreteDecoratorQuotes concreteDecoratorQuotes = new ConcreteDecoratorQuotes(concreteDecoratorRightBracket); concreteDecoratorQuotes.print("Test"); System.out.println(); new ConcreteDecoratorQuotes( new ConcreteDecoratorRightBracket( new ConcreteDecoratorLeftBracket( new ConcreteComponent() ) ) ).print("Test2"); System.out.println(); new ConcreteDecoratorQuotes( new ConcreteDecoratorLeftBracket( new ConcreteDecoratorRightBracket( new ConcreteComponent() ) ) ).print("Test3"); System.out.println(); new ConcreteDecoratorLeftBracket( new ConcreteDecoratorRightBracket( new ConcreteDecoratorQuotes( new ConcreteComponent() ) ) ).print("Test5"); System.out.println(); } }
package com.jayqqaa12.abase.exception; public class AbaseException extends RuntimeException { private static final long serialVersionUID = 1L; public AbaseException() { super(); } public AbaseException(String msg) { super(msg); } public AbaseException(Throwable ex) { super(ex); } public AbaseException(String msg,Throwable ex) { super(msg,ex); } }
package com.krokodillLl.degree.controllers; import com.krokodillLl.degree.service.ConnectionService; import com.krokodillLl.degree.service.Utils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.event.EventListener; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import org.springframework.web.socket.messaging.SessionDisconnectEvent; import javax.servlet.http.HttpServletRequest; import java.util.Set; @RestController @RequestMapping("/degree") public class ConnectionController { @Autowired private ConnectionService connectionService; @PostMapping("/user-connect") public ResponseEntity<String> connectUser(HttpServletRequest request, @RequestBody String username) { return connectionService.connectUser(request, username); } @PostMapping("/user-disconnect") public ResponseEntity<String> disconnectUser(@RequestBody String username) { return connectionService.disconnectUser(username); } @GetMapping("/active-users") public Set<String> getUsers() { return connectionService.getUsers(); } @GetMapping("/stickers") public Set<String> getStickers() { return Utils.getStickers(); } @EventListener public void handleWebSocketDisconnectListener(SessionDisconnectEvent event) { connectionService.disconnectUser(event); } }
package com.tencent.mm.plugin.label.ui; import android.view.View; import android.view.View.OnClickListener; class ContactLabelManagerUI$6 implements OnClickListener { final /* synthetic */ ContactLabelManagerUI kBk; ContactLabelManagerUI$6(ContactLabelManagerUI contactLabelManagerUI) { this.kBk = contactLabelManagerUI; } public final void onClick(View view) { ContactLabelManagerUI.b(this.kBk); } }
package firemage.dynfx.shape; import javafx.scene.paint.Paint; import org.dyn4j.geometry.Triangle; import org.dyn4j.geometry.Vector2; public class FXTriangle extends FXPolygonBase { public FXTriangle(Vector2 point1, Vector2 point2, Vector2 point3, Paint paint) { super(new Triangle(point1, point2, point3), paint); } public FXTriangle(Vector2 point1, Vector2 point2, Vector2 point3, Paint paint, Paint outlinePaint) { super(new Triangle(point1, point2, point3), paint, outlinePaint); } }
package org.alienideology.jcord.internal.object.client; import org.alienideology.jcord.handle.client.IClient; import org.alienideology.jcord.handle.client.IClientObject; import org.alienideology.jcord.internal.object.DiscordObject; /** * @author AlienIdeology */ public class ClientObject extends DiscordObject implements IClientObject { private Client client; public ClientObject(IClient client) { super(client == null ? null : client.getIdentity()); this.client = (Client) client; } @Override public Client getClient() { return client; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof IClientObject)) return false; if (!super.equals(o)) return false; IClientObject that = (IClientObject) o; return client.equals(that.getClient()); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + client.hashCode(); return result; } }
package com.gmail.volodymyrdotsenko.cms.fe.vaadin.views; import java.io.File; import java.io.FileOutputStream; import java.io.OutputStream; import com.vaadin.server.Page; import com.vaadin.ui.Button; import com.vaadin.ui.Button.ClickEvent; import com.vaadin.ui.FormLayout; import com.vaadin.ui.HorizontalLayout; import com.vaadin.ui.Label; import com.vaadin.ui.Notification; import com.vaadin.ui.ProgressBar; import com.vaadin.ui.UI; import com.vaadin.ui.Upload; import com.vaadin.ui.Upload.FailedEvent; import com.vaadin.ui.Upload.FinishedEvent; import com.vaadin.ui.Upload.Receiver; import com.vaadin.ui.Upload.StartedEvent; import com.vaadin.ui.Upload.StartedListener; import com.vaadin.ui.Upload.SucceededEvent; import com.vaadin.ui.VerticalLayout; import com.vaadin.ui.Window; public class UploadProgressView extends VerticalLayout { private static final long serialVersionUID = 1L; private final Upload upload; public UploadProgressView(SuccessHandler sh) { Receiver receiver = new ReceiverImpl(); upload = new Upload(null, receiver); final UploadInfoWindow uploadInfoWindow = new UploadInfoWindow(upload, receiver, sh); upload.setImmediate(true); upload.setButtonCaption("Upload"); upload.addStartedListener(new StartedListener() { private static final long serialVersionUID = 1L; @Override public void uploadStarted(final StartedEvent event) { if (isEmpty(event.getFilename())) { new Notification("Choose file, firstly", Notification.Type.ERROR_MESSAGE).show(Page.getCurrent()); return; } if (uploadInfoWindow.getParent() == null) { UI.getCurrent().addWindow(uploadInfoWindow); } uploadInfoWindow.setClosable(false); } }); upload.addFinishedListener(new Upload.FinishedListener() { private static final long serialVersionUID = 1L; @Override public void uploadFinished(final FinishedEvent event) { uploadInfoWindow.setClosable(true); } }); // upload.addChangeListener(new ChangeListener() { // // private static final long serialVersionUID = 1L; // // @Override // public void filenameChanged(ChangeEvent event) { // if (!isEmpty(event.getFilename())) // upload.setButtonCaption("Upload"); // } // }); addComponent(upload); } // @StyleSheet("uploadexample.css") private static class UploadInfoWindow extends Window implements Upload.StartedListener, Upload.ProgressListener, Upload.FailedListener, Upload.SucceededListener, Upload.FinishedListener { private static final long serialVersionUID = 1L; private final Label state = new Label(); private final Label fileName = new Label(); private final Label textualProgress = new Label(); private final SuccessHandler sh; private final Receiver receiver; private final ProgressBar progressBar = new ProgressBar(); private final Button cancelButton; public UploadInfoWindow(final Upload upload, final Receiver receiver, final SuccessHandler sh) { super("Status"); this.sh = sh; this.receiver = receiver; setWidth(350, Unit.PIXELS); addStyleName("upload-info"); setResizable(true); setDraggable(true); final FormLayout l = new FormLayout(); setContent(l); l.setMargin(true); final HorizontalLayout stateLayout = new HorizontalLayout(); stateLayout.setSpacing(true); stateLayout.addComponent(state); cancelButton = new Button("Cancel"); cancelButton.addClickListener(new Button.ClickListener() { private static final long serialVersionUID = 1L; @Override public void buttonClick(final ClickEvent event) { upload.interruptUpload(); } }); cancelButton.setVisible(false); cancelButton.setStyleName("small"); stateLayout.addComponent(cancelButton); stateLayout.setCaption("Current state"); state.setValue("Idle"); l.addComponent(stateLayout); fileName.setCaption("File name"); l.addComponent(fileName); progressBar.setCaption("Progress"); progressBar.setVisible(false); l.addComponent(progressBar); textualProgress.setVisible(false); l.addComponent(textualProgress); upload.addStartedListener(this); upload.addProgressListener(this); upload.addFailedListener(this); upload.addSucceededListener(this); upload.addFinishedListener(this); } @Override public void uploadFinished(final FinishedEvent event) { if (isEmpty(event.getFilename())) return; state.setValue("Idle"); progressBar.setVisible(false); textualProgress.setVisible(false); cancelButton.setVisible(false); } @Override public void uploadStarted(final StartedEvent event) { if (isEmpty(event.getFilename())) return; // this method gets called immediately after upload is started progressBar.setValue(0f); progressBar.setVisible(true); UI.getCurrent().setPollInterval(500); textualProgress.setVisible(true); // updates to client state.setValue("Uploading"); fileName.setValue(event.getFilename()); cancelButton.setVisible(true); } @Override public void updateProgress(final long readBytes, final long contentLength) { // this method gets called several times during the update progressBar.setValue(new Float(readBytes / (float) contentLength)); textualProgress.setValue("Processed " + readBytes + " bytes of " + contentLength); // result.setValue(counter.getLineBreakCount() + " (counting...)"); } @Override public void uploadSucceeded(final SucceededEvent event) { new Notification("File loaded successful ", Notification.Type.HUMANIZED_MESSAGE).show(Page.getCurrent()); event.getMIMEType(); sh.fireLoadingSuccessEvent(event.getFilename(), event.getMIMEType(), event.getLength(), ((ReceiverImpl) receiver).getFile()); } @Override public void uploadFailed(final FailedEvent event) { if (isEmpty(event.getFilename())) return; new Notification("File loading is failed", Notification.Type.ERROR_MESSAGE).show(Page.getCurrent()); } } private static class ReceiverImpl implements Receiver { private static final long serialVersionUID = 1L; private File file; @Override public OutputStream receiveUpload(final String fileName, final String MIMEType) { if (!isEmpty(fileName)) { // Create upload stream FileOutputStream fos = null; // Stream to write to try { // Open the file for writing. file = new File("/tmp/" + fileName); fos = new FileOutputStream(file); } catch (final java.io.FileNotFoundException e) { new Notification("Could not open file<br/>", e.getMessage(), Notification.Type.ERROR_MESSAGE) .show(Page.getCurrent()); return null; } return fos; // Return the output stream to write to } return null; } public File getFile() { return file; } } public interface SuccessHandler { void fireLoadingSuccessEvent(String fileName, String MIMEType, long fileLength, File file); } private static boolean isEmpty(String s) { return s == null || s.isEmpty(); } }
package com.xiaoxiao.contorller.backend; import com.xiaoxiao.pojo.XiaoxiaoLabels; import com.xiaoxiao.service.backend.LabelFeignService; import com.xiaoxiao.utils.Result; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.*; /** * _ooOoo_ * o8888888o * 88" . "88 * (| -_- |) * O\ = /O * ____/`---'\____ * .' \\| |// `. * / \\||| : |||// \ * / _||||| -:- |||||- \ * | | \\\ - /// | | * | \_| ''\---/'' | | * \ .-\__ `-` ___/-. / * ___`. .' /--.--\ `. . __ * ."" '< `.___\_<|>_/___.' >'"". * | | : `- \`.;`\ _ /`;.`/ - ` : | | * \ \ `-. \_ __\ /__ _/ .-` / / * ======`-.____`-.___\_____/___.-`____.-'====== * `=---=' * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ * 佛祖保佑 永无BUG * 佛曰: * 写字楼里写字间,写字间里程序员; * 程序人员写程序,又拿程序换酒钱。 * 酒醒只在网上坐,酒醉还来网下眠; * 酒醉酒醒日复日,网上网下年复年。 * 但愿老死电脑间,不愿鞠躬老板前; * 奔驰宝马贵者趣,公交自行程序员。 * 别人笑我忒疯癫,我笑自己命太贱; * 不见满街漂亮妹,哪个归得程序员? * * @project_name:xiaoxiao_final_blogs * @date:2019/11/29:11:03 * @author:shinelon * @Describe: */ @RestController @RequestMapping(value = "/admin/label") @CrossOrigin public class LabelController { @Autowired private LabelFeignService labelFeignService; /** * 查询全部的标签 * @param page * @param rows * @return */ @GetMapping(value = "/find_all_label") public Result findAllLabel(@RequestParam(name = "page",defaultValue = "1",required = false) Integer page, @RequestParam(name = "rows",defaultValue = "10",required = false) Integer rows){ return this.labelFeignService.findAllLabel(page, rows); } @PostMapping(value = "/update") public Result update(XiaoxiaoLabels labels){ return this.labelFeignService.update(labels); } @GetMapping(value = "/find_label_by_id") public Result findLabelById(Long labelId){ return this.labelFeignService.findLabelById(labelId); } @GetMapping(value = "/delete") public Result delete(Long labelId){ return this.labelFeignService.delete(labelId); } @PostMapping(value = "/insert") public Result insert(XiaoxiaoLabels labels){ return this.labelFeignService.insert(labels); } }
package pt.ist.sonet; import pt.ist.sonet.domain.ExternalServiceConfig; import pt.ist.sonet.domain.Sonet; import pt.ist.sonet.factory.ExternalServiceFactory; import pt.ist.sonet.factory.LocalExternalServiceFactory; import pt.ist.sonet.factory.RemoteExternalServiceFactory; import pt.ist.fenixframework.Config; import pt.ist.fenixframework.FenixFramework; public class DataBaseBootstrap { private static boolean notInitialized = true; public synchronized static void init(String serverType) { if (notInitialized) { FenixFramework.initialize(new Config() {{ domainModelPath = "src/main/dml/domain.dml"; dbAlias = "//localhost:3306/sonetdb"; dbUsername = "sonet"; dbPassword = "s0n3t"; rootClass = Sonet.class; }}); } if(serverType.contains("ES+SD")){ ExternalServiceFactory remoteFactory = new RemoteExternalServiceFactory(); ExternalServiceConfig.setFactory(remoteFactory); } else { ExternalServiceFactory localFactory = new LocalExternalServiceFactory(); ExternalServiceConfig.setFactory(localFactory); } notInitialized = false; } public static void setup() { try { pt.ist.sonet.SonetSetup.populateDomain(); } catch (pt.ist.sonet.exception.SonetException ex) { System.out.println("Error while populating sonet application: " + ex); } } }
package com.example.markus.todoregister.data; import android.util.Log; import java.util.Date; /** * Created by Markus on 7.4.2017. * Task which has been given a specific time frame to complete * if the time goes to zero, the tasks will show an alert * and then delete itself after some time */ public class TimedTask extends Task { private String currentDate; private String endDate; private int timeLeftDays; private int timeLeftHours; @SuppressWarnings("unused") public TimedTask(String title, String content, int priority, Date endDate) { super(title, content, priority); this.currentDate = getDate(); //this.endDate = getDate(endDate); } //integer so don't need to worry about rounding @SuppressWarnings("unused") public void getTimeLeftDays() { Log.d("date: ", currentDate); //TODO: From currentDate remove endDate and the time left! } //integer so don't need to worry about rounding @SuppressWarnings("unused") public void getTimeLeftHours() { //TODO: From currentDate remove endDate and the time left! } //Update the current date each time user refreshes the app @SuppressWarnings("unused") public void updateDate() { getDate(); } }
package org.sero.cash.superzk.json; import org.sero.cash.superzk.crypto.ecc.Point; import org.sero.cash.superzk.protocol.AccountType; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.databind.module.SimpleModule; public class JSON { private static ObjectMapper mapper; static { mapper = new ObjectMapper(); mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS); SimpleModule module = new SimpleModule(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); module.addSerializer(byte[].class, new BytesSerializer()); module.addSerializer(HexType.class, new HexTypeSerializer()); module.addDeserializer(byte[].class, new BytesDeserializer()); module.addDeserializer(AccountType.PKr.class, new PKrDeserializer()); module.addDeserializer(AccountType.SK.class, new SKDeserializer()); module.addDeserializer(Point.class, new PointDeserializer()); mapper.registerModule(module); } public static <T> String toJson(T t) throws JsonProcessingException { return mapper.writeValueAsString(t); } public static <T> T fromJson(String json, Class<T> clazz) throws JsonProcessingException { return mapper.readValue(json, clazz); } public static <T> T fromJson(String json, Class<?> listType, Class<?> beanType) throws JsonProcessingException { JavaType clazz = mapper.getTypeFactory().constructParametricType(listType, beanType); return mapper.readValue(json, clazz); } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; import javax.swing.JOptionPane; import jdbc.Conectar; import model.Fornecedores; import model.Produtos; /** * * @author Rafael */ public class ProdutosDAO { private Connection conexao; //objeto que o banco de dados guarda com o Connection é somente chamar o objeto do tipo conexao public ProdutosDAO() { this.conexao = new Conectar().getConnection(); } public void cadastrar(Produtos obj) { try { String sql = "insert into tb_produtos (descricao,preco,qtd_estoque,for_id)values(?,?,?,?)"; //conectar banco de dados e organizar o sql // tratar os comandos sqls e executar (preparedstatement) PreparedStatement stmt = conexao.prepareStatement(sql); stmt.setString(1, obj.getDescricao()); stmt.setDouble(2, obj.getPreco()); stmt.setInt(3, obj.getQtd_estoque()); stmt.setInt(4, obj.getFornecedor().getId()); stmt.execute(); stmt.close(); JOptionPane.showMessageDialog(null, "Produto cadastrado com sucesso"); } catch (Exception erro) { JOptionPane.showMessageDialog(null, "Erro: " + erro); } } public List<Produtos> listarProdutos() { try { List<Produtos> lista = new ArrayList<>(); String sql = "select p.id,p.descricao,p.preco,p.qtd_estoque, f.nome from tb_produtos as p " + "inner join tb_fornecedores as f on (p.for_id = f.id)"; PreparedStatement stmt = conexao.prepareStatement(sql); ResultSet rs = stmt.executeQuery(); while (rs.next()) { Produtos obj = new Produtos(); Fornecedores f = new Fornecedores(); obj.setId(rs.getInt("p.id")); obj.setDescricao(rs.getString("p.descricao")); obj.setPreco(rs.getDouble("p.preco")); obj.setQtd_estoque(rs.getInt("p.qtd_estoque")); f.setNome(rs.getString(("f.nome"))); obj.setFornecedor(f); lista.add(obj); } return lista; } catch (Exception erro) { JOptionPane.showMessageDialog(null, "Erro: " + erro); return null; } } public void alterar(Produtos obj){ try { String sql = "update tb_produtos set descricao=?, preco=?, qtd_estoque=?, for_id=? where id=?"; PreparedStatement stmt = conexao.prepareStatement(sql); stmt.setString(1, obj.getDescricao()); stmt.setDouble(2, obj.getPreco()); stmt.setInt(3, obj.getQtd_estoque()); stmt.setInt(4, obj.getFornecedor().getId()); stmt.setInt(5, obj.getId()); stmt.execute(); stmt.close(); JOptionPane.showMessageDialog(null, "Produto alterado com sucesso"); } catch (Exception erro) { JOptionPane.showMessageDialog(null, "Erro: " + erro); } } public void excluir(Produtos obj){ try { String sql = "delete from tb_produtos where id=?"; PreparedStatement stmt = conexao.prepareStatement(sql); stmt.setInt(1,obj.getId()); stmt.execute(); stmt.close(); JOptionPane.showMessageDialog(null, "Produto excluido com sucesso"); } catch (Exception erro) { JOptionPane.showMessageDialog(null, "Erro: " + erro); } } // listar produtos por nome - retorna a lista public List<Produtos> listarProdutosPeloNome(String nome) { try { List<Produtos> lista = new ArrayList<>(); String sql = "select p.id,p.descricao,p.preco,p.qtd_estoque, f.nome from tb_produtos as p " + "inner join tb_fornecedores as f on (p.for_id = f.id) where p.descricao like ?"; PreparedStatement stmt = conexao.prepareStatement(sql); stmt.setString(1,nome); ResultSet rs = stmt.executeQuery(); while (rs.next()) { Produtos obj = new Produtos(); Fornecedores f = new Fornecedores(); obj.setId(rs.getInt("p.id")); obj.setDescricao(rs.getString("p.descricao")); obj.setPreco(rs.getDouble("p.preco")); obj.setQtd_estoque(rs.getInt("p.qtd_estoque")); f.setNome(rs.getString(("f.nome"))); obj.setFornecedor(f); lista.add(obj); } return lista; } catch (Exception erro) { JOptionPane.showMessageDialog(null, "Erro: " + erro); return null; } } public Produtos consultaPorNomeProdutos(String nome) { try { String sql = "select p.id,p.descricao,p.preco,p.qtd_estoque, f.nome from tb_produtos as p " + "inner join tb_fornecedores as f on (p.for_id = f.id) where p.descricao = ?"; PreparedStatement stmt = conexao.prepareStatement(sql); stmt.setString(1,nome); ResultSet rs = stmt.executeQuery(); Produtos obj = new Produtos(); Fornecedores f = new Fornecedores(); if(rs.next()){ obj.setId(rs.getInt("p.id")); obj.setDescricao(rs.getString("p.descricao")); obj.setPreco(rs.getDouble("p.preco")); obj.setQtd_estoque(rs.getInt("p.qtd_estoque")); f.setNome(rs.getString(("f.nome"))); obj.setFornecedor(f); } return obj; } catch (Exception erro) { JOptionPane.showMessageDialog(null, "Erro: " + erro); return null; } } public void adicionarEstoque (int id, int qtd_novo){ try { String sql = "update tb_produtos set qtd_estoque=? where id=?"; PreparedStatement stmt = conexao.prepareStatement(sql); stmt.setInt(1,qtd_novo); stmt.setInt(2,id); stmt.execute(); stmt.close(); } catch (Exception erro) { JOptionPane.showMessageDialog(null, "Erro: " + erro); } } }
/////////////////////////////////////////////////////////////////////////////// // ALL STUDENTS COMPLETE THESE SECTIONS // Title: TheGame // Files: DirectedGraph.java, Player.java, Item.java, Room.java, // TheGame.java // Semester: 367 Fall 2015 // // Author: Xiaojun He // Email: xhe66@wisc.edu // CS Login: xiaojun // Lecturer's Name: Jim Skrentny // //////////////////// PAIR PROGRAMMERS COMPLETE THIS SECTION //////////////////// // // Pair Partner: Junjie Xu // Email: (email address of your programming partner) // CS Login: (partner's login name) // Lecturer's Name: Jim Skrentny // //////////////////////////////////////////////////////////////////////////////// import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Scanner; import java.util.Set; /** * This is the main class that runs the whole game * * @author Xiaojun He * */ public class TheGame { private static String gameIntro; // initial introduction to the game private static String winningMessage; // winning message of game private static String gameInfo; // additional game info private static boolean gameWon = false; // state of the game private static Scanner scanner = null; // for reading files private static Scanner ioscanner = null; // for reading standard input private static Player player; // object for player of the game private static Room location; // current room in which player is located private static Room winningRoom; // Room which player must reach to win private static Item winningItem; // Item which player must find private static DirectedGraph<Room> layout; // Graph structure of the Rooms public static void main(String[] args) { if (args.length != 1) { System.err.println("Bad invocation! Correct usage: " + "java AppStore <gameFile>"); System.exit(1); } boolean didInitialize = initializeGame(args[0]); if (!didInitialize) { System.err.println("Failed to initialize the application!"); System.exit(1); } System.out.println(gameIntro); // game intro processUserCommands(); } /** * This is the method that intialize the game and read in files * * @param gameFile: the name of the files to be read * @return true if initialization is succeeded, false otherwise */ private static boolean initializeGame(String gameFile) { try { // reads player name System.out.println("Welcome worthy squire! What might be your name?"); ioscanner = new Scanner(System.in); String playerName = ioscanner.nextLine(); /* * read the contents of the input file using Java File IO * and then process them to initializeplayer and layout * (DirectedGraph) */ layout= new DirectedGraph<Room>(); File file = new File(gameFile); scanner = new Scanner(file); gameIntro = scanner.nextLine(); winningMessage = scanner.nextLine(); gameInfo = scanner.nextLine(); String line; String name; String roomDes; String description; boolean activated; String roomName; String message; boolean oneTimeUse; String usedString; boolean visibility; boolean habitability; String habMsg=null; String[] roomPair; HashSet<Item> startItems = new HashSet(); HashSet<Item> roomItems; ArrayList<MessageHandler> handlers; location=null; line = scanner.nextLine(); // Start reading the whole file while (scanner.hasNextLine()) { if (line.contains("#player")) { line = scanner.nextLine().trim(); //reading the intial items of a player while (line.contains("#item")) { boolean winItem=false; if (line.contains("win")) { winItem=true; } name = scanner.nextLine().trim(); description = scanner.nextLine().trim(); activated = scanner.nextLine().contains("true"); message = scanner.nextLine().trim(); oneTimeUse = scanner.nextLine().contains("true"); usedString = scanner.nextLine().trim(); Item newItem=new Item(name, description, activated, message, oneTimeUse, usedString); if (winItem){ winningItem=newItem; } startItems.add(newItem); line = scanner.nextLine().trim(); } } player=new Player(playerName, startItems); //reading rooms and items in it while (line.contains("#room")) { roomItems = new HashSet(); boolean isWin=false; if (line.contains("win")) { isWin=true; } roomName = scanner.nextLine().trim(); roomDes = scanner.nextLine().trim(); visibility = scanner.nextLine().contains("true"); habitability = scanner.nextLine().contains("true"); if (habitability==false){ habMsg= scanner.nextLine().trim(); } line = scanner.nextLine().trim(); while (line.contains("#item")) { boolean winItem=false; if (line.contains("win")) { winItem=true; } name = scanner.nextLine().trim(); description = scanner.nextLine().trim(); activated = scanner.nextLine().contains("true"); message = scanner.nextLine().trim(); oneTimeUse = scanner.nextLine().contains("true"); usedString = scanner.nextLine().trim(); // construct an item and put it to the room Item newItem=new Item(name, description, activated, message, oneTimeUse, usedString); if (winItem){ winningItem=newItem; } roomItems.add(newItem); line = scanner.nextLine().trim(); } handlers=new ArrayList<MessageHandler>(); //read in message handler for each room while (line.contains("#messageHandler")) { message = scanner.nextLine().trim(); String type; String unlockRoom=null; String secLine = scanner.nextLine().trim(); if (secLine.contains("room")) { unlockRoom = scanner.nextLine().trim(); } handlers.add(new MessageHandler(message, secLine, unlockRoom)); line = scanner.nextLine().trim(); } //construct a new room Room newRoom = new Room(roomName, roomDes, visibility, habitability, habMsg, roomItems, handlers); //set the first location to current location if (location==null){ location=newRoom; } //set the winningRoom if (isWin){ winningRoom=newRoom; } layout.addVertex(newRoom); } //read in locked meesage if (line.contains("#locked passages")) { Room room1, room2; String lockMessage; line = scanner.nextLine().trim(); while (!line.contains("#Adjacency List:")) { room1 = null; room2 = null; roomPair = line.split(" "); line = scanner.nextLine().trim(); lockMessage = line; Iterator<Room> itr = layout.getAllVertices().iterator(); while (itr.hasNext()) { Room currRoom = itr.next(); if (roomPair[0].equals(currRoom.getName())) { room1 = currRoom; } else if (roomPair[1].equals(currRoom.getName())) { room2 = currRoom; } if ((room1 != null) && (room2 != null)) { room1.addLockedPassage(room2, lockMessage); break; } } line = scanner.nextLine().trim(); } } //reading adjacency list if (line.contains("#Adjacency List:")) { Room room1, room2; while (scanner.hasNextLine()) { room1 = null; room2 = null; line = scanner.nextLine().trim(); roomPair = line.split(" "); if (roomPair.length<2) continue; Iterator<Room> itr = layout.getAllVertices().iterator(); while (itr.hasNext()) { Room currRoom = itr.next(); if (roomPair[0].equals(currRoom.getName())) { room1 = currRoom; } else if (roomPair[1].equals(currRoom.getName())) { room2 = currRoom; } if ((room1 != null) && (room2 != null)) { layout.addEdge(room1, room2); break; } } } } } return true; } catch (FileNotFoundException e) { e.printStackTrace(); return false; } catch (Exception e) { e.printStackTrace(); return false; } } private static void processUserCommands() { String command = null; do { System.out.print("\nPlease Enter a command ([H]elp):"); command = ioscanner.next(); switch (command.toLowerCase()) { case "p": // pick up processPickUp(ioscanner.nextLine().trim()); goalStateReached(); break; case "d": // put down item processPutDown(ioscanner.nextLine().trim()); break; case "u": // use item processUse(ioscanner.nextLine().trim()); break; case "lr":// look around processLookAround(); break; case "lt":// look at processLookAt(ioscanner.nextLine().trim()); break; case "ls":// look at sack System.out.println(player.printSack()); break; case "g":// goto room processGoTo(ioscanner.nextLine().trim()); goalStateReached(); break; case "q": System.out.println("You Quit! You, " + player.getName() + ", are a loser!!"); break; case "i": System.out.println(gameInfo); break; case "h": System.out.println("\nCommands are indicated in [], and may be followed by \n" + "any additional information which may be needed, indicated within <>.\n" + "\t[p] pick up item: <item name>\n" + "\t[d] put down item: <item name>\n" + "\t[u] use item: <item name>\n" + "\t[lr] look around\n" + "\t[lt] look at item: <item name>\n" + "\t[ls] look in your magic sack\n" + "\t[g] go to: <destination name>\n" + "\t[q] quit\n" + "\t[i] game info\n"); break; default: System.out.println("Unrecognized Command!"); break; } } while (!command.equalsIgnoreCase("q") && !gameWon); ioscanner.close(); } private static void processLookAround() { System.out.print(location.toString()); for (Room rm : layout.getNeighbors(location)) { System.out.println(rm.getName()); } } private static void processLookAt(String item) { Item itm = player.findItem(item); if (itm == null) { itm = location.findItem(item); } if (itm == null) { System.out.println(item + " not found"); } else System.out.println(itm.toString()); } private static void processPickUp(String item) { if (player.findItem(item) != null) { System.out.println(item + " already in sack"); return; } Item newItem = location.findItem(item); if (newItem == null) { System.out.println("Could not find " + item); return; } player.addItem(newItem); location.removeItem(newItem); System.out.println("You picked up "); System.out.println(newItem.toString()); } private static void processPutDown(String item) { if (player.findItem(item) == null) { System.out.println(item + " not in sack"); return; } Item newItem = player.findItem(item); location.addItem(newItem); player.removeItem(newItem); System.out.println("You put down " + item); } private static void processUse(String item) { Item newItem = player.findItem(item); if (newItem == null) { System.out.println("Your magic sack doesn't have a " + item); return; } if (newItem.activated()) { System.out.println(item + " already in use"); return; } if (notifyRoom(newItem)) { if (newItem.isOneTimeUse()) { player.removeItem(newItem); } } } private static void processGoTo(String destination) { Room dest = findRoomInNeighbours(destination); if (dest == null) { for (Room rm : location.getLockedPassages().keySet()) { if (rm.getName().equalsIgnoreCase(destination)) { System.out.println(location.getLockedPassages().get(rm)); return; } } System.out.println("Cannot go to " + destination + " from here"); return; } Room prevLoc = location; location = dest; if (!player.getActiveItems().isEmpty()) System.out.println("The following items are active:"); for (Item itm : player.getActiveItems()) { notifyRoom(itm); } if (!dest.isHabitable()) { System.out.println("Thou shall not pass because"); System.out.println(dest.getHabitableMsg()); location = prevLoc; return; } System.out.println(); processLookAround(); } private static boolean notifyRoom(Item item) { Room toUnlock = location.receiveMessage(item.on_use()); if (toUnlock == null) { if (!item.activated()) System.out.println("The " + item.getName() + " cannot be used here"); return false; } else if (toUnlock == location) { System.out.println(item.getName() + ": " + item.on_useString()); item.activate(); } else { // add edge from location to to Unlock layout.addEdge(location, toUnlock); if (!item.activated()) System.out.println(item.on_useString()); item.activate(); } return true; } private static Room findRoomInNeighbours(String room) { Set<Room> neighbours = layout.getNeighbors(location); for (Room rm : neighbours) { if (rm.getName().equalsIgnoreCase(room)) { return rm; } } return null; } private static void goalStateReached() { if ((location == winningRoom && player.hasItem(winningItem)) || (location == winningRoom && winningItem == null)) { System.out.println("Congratulations, " + player.getName() + "!"); System.out.println(winningMessage); System.out.println(gameInfo); gameWon = true; } } }
package ga.islandcrawl.action; import ga.islandcrawl.map.O; import ga.islandcrawl.object.*; import ga.islandcrawl.object.Object; import ga.islandcrawl.object.unit.Unit; /** * Created by Ga on 9/7/2015. */ public abstract class Action { protected Unit host; public int animation = 0; public int initAnimation = -1; public float frame = 1; public Action(){} public void init(Unit host){ this.host = host; if (initAnimation != -1) host.getForm().animate(initAnimation, (int)frame); } public void animate(){ if (frame > 99999) frame -= 99999; host.getForm().animate(animation, (int)frame); } public void end(){ host.getForm().animate(animation, 0); host.getForm().end(); } public abstract boolean perform(O target); public ga.islandcrawl.object.Object getSimpleTarget(O target){ if (target == null || target.occupant == null) return null; return target.occupant; } public AdvObject getAdvTarget(O target){ Object t = getSimpleTarget(target); if (t instanceof AdvObject && ((AdvObject) target.occupant).alive) return (AdvObject)t; return null; } }
package fr.clivana.lemansnews.utils; import android.app.Service; import android.content.Intent; import android.os.IBinder; //import android.os.RemoteException; public class SingletonService extends Service { // private final ISingletonService.Stub mBinder = new ISingletonService.Stub() { // public void startSingletons() throws RemoteException { // // initializeSingletons(); // // } // // public void stopSingletons() throws RemoteException { // // shutdownSingletons(); // // } // }; @Override public IBinder onBind(Intent intent) { return null; // return mBinder; } @Override public void onCreate() { super.onCreate(); initializeSingletons(); } @Override public void onDestroy() { super.onDestroy(); shutdownSingletons(); } protected void initializeSingletons() { ImageSingleton.create(getApplicationContext()); } private void shutdownSingletons() { ImageSingleton singleton = ImageSingleton.getInstance(); singleton.shutdown(); } }
/* * 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 Ejercicios; import java.util.Scanner; /** * * @author Michael */ public class GranPiramideMetodos { public static void main( String[] args){ int n=0; System.out.println("Introduce un numero entre -100 y 100 para enseñar los diez superiores e inferiores"); while(n<(-100)|| n>100){ System.out.println("Numero fuera de ango, introduce de nuevo"); } int num=leerNumero(n); System.out.println("Menores"); diezMenores(num); System.out.println("Mayores"); diezMayores(num); } public static int leerNumero(int n){ Scanner leer=new Scanner(System.in); n=leer.nextInt(); return n; } public static void diezMenores(int n){ int almacenado=n; if(n-10<-100){ for(int i=1;i<=(100+almacenado);i++){ System.out.print((n=n-1)+" "); } System.out.println(""); } else{ for(int i=1;i<=10;i++){ System.out.print((n=n-1)+" "); } System.out.println(""); } } public static void diezMayores(int n){ int almacenado=n; if(n+10>100){ for(int i=1;i<=(100-almacenado);i++){ System.out.print((n=n+1)+" "); } System.out.println(""); } else{ for(int i=1;i<=10;i++){ System.out.print((n=n+1)+" "); } } } }
package com.espendwise.manta.auth; import com.espendwise.manta.util.trace.ApplicationRuntimeException; public interface LogonService { public AppUser logon(String userName, LogonRequest request) throws ApplicationRuntimeException; }
package com.czm.cloudocr.PhotoSelect; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.util.DisplayMetrics; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.czm.cloudocr.GlideApp; import com.czm.cloudocr.MainActivity; import com.czm.cloudocr.PhotoHandle.PhotoHandleActivity; import com.czm.cloudocr.R; import com.czm.cloudocr.model.PhotoResult; import java.io.File; import java.util.List; import static com.bumptech.glide.load.resource.bitmap.BitmapTransitionOptions.withCrossFade; import static com.czm.cloudocr.util.SystemUtils.dip2px; /** * Created by Phelps on 2018/3/25. */ public class PhotoAdapter extends RecyclerView.Adapter<PhotoAdapter.ImageViewHolder> { private Context mContext; private List<String> mUrls; private PhotoSelectContract.Presenter mPresenter; private MainActivity mActivity; public PhotoAdapter(Context context, Activity activity, List<String> urls, PhotoSelectContract.Presenter presenter) { mContext = context; mUrls = urls; mPresenter = presenter; mActivity = (MainActivity) activity; } @NonNull @Override public ImageViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { View view = LayoutInflater.from(mContext).inflate(R.layout.item_photo_select, parent, false); return new ImageViewHolder(view); } @Override public void onBindViewHolder(@NonNull ImageViewHolder holder, final int position) { DisplayMetrics outMetrics = mContext.getApplicationContext().getResources().getDisplayMetrics(); int width = (outMetrics.widthPixels - dip2px(mContext,64))/3; GlideApp.with(mContext) .asBitmap() .override(width, dip2px(mContext,100)) .diskCacheStrategy(DiskCacheStrategy.ALL) .load(mUrls.get(position)) .transition(withCrossFade()) .into(holder.mImageView); holder.mImageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(mContext, PhotoHandleActivity.class); Uri uri = Uri.fromFile(new File(mUrls.get(position))); PhotoResult result = mPresenter.checkPhoto(uri); intent.putExtra("advanced", mActivity.isAdvanced()); intent.putExtra("flag", result != null); intent.putExtra("photo_result", result); intent.putExtra("photo", uri.toString()); mContext.startActivity(intent); } }); } @Override public int getItemCount() { return mUrls.size(); } public class ImageViewHolder extends RecyclerView.ViewHolder{ ImageView mImageView; public ImageViewHolder(View itemView) { super(itemView); mImageView = itemView.findViewById(R.id.photo_select_iv); } } }
package studio.cyclingbits.byob2048; import android.app.Activity; import android.os.Bundle; import android.view.ViewTreeObserver; import android.widget.FrameLayout; import android.widget.ImageView; public class MainActivity extends Activity { private RuntimeConstants constants = new RuntimeConstants(); private FrameLayout bikeView; private ImageView frontWheelImage; private ImageView frameImage; private ImageView crankImage; private ImageView rearWheelImage; private ImageView saddleImage; // grid private FrameLayout gridView; private int gridViewHeight; private int gridViewWidth; private ImageView gridImage; private int gridImageSize; private int gridImageX; private int gridImageY; private int gridSVGSize = 840; private int gridSVGTileSize = 200; private int gridSVGPadding = 5; private float gridImageScale; // tile private int tilePadding; private int tileImageSize; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); constants.setContext(this); bikeView = findViewById(R.id.bike_view); // frontWheelImage = new ImageView(this); // frontWheelImage.setImageResource(R.drawable.ic_100_front_wheel); // bikeView.addView(frontWheelImage); // // frameImage = new ImageView(this); // frameImage.setImageResource(R.drawable.ic_100_frame); // bikeView.addView(frameImage); // // crankImage = new ImageView(this); // crankImage.setImageResource(R.drawable.ic_100_crank); // bikeView.addView(crankImage); // // rearWheelImage = new ImageView(this); // rearWheelImage.setImageResource(R.drawable.ic_100_rear_wheel); // bikeView.addView(rearWheelImage); // // saddleImage = new ImageView(this); // saddleImage.setImageResource(R.drawable.ic_100_saddle); // bikeView.addView(saddleImage); gridView = findViewById(R.id.grid_view); constants.setGridView(gridView); gridView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { public void onGlobalLayout() { buildGrid(); gridImage.getViewTreeObserver().removeOnGlobalLayoutListener(this); TileManager tileManager = new TileManager(constants); tileManager.initGame(); tileManager.drawAllTiles(); } }); } private void buildGrid() { // grid view width & height gridViewHeight = gridView.getHeight(); gridViewWidth = gridView.getWidth(); // grid image width & height if(gridViewHeight<gridViewWidth){ gridImageSize = gridViewHeight; } else { gridImageSize = gridViewWidth; } // grid image X & Y gridImageX = (gridViewWidth - gridImageSize) / 2; constants.setGridImageX(gridImageX); gridImageY = 0; constants.setGridImageY(gridImageY); // grid scale gridImageScale = (float) gridImageSize / gridSVGSize; // draw gridImage = new ImageView(this); gridImage.setImageResource(R.drawable.ic_grid_padding_5_10); gridImage.setX(gridImageX); gridImage.setY(gridImageY); gridView.addView(gridImage, gridImageSize, gridImageSize); // tile tilePadding = Math.round(gridSVGPadding * gridImageScale); constants.setTilePadding(tilePadding); tileImageSize = Math.round(gridSVGTileSize * gridImageScale) + tilePadding*2; constants.setTileImageSize(tileImageSize); } }
package com.rastiehaiev.notebook.controller; import com.rastiehaiev.notebook.bean.User; import com.rastiehaiev.notebook.management.ISuggestionManagementService; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import javax.servlet.http.HttpSession; /** * @author Roman Rastiehaiev * Created on 18.10.15. */ @Controller public class SuggestionController extends BaseController { private static final Logger LOG = Logger.getLogger(SuggestionController.class); @Autowired private ISuggestionManagementService suggestionManagementService; @RequestMapping(value = "/suggestion", method = RequestMethod.POST) public void suggest(@RequestParam("word") String word, @RequestParam("translation") String translation, @RequestParam("to") String to, HttpSession session) { User user = getUser(session); LOG.info(String.format("Suggested. Word: %s, translation: %s, to: %s, by: %s.", word, translation, to, user.getId())); suggestionManagementService.putSuggestion(user.getId(), to, word, translation); } }
package com.google.android.exoplayer2.e; public interface c { public static final c aqg = new 1(); a d(String str, boolean z); a kp(); }
package utils; import java.io.File; import java.io.BufferedReader; import java.io.InputStreamReader; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.ArrayList; import java.util.Collections; public class SpiderUtils { public static String getResultLine(String line){ String pattern = "^<OK>(?!SyntaxError:).*"; Pattern r = Pattern.compile(pattern); Matcher m = r.matcher(line); if(m.find()){ return m.group(); }else{ return ""; } } /** * 执行cmd 命令, 并返回结果 * @param cmd * @param dir * @return */ public static String getResultByCmd(String cmd, File dir){ String line; String result=""; Runtime runtime=Runtime.getRuntime(); try{ Process p = runtime.exec(cmd, null, dir); BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream())); while ((line = input.readLine()) != null) { result = getResultLine(line); if(result != ""){ break; } } input.close(); }catch(Exception e){ e.printStackTrace(); } if(result == "" ||result.contains("DENIED")){ throw new RuntimeException("PERMISSION DENIED"); } return result; } /** * 从line中找到与pattern匹配的字符串, pattern为正则表达式,至少包含一个括号 * * @return pattern 中的group(1) */ public static String getPatternInLine(String pattern, String line){ Pattern r = Pattern.compile(pattern); Matcher m = r.matcher(line); if(m.find()){ return m.group(1); }else{ return ""; } } /** * 通过字符串获取浮点数数组 * @param line 字符串 * @param regex 分隔符 * @return */ public static float[] getFloatArrayFromString(String line, String regex){ return getFloatArrayFromString(line, regex, 0, line.split(regex).length); } /** * 通过字符串获取浮点数数组,返回数组从 begin 开始,到 end-1 结束 * @param line 字符串 * @param regex 分隔符 * @param begin * @param end * @return */ public static float[] getFloatArrayFromString(String line, String regex, int begin, int end){ String[] arrayS = getStringArrayFromString(line, regex, begin, end); int len = arrayS.length; float[] arrayF = new float[len]; for(int i=0;i<len;i++){ arrayF[i]=Float.parseFloat(arrayS[i]); } return arrayF; } /** * 以regex为界限分隔字符串,生成数组 * @param line 字符串 * @param regex 分隔符 * @return */ public static String[] getStringArrayFromString(String line, String regex){ return getStringArrayFromString(line, regex, 0, line.split(regex).length); } /** * 以regex为界限分隔字符串,生成数组,并且返回从 begin 开始,到 end-1 结束 * 的新数组 * @param line 字符串 * @param regex 分隔符 * @param begin * @param end * @return */ public static String[] getStringArrayFromString(String line, String regex, int begin, int end){ String[] arrayS = line.split(regex); int len = arrayS.length; if(end>len){ end=len; } String[] result = new String[end-begin]; int s = 0; for(int i = begin; i<end; i++){ result[s++] = arrayS[i]; } return result; } public static float getSumOfFloatArray(float[] array){ float result=0; for(float e:array){ result+=e; } return result; } /** * 将path转换 y 坐标的数组 * @param line * @return */ public static ArrayList<Float> getYFromPath(String line){ String[] splitC = line.split("C"); int lc = splitC.length; ArrayList<Float> result = new ArrayList<Float>(); for(int i=0; i<lc; i++){ String[] p = splitC[i].split(","); int len = p.length; result.add(Float.parseFloat(p[len-1])); } return result; } /** * 将path转换成 y 坐标,并进行格式化 * 百度指数最低的点设为0 * @param line * @return */ public static ArrayList<Float> getYFromPathFormat(String line){ ArrayList<Float> result = new ArrayList<Float>(); ArrayList<Float> tmp = getYFromPath(line); Float max = Collections.max(tmp); //此处为max for(Float y:tmp){ result.add(max-y); } return result; } /** * 将path坐标转换成 浮点数对 * @param line * @return */ public static ArrayList<float[]> getFloatPairsFromPath(String line){ String[] splitC = line.split("C"); int lc = splitC.length; ArrayList<float[]> result = new ArrayList<float[]>(); for(int i=0; i<lc; i++){ String[] p = splitC[i].split(","); int len = p.length; float[] tmp = {Float.parseFloat(p[len-2]),Float.parseFloat(p[len-1])}; result.add(tmp); } return result; } public static void main(String[] args) { // String line = getResultByCmd("phantomjs crowd.js %D2%F5%D1%F4%CA%A6", new File("./phantomjs/")); String line = getResultByCmd("phantomjs crowd.js %D6%D0%CC%EF%CE%C4", new File("./phantomjs/")); String p1 = "age::g:(.*?)a:"; System.out.println(line); String result= getPatternInLine(p1, line); System.out.println(result); float[] arrayF=getFloatArrayFromString(result,";"); for(Float e:arrayF){ System.out.println(e); } } }
package com.starmicronics.starprntsdk.functions; import com.starmicronics.starioextension.IScaleCommandBuilder; import com.starmicronics.starioextension.StarIoExt; import com.starmicronics.starioextension.StarIoExt.ScaleModel; public class ScaleFunctions { public static byte[] createZeroClear() { IScaleCommandBuilder builder = StarIoExt.createScaleCommandBuilder(ScaleModel.APS10); // IScaleCommandBuilder builder = StarIoExt.createScaleCommandBuilder(ScaleModel.APS12); // IScaleCommandBuilder builder = StarIoExt.createScaleCommandBuilder(ScaleModel.APS20); builder.appendZeroClear(); return builder.getPassThroughCommands(); } public static byte[] createUnitChange() { IScaleCommandBuilder builder = StarIoExt.createScaleCommandBuilder(ScaleModel.APS10); // IScaleCommandBuilder builder = StarIoExt.createScaleCommandBuilder(ScaleModel.APS12); // IScaleCommandBuilder builder = StarIoExt.createScaleCommandBuilder(ScaleModel.APS20); builder.appendUnitChange(); return builder.getPassThroughCommands(); } }
package com.tencent.mm.plugin.wallet_core.id_verify; import android.text.SpannableString; import com.tencent.mm.ab.l; import com.tencent.mm.plugin.wallet_core.ui.h; import com.tencent.mm.plugin.wxpay.a; import com.tencent.mm.ui.MMActivity; import com.tencent.mm.wallet_core.d.g; import com.tencent.mm.wallet_core.d.i; class a$3 extends g { final /* synthetic */ a pjX; a$3(a aVar, MMActivity mMActivity, i iVar) { this.pjX = aVar; super(mMActivity, iVar); } public final CharSequence ui(int i) { if (i != 0) { return null; } String string = this.fEY.getString(a.i.wallet_real_name_verify_cur_verify_id_tip); String string2 = this.fEY.getString(a.i.wallet_real_name_verify_change_to_bindcard); string = this.fEY.getString(a.i.wallet_real_name_verify_tip, new Object[]{string, string2}); h hVar = new h(this.fEY); SpannableString spannableString = new SpannableString(string); spannableString.setSpan(hVar, string.length() - string2.length(), string.length(), 33); return spannableString.subSequence(0, spannableString.length()); } public final boolean m(Object... objArr) { return false; } public final boolean d(int i, int i2, String str, l lVar) { return false; } }