text
stringlengths
10
2.72M
package mygroup; import java.util.List; import rx.Observable; import rx.Subscriber; import rx.schedulers.Schedulers; class MyOnSubscribe implements Observable.OnSubscribe<Integer> { @Override public void call(Subscriber<? super Integer> t) { t.onNext(1); t.onCompleted(); } } class MySubscriber extends Subscriber<Integer> { @Override public void onCompleted() { System.out.println("onCompleted"); } @Override public void onError(Throwable e) { System.out.println("onError"); } @Override public void onNext(Integer t) { System.out.println("onNext: " + t); } } class User { private int age; private String name; public User(int age, String name) { this.age = age; this.name = name; } public int getAge() { return age; } public String getName() { return name; } } public class UseRx { public static void main(String[] args) { // 使用rxjava1.3.8的api @SuppressWarnings("deprecation") final Observable<Integer> ob = Observable.create(new MyOnSubscribe()); ob.subscribe(new MySubscriber()); Observable.just("hw").subscribe(System.out::println); Observable.just(7, 9, 5, 4) .subscribeOn(Schedulers.io()) .observeOn(Schedulers.immediate()) .subscribe(System.out::print); System.out.println(); List<User> list = List.of(new User(20, "John"), new User(30, "Smith")); Observable.from(list) .map(User::getAge) .subscribe(System.out::print); System.out.println(); } }
package Deneme; public class Insan { private String ad; private String soyad; private int yas; public static int say; public Insan(String ad, String soyad, int yas) { this.ad = ad; this.soyad = soyad; this.yas = yas; } @Override public String toString() { return "Insan [ad=" + ad + ", soyad=" + soyad + ", yas=" + yas + "] insan SAY: " + say; } }
package com.toshevski.android.shows.pojos; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.util.Log; import java.io.File; import java.io.FileInputStream; import java.io.Serializable; import java.util.ArrayList; public class Series implements Serializable { public enum ImageStatus { NO, DOWN, ONLINE } private String title; private int year; private String imdb; private String overview; private double rating; private String genre; private String imageLink; private ArrayList<Season> seasons; private Drawable image; private ImageStatus status; private int lastTimeUnfinished; private int totalEpisodes; private int totalSpecialEpisodes; public boolean selected; private boolean refresh; private File filesDir; public Series(String title, int year, String imdb, String overview, double rating, String genre, String imageLink, ImageStatus status) { this.title = title; this.year = year; this.imdb = imdb; this.overview = overview; this.rating = rating; this.genre = genre; this.seasons = new ArrayList<>(); this.imageLink = imageLink; this.status = status; this.selected = false; this.totalEpisodes = -1; this.lastTimeUnfinished = -1; this.refresh = true; } @Override public String toString() { return title; } public void setRefresh(boolean refresh) { this.refresh = refresh; } public boolean isRefresh() { return refresh; } public void addAllSeasons(ArrayList<Season> s) { this.seasons = s; } public Season addSeason(Season s) { for (int i = 0; i < seasons.size(); ++i) { if (s.getTraktID() == seasons.get(i).getTraktID()) { Season old = seasons.get(i); old.setRating(s.getRating()); old.setAiredEpisodes(s.getAiredEpisodes()); old.setEpisodesCount(s.getEpisodesCount()); old.setOverview(s.getOverview()); return old; } } seasons.add(s); return s; } public void setAllFinished(Boolean how) { for (Season s : seasons) { s.setAllFinished(how); } } public boolean isSelected() { return selected; } public void setSelected(boolean selected) { this.selected = selected; } public int getTotalSpecialEpisodes() { return totalSpecialEpisodes; } public void setTotalSpecialEpisodes(int totalSpecialEpisodes) { this.totalSpecialEpisodes = totalSpecialEpisodes; } public int getNumberOfSeasons() { return seasons.size(); } public void removePictures(File filesDir) { for (Season s : seasons) { Log.i("Series.removePic:", "Brishenje: " + s.getTitle()); File f = new File(filesDir, s.getImageLink()); if (f.exists()) f.delete(); } } public Season getOneSeason(int position) { return seasons.get(position); } public void setFilesDir(File filesDir) { this.filesDir = filesDir; } public Drawable getImageFromFile() { try { FileInputStream fis = new FileInputStream(new File(filesDir, getImageLink())); Bitmap b = BitmapFactory.decodeStream(fis); return new BitmapDrawable(Resources.getSystem(), b); } catch (Exception e) { Log.i("Season.getImage:", e.getMessage()); e.printStackTrace(); } return null; } public void setRating(double rating) { this.rating = rating; } public void setGenre(String genre) { this.genre = genre; } public void setTotalEpisodes(int totalEpisodes) { this.totalEpisodes = totalEpisodes; } public int getTotalEpisodes() { return totalEpisodes + totalSpecialEpisodes; } public void setOverview(String overview) { this.overview = overview; } public int getUnfinished() { int counter = 0; for (Season s : seasons) { counter += s.getUnfinished(); } return counter; } public String getFirstHeader() { return Integer.toString(year); } public int returnType() { return 0; } public void setImage(Drawable image) { this.image = image; } public void setStatus(ImageStatus status) { this.status = status; } public Drawable getImage() { return image; } public String getTitle() { return title; } public ImageStatus getStatus() { return status; } public int getYear() { return year; } public String getImdb() { return imdb; } public String getOverview() { return overview; } public double getRating() { return rating; } public String getImageLink() { return imdb + ".jpg"; } public String getGenre() { return genre; } public ArrayList<Season> getSeasons() { return seasons; } }
package leecode.DP; public class 地下城游戏_174 { public int calculateMinimumHP(int[][] dungeon) { //https://leetcode-cn.com/problems/dungeon-game/solution/dong-tai-gui-hua-by-wisemove-2-7/ int m=dungeon.length; int n=dungeon[0].length; /* dp是倒序的:倒序的含义是“从(i,j)出发,到达终点需要最少的血量”。 因为有“加血”的过程,只能依赖后面的值判断需要的血量。所以倒序 正序的含义为“从起点出发,到达位置(i,j)所需要的最少血量”,最小路径和为什么是正序的? 因为【最小路径和】是无状态的,你会发现【最小路径和】倒序dp也是可以的, */ int[][]dp=new int[m][n]; //保证最低血为1 dp[m-1][n-1]=Math.max(1,1-dungeon[m-1][n-1]);//最后一点存活的血量:到达最后一点要有1滴血-改点怪物,保证消耗完后还有1滴 for (int i = m-2; i >=0 ; i--) { int temp=dp[i+1][n-1]-dungeon[i][n-1];//邻点 - 该点的血量 dp[i][n-1]=Math.max(temp,1);//保证血量最少为1 } for(int i = n - 2; i >= 0; i--){ dp[m-1][i] = Math.max(1, dp[m-1][i+1] - dungeon[m-1][i]); } for(int i = m - 2; i >= 0; i--){ for(int j = n - 2; j >= 0; j--){ int dpmin = Math.min(dp[i+1][j], dp[i][j+1]); dp[i][j] = Math.max(1, dpmin - dungeon[i][j]); } } return dp[0][0]; } }
package com.google.android.exoplayer2.metadata.emsg; import com.google.android.exoplayer2.i.j; import com.google.android.exoplayer2.metadata.Metadata; import com.google.android.exoplayer2.metadata.Metadata.Entry; import com.google.android.exoplayer2.metadata.d; import java.nio.ByteBuffer; import java.util.Arrays; public final class a implements com.google.android.exoplayer2.metadata.a { public final Metadata a(d dVar) { ByteBuffer byteBuffer = dVar.aig; j jVar = new j(byteBuffer.array(), byteBuffer.limit()); String mj = jVar.mj(); String mj2 = jVar.mj(); long ba = jVar.ba(); jVar.da(4); return new Metadata(new Entry[]{new EventMessage(mj, mj2, (jVar.ba() * 1000) / ba, jVar.ba(), Arrays.copyOfRange(r1, jVar.position, r0))}); } }
package heihei.frame; /** * Created by Administrator on 2016/8/7. */ public class BannerModel { String title; String img; String url; public BannerModel(String title, String img, String url) { this.title = title; this.img = img; this.url = url; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getImg() { return img; } public void setImg(String img) { this.img = img; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } }
package br.com.allerp.allbanks.entity.colaborador; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import org.hibernate.annotations.ForeignKey; import br.com.allerp.allbanks.entity.pessoa.PessoaFisica; @Entity @Table(name = "FUNCIONARIO") @ForeignKey(name = "FK_FUNC_PF") public class Funcionario extends PessoaFisica { private static final long serialVersionUID = -7294170664540633593L; @OneToMany(mappedBy = "funcionario", cascade = CascadeType.ALL) private List<Dependente> dependente; @ManyToOne @JoinColumn(name = "dpto_cod", referencedColumnName = "codigo") @ForeignKey(name = "FK_FUNC_DPTO") private Departamento departamento; @Column(nullable = false, precision = 7, scale = 2) private Float salario; @Column(nullable = false, length = 20) private String formacao; @Column(nullable = false, length = 20) private String funcao; public List<Dependente> getDependente() { return dependente; } public void setDependente(List<Dependente> dependente) { this.dependente = dependente; } public Departamento getDepartamento() { return departamento; } public void setDepartamento(Departamento departamento) { this.departamento = departamento; } public Float getSalario() { if(salario == null) { return new Float("0"); } return salario; } public void setSalario(Float salario) { this.salario = salario; } public String getFormacao() { if(formacao == null) { return ""; } return formacao; } public void setFormacao(String formacao) { this.formacao = formacao; } public String getFuncao() { if(funcao == null) { return ""; } return funcao; } public void setFuncao(String funcao) { this.funcao = funcao; } }
package com.company; import java.util.Arrays; public class CyclicSort { public static void main(String[] args) { int[] arr ={ 5,4,3,2,1}; sort(arr); System.out.println(Arrays.toString(arr)); } static void sort (int arr[]) { int i=0; while(i<arr.length) { int correct=arr[i]-1; if(arr[i] != arr[correct]) swap(arr,i,correct); else i++; } } static void swap(int[] arr, int first, int second) { int temp; temp=arr[first]; arr[first]=arr[second]; arr[second]=temp; } }
package abstractfactory.design.pattern.example; public class FactoryCreator { public static AbstractFactory getFactory(String choice) { if (choice.equalsIgnoreCase("Event")) { return new EventFactory(); } else if (choice.equalsIgnoreCase("Error")) { return new ErrorFactory(); } return null; } }
package com.codelaxy.qwertpoiuy; import android.app.AlertDialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.Drawable; import android.os.Bundle; import android.os.CountDownTimer; import com.bumptech.glide.Glide; import com.bumptech.glide.load.DataSource; import com.bumptech.glide.load.engine.DiskCacheStrategy; import com.bumptech.glide.load.engine.GlideException; import com.bumptech.glide.request.RequestListener; import com.bumptech.glide.request.target.Target; import com.google.android.material.snackbar.Snackbar; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import android.os.Handler; import android.util.Log; import android.view.Gravity; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.TextView; import com.codelaxy.qwertpoiuy.Api.RetrofitClient; import com.codelaxy.qwertpoiuy.Models.Captcha; import com.codelaxy.qwertpoiuy.Models.DefaultResponse; import java.util.ArrayList; import butterknife.BindView; import butterknife.ButterKnife; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class CaptchaActivity extends AppCompatActivity implements View.OnClickListener { @BindView(R.id.toolbar) androidx.appcompat.widget.Toolbar toolbar; @BindView(R.id.captcha_image) ImageView captcha_image; @BindView(R.id.captcha_text) EditText captcha_text; @BindView(R.id.btn_continue) Button btn_continue; @BindView(R.id.btn_skip) Button btn_skip; @BindView(R.id.right_captcha_count) TextView txt_right_count; @BindView(R.id.wrong_captcha_count) TextView txt_wrong_count; @BindView(R.id.skip_captcha_count) TextView txt_skip_count; @BindView(R.id.captcha_type) TextView captcha_type; @BindView(R.id.timer_text) TextView timer_text; @BindView(R.id.next_order) Button next_order; @BindView(R.id.balance) TextView balance; TextView txt_user_id, txt_total_earning; androidx.appcompat.app.AlertDialog alertDialog = null; //int position = 0, right_count, wrong_count, skip_count, total_earning, auto_approve; ArrayList<Captcha> dataList; //String image_url = "http://captchabro.website/CaptchaApi/includes/uploads/"; CountDownTimer timer; boolean timer_running = false; String captcha_id; String str_captcha_type; String total_earning, user_id, captcha_time, captcha_count, captcha_rate, auto_approve; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_captcha); ButterKnife.bind(this); setSupportActionBar(toolbar); txt_user_id = toolbar.findViewById(R.id.user_id); txt_total_earning = toolbar.findViewById(R.id.total_earning); total_earning = getIntent().getStringExtra("total_earning"); user_id = getIntent().getStringExtra("user_id"); captcha_time = getIntent().getStringExtra("captcha_time"); captcha_count = getIntent().getStringExtra("captcha_count"); captcha_rate = getIntent().getStringExtra("captcha_rate"); auto_approve = getIntent().getStringExtra("auto_approve"); txt_user_id.setText(user_id); txt_total_earning.setText("Total Earning - "+total_earning+" $"); balance.setText(captcha_count + " / " + captcha_rate + " $"); next_order.setEnabled(false); getCaptcha(); btn_continue.setOnClickListener(this); btn_skip.setOnClickListener(this); next_order.setOnClickListener(this); } private void getCaptcha() { ProgressDialog dialog = new ProgressDialog(CaptchaActivity.this); dialog.setCancelable(false); dialog.setMessage("Please wait..."); dialog.show(); Call<com.codelaxy.qwertpoiuy.ModelsNew.CaptchaResponse> call = RetrofitClient.getInstance().getApi().getCaptcha(user_id); call.enqueue(new Callback<com.codelaxy.qwertpoiuy.ModelsNew.CaptchaResponse>() { @Override public void onResponse(Call<com.codelaxy.qwertpoiuy.ModelsNew.CaptchaResponse> call, Response<com.codelaxy.qwertpoiuy.ModelsNew.CaptchaResponse> response) { dialog.dismiss(); com.codelaxy.qwertpoiuy.ModelsNew.Captcha captcha = response.body().getCaptcha(); if (captcha != null) { String str_right_count = captcha.getRight_count(); String str_wrong_count = captcha.getWrong_count(); String str_skip_count = captcha.getSkip_count(); String is_right = captcha.getIs_right(); captcha_id = captcha.getId(); String str_image = captcha.getImage(); str_captcha_type = captcha.getCaptcha_type(); if (Integer.parseInt(str_right_count) >= Integer.parseInt(captcha_count) && auto_approve.equals("0")) { completeOrder(); } else if (Integer.parseInt(str_right_count) >= Integer.parseInt(captcha_count) && auto_approve.equals("1")) { autoApproveOrder(); } else { txt_right_count.setText(str_right_count); txt_wrong_count.setText(str_wrong_count); txt_skip_count.setText(str_skip_count); captcha_type.setText(str_captcha_type); Glide.with(CaptchaActivity.this) .load(str_image) .diskCacheStrategy(DiskCacheStrategy.NONE) .skipMemoryCache(true) .listener(new RequestListener<Drawable>() { @Override public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) { return false; } @Override public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) { if (timer_running) { timer.cancel(); startTimer(); } else startTimer(); return false; } }) .into(captcha_image); /*Picasso.get().load(image_url + str_image).resize(500, 200).memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE).into(captcha_image, new com.squareup.picasso.Callback() { @Override public void onSuccess() { if (timer_running) { timer.cancel(); startTimer(); } else startTimer(); } @Override public void onError(Exception e) { } });*/ } } } @Override public void onFailure(Call<com.codelaxy.qwertpoiuy.ModelsNew.CaptchaResponse> call, Throwable t) { dialog.dismiss(); Log.d("niraj", "Failed"); } }); } private void submitCaptcha() { ProgressDialog dialog = new ProgressDialog(CaptchaActivity.this); dialog.setMessage("Please wait..."); dialog.setCancelable(false); dialog.show(); Call<com.codelaxy.qwertpoiuy.ModelsNew.CaptchaResponse> call = RetrofitClient.getInstance().getApi().submitCaptcha(user_id, captcha_id, captcha_text.getText().toString().trim(), str_captcha_type); call.enqueue(new Callback<com.codelaxy.qwertpoiuy.ModelsNew.CaptchaResponse>() { @Override public void onResponse(Call<com.codelaxy.qwertpoiuy.ModelsNew.CaptchaResponse> call, Response<com.codelaxy.qwertpoiuy.ModelsNew.CaptchaResponse> response) { dialog.dismiss(); com.codelaxy.qwertpoiuy.ModelsNew.Captcha captcha = response.body().getCaptcha(); if (captcha != null) { captcha_text.setText(""); String str_right_count = captcha.getRight_count(); String str_wrong_count = captcha.getWrong_count(); String str_skip_count = captcha.getSkip_count(); String is_right = captcha.getIs_right(); captcha_id = captcha.getId(); String str_image = captcha.getImage(); str_captcha_type = captcha.getCaptcha_type(); if (is_right.equals("0")) showSnackBar("Wrong Answer"); if (Integer.parseInt(str_right_count) >= Integer.parseInt(captcha_count) && auto_approve.equals("0")) { completeOrder(); } else if (Integer.parseInt(str_right_count) >= Integer.parseInt(captcha_count) && auto_approve.equals("1")) { autoApproveOrder(); } else { txt_right_count.setText(str_right_count); txt_wrong_count.setText(str_wrong_count); txt_skip_count.setText(str_skip_count); captcha_type.setText(str_captcha_type); /*Picasso.get().load(image_url + str_image).resize(500, 200).memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE).into(captcha_image, new com.squareup.picasso.Callback() { @Override public void onSuccess() { if (timer_running) { timer.cancel(); startTimer(); } else startTimer(); } @Override public void onError(Exception e) { } });*/ Glide.with(CaptchaActivity.this) .load(str_image) .diskCacheStrategy(DiskCacheStrategy.NONE) .skipMemoryCache(true) .listener(new RequestListener<Drawable>() { @Override public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) { return false; } @Override public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) { if (timer_running) { timer.cancel(); startTimer(); } else startTimer(); return false; } }) .into(captcha_image); } } } @Override public void onFailure(Call<com.codelaxy.qwertpoiuy.ModelsNew.CaptchaResponse> call, Throwable t) { dialog.dismiss(); Log.d("niraj", "Failed"); } }); } private void skipCaptcha() { ProgressDialog dialog = new ProgressDialog(CaptchaActivity.this); dialog.setMessage("Please wait..."); dialog.setCancelable(false); dialog.show(); Call<com.codelaxy.qwertpoiuy.ModelsNew.CaptchaResponse> call = RetrofitClient.getInstance().getApi().skipCaptcha(user_id); call.enqueue(new Callback<com.codelaxy.qwertpoiuy.ModelsNew.CaptchaResponse>() { @Override public void onResponse(Call<com.codelaxy.qwertpoiuy.ModelsNew.CaptchaResponse> call, Response<com.codelaxy.qwertpoiuy.ModelsNew.CaptchaResponse> response) { dialog.dismiss(); com.codelaxy.qwertpoiuy.ModelsNew.Captcha captcha = response.body().getCaptcha(); if (captcha != null) { captcha_text.setText(""); String str_right_count = captcha.getRight_count(); String str_wrong_count = captcha.getWrong_count(); String str_skip_count = captcha.getSkip_count(); String is_right = captcha.getIs_right(); captcha_id = captcha.getId(); String str_image = captcha.getImage(); str_captcha_type = captcha.getCaptcha_type(); if (Integer.parseInt(str_right_count) >= Integer.parseInt(captcha_count) && auto_approve.equals("0")) { completeOrder(); } else if (Integer.parseInt(str_right_count) >= Integer.parseInt(captcha_count) && auto_approve.equals("1")) { autoApproveOrder(); } else { txt_right_count.setText(str_right_count); txt_wrong_count.setText(str_wrong_count); txt_skip_count.setText(str_skip_count); captcha_type.setText(str_captcha_type); /*Picasso.get().load(image_url + str_image).resize(500, 200).memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE).into(captcha_image, new com.squareup.picasso.Callback() { @Override public void onSuccess() { btn_skip.setEnabled(true); btn_continue.setEnabled(true); if (timer_running) { timer.cancel(); startTimer(); } else startTimer(); } @Override public void onError(Exception e) { } });*/ Glide.with(CaptchaActivity.this) .load(str_image) .diskCacheStrategy(DiskCacheStrategy.NONE) .skipMemoryCache(true) .listener(new RequestListener<Drawable>() { @Override public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) { return false; } @Override public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) { if (timer_running) { timer.cancel(); startTimer(); } else startTimer(); return false; } }) .into(captcha_image); } } } @Override public void onFailure(Call<com.codelaxy.qwertpoiuy.ModelsNew.CaptchaResponse> call, Throwable t) { dialog.dismiss(); Log.d("niraj", "Failed"); } }); } private void autoApproveOrder() { btn_continue.setEnabled(false); btn_skip.setEnabled(false); Call<DefaultResponse> call = RetrofitClient.getInstance().getApi().autoApproveOrder(user_id); call.enqueue(new Callback<DefaultResponse>() { @Override public void onResponse(Call<DefaultResponse> call, Response<DefaultResponse> response) { if (response.code() == 201) { Snackbar.make(findViewById(R.id.main_layout), "Your " + captcha_rate + "$ payment completed successfully. Please login again to continue", Snackbar.LENGTH_LONG).show(); new Handler() .postDelayed(new Runnable() { @Override public void run() { Intent intent = new Intent(getApplicationContext(), Login.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } }, 5000); } else { showSnackBar("Something went wrong. Please try again"); finish(); Log.d("niraj", response.message()); } } @Override public void onFailure(Call<DefaultResponse> call, Throwable t) { Log.d("niraj", "Failed"); Log.d("niraj", t.getMessage()); showSnackBar("Something went wrong. Please try again"); finish(); } }); } private void completeOrder() { AlertDialog.Builder builder = new AlertDialog.Builder(CaptchaActivity.this); builder.setCancelable(false); builder.setMessage("Your " + captcha_rate + " $ payment completed. You can now take payment from company and Click on Next order button to take next order"); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface dialog, int which) { dialog.cancel(); next_order.setBackgroundColor(getResources().getColor(R.color.colorPrimary)); next_order.setEnabled(true); btn_continue.setEnabled(false); btn_skip.setEnabled(false); captcha_text.setEnabled(false); btn_continue.setBackgroundColor(getResources().getColor(R.color.light_grey)); btn_skip.setBackgroundColor(getResources().getColor(R.color.light_grey)); } }).create().show(); } private void startTimer() { timer_running = true; int int_timer = Integer.parseInt(captcha_time); timer = new CountDownTimer((int_timer + 1) * 1000, 1000) { @Override public void onTick(long millisUntilFinished) { timer_text.setText(String.valueOf((millisUntilFinished / 1000)) + " s"); } @Override public void onFinish() { //skip(); getCaptcha(); } }; timer.start(); } /*private void getNewCaptcha() { if (position >= dataList.size()) { position = 0; Collections.shuffle(dataList); } if (right_count >= Integer.parseInt(captcha_count) && auto_approve == 0) { completeOrder(); } else if (right_count >= Integer.parseInt(captcha_count) && auto_approve == 1) { autoApproveOrder(); } else { Picasso.get().load(image_url + dataList.get(position + 1).getImage()).resize(500, 200).into(captcha_image, new com.squareup.picasso.Callback() { @Override public void onSuccess() { if (timer_running) { timer.cancel(); startTimer(); } else startTimer(); } @Override public void onError(Exception e) { } }); captcha_type.setText("* " + dataList.get(position + 1).getCaptcha_type()); position++; } } */ @Override public void onClick(View v) { if (v == next_order) { final ProgressDialog progressDialog = new ProgressDialog(CaptchaActivity.this); progressDialog.setMessage("Please Wait"); progressDialog.setCancelable(false); progressDialog.show(); Call<DefaultResponse> call1 = RetrofitClient.getInstance().getApi().createNextOrder(user_id); call1.enqueue(new Callback<DefaultResponse>() { @Override public void onResponse(Call<DefaultResponse> call, Response<DefaultResponse> response) { progressDialog.cancel(); if (response.code() == 201) { AlertDialog.Builder builder = new AlertDialog.Builder(CaptchaActivity.this); builder.setCancelable(false); builder.setMessage("Your request for next order has been sent. Please wait for response"); builder.setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.cancel(); next_order.setEnabled(false); } }).create().show(); } } @Override public void onFailure(Call<DefaultResponse> call, Throwable t) { progressDialog.cancel(); } }); } if (v == btn_continue) { submitCaptcha(); } if (v == btn_skip) { skipCaptcha(); } } public void showSnackBar(String msg) { Snackbar mSnackBar = Snackbar.make(findViewById(R.id.main_layout), msg, Snackbar.LENGTH_SHORT); View view = mSnackBar.getView(); FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) view.getLayoutParams(); params.gravity = Gravity.TOP; view.setLayoutParams(params); view.setBackgroundColor(Color.RED); TextView mainTextView = (TextView) (view).findViewById(com.google.android.material.R.id.snackbar_text); mainTextView.setTextColor(Color.WHITE); mSnackBar.show(); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle item selection switch (item.getItemId()) { case R.id.order_history: if (timer_running) timer.cancel(); Intent intent = new Intent(CaptchaActivity.this, OrderHistory.class); intent.putExtra("user_id", user_id); intent.putExtra("total_earning", total_earning); startActivity(intent); return true; case R.id.view_messages: if (timer_running) timer.cancel(); startActivity(new Intent(CaptchaActivity.this, ViewMessages.class)); return true; case R.id.logout: if (timer_running) timer.cancel(); finish(); default: return super.onOptionsItemSelected(item); } } @Override protected void onPause() { super.onPause(); if (timer_running) timer.cancel(); } @Override protected void onStop() { super.onStop(); if (timer_running) timer.cancel(); } @Override protected void onResume() { super.onResume(); if (timer != null) timer.start(); } }
/* * 文 件 名: Node.java * 描 述: <描述> * 修 改 人: root * 修改时间: 2014-10-29 * 跟踪单号: <跟踪单号> * 修改单号: <修改单号> * 修改内容: <修改内容> */ package com.henry.tree; /** * <一句话功能简述> * <功能详细描述> * * @author root * @version [版本号, 2014-10-29] * @see [相关类/方法] * @since [产品/模块版本] */ public class Node { int key; private Node left; private Node right; private Node Parent; //红黑树所需要 private String color; public int getKey() { return key; } public void setKey(int key) { this.key = key; } public Node getLeft() { return left; } public void setLeft(Node left) { this.left = left; } public Node getRight() { return right; } public void setRight(Node right) { this.right = right; } public Node getParent() { return Parent; } public void setParent(Node parent) { Parent = parent; } public String getColor() { return color; } public void setColor(String color) { this.color = color; } }
package support.yz.data.entity.node; import java.util.ArrayList; import java.util.List; import lombok.Getter; import lombok.Setter; /** * @author yangzhuo * @Description 技术链分装类 * @Date: 2018/7/25 */ @Setter @Getter public class TechnologyChain { private String name; private List<TechnologyChain> children = new ArrayList<TechnologyChain>(); }
//John Aspinwall //Zachary Zembower package experiment; import java.io.File; import java.io.FileNotFoundException; import java.util.ArrayList; import java.util.HashSet; import java.util.LinkedList; import java.util.Scanner; import java.util.Set; public class IntBoard { ArrayList<String> boardArray; ArrayList<LinkedList<Integer>> adjList; int size; Set targets = new HashSet<Integer>(); ArrayList<Boolean> visited; public IntBoard() { super(); try { Scanner s = new Scanner(new File("simpleMap.csv")); boardArray = new ArrayList<String>(); s.useDelimiter(", *"); while (s.hasNext()){ boardArray.add(s.next()); } s.close(); } catch (FileNotFoundException e) { // TODO Auto-generated catch block System.out.println("Failed in IntBoard declaration due to file not found"); e.printStackTrace(); } //for(String s: list) //System.out.println(s); //System.out.println(list.size()); adjList = new ArrayList<LinkedList<Integer>>(); size = (int) Math.sqrt(boardArray.size()); } public void calcAdjacencies() { for(int i = 0; i < boardArray.size(); i++) { LinkedList<Integer> set = new LinkedList<Integer>(); if(i - size >= 0) set.add(i-size); if(i + size < size * size) set.add(i+size); if(i - 1 >= 0 && i%size != 0) set.add(i-1); if(i + 1 < size * size && (i+1)%size != 0) set.add(i+1); adjList.add(set); } } public void startTargets(int location, int roll) { LinkedList<Integer> adjList = getAdjList(location); visited = new ArrayList<Boolean>(); for(int i=0;i<boardArray.size();i++) visited.add(false); visited.set(location, true); if(roll == 1) { targets.add(this.getAdjList(location)); } else { for(Integer i: adjList) { calcTargets(i,roll-1); } } } public int calcIndex(int row, int col) { int location; location = row * size + col; return location; } public Set getTargets() { return targets; } public LinkedList<Integer> getAdjList(int location) { return adjList.get(location); } public void calcTargets(int location, int roll) { LinkedList<Integer> adjList = getAdjList(location); visited.set(location, true); for(Integer i: adjList) { if(visited.get(i) == false) if(roll == 1) targets.add(i); else calcTargets(i,roll-1); } visited.set(location, false); } public static void main(String args[]) { IntBoard intBoard = new IntBoard(); } }
package org.zerock.domain; import lombok.Data; import java.util.Date; @Data public class BagVO { private int bagOid; private int userOid; private int merchanOid; private int count; private String demand; }
package com.khaale.bigdatarampup.mapreduce.hw3.part1; import com.khaale.bigdatarampup.mapreduce.shared.LocalFilePathProvider; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.io.LongWritable; import org.apache.hadoop.io.Text; import org.apache.hadoop.mrunit.mapreduce.MapDriver; import org.junit.Before; import org.junit.Test; import java.io.IOException; import static org.powermock.api.mockito.PowerMockito.when; /** * Created by Aleksander_Khanteev on 3/29/2016. */ public class UserTagsMapperTests { MapDriver<LongWritable, Text, Text, LongWritable> mapDriver; @Before public void setUp() { UserTagsMapper mapper = new UserTagsMapper(); mapDriver = new MapDriver<>(); mapDriver.setMapper(mapper); Configuration conf = mapDriver.getConfiguration(); conf.set(LocalFilePathProvider.LocalKey,"data\\user.profile.tags.us.txt"); } @Test public void testMapper() throws IOException { mapDriver.withInput(new LongWritable(1), new Text( "b382c1c156dcbbd5b9317cb50f6a747b\t20130606000104000\tVh16OwT6OQNUXbj\tmozilla/4.0 (compatible; msie 6.0; windows nt 5.1; sv1; qqdownload 718)\t180.127.189.*\t80\t87\t1\ttFKETuqyMo1mjMp45SqfNX\t249b2c34247d400ef1cd3c6bfda4f12a\t\tmm_11402872_1272384_3182279\t300\t250\t1\t1\t0\t00fccc64a1ee2809348509b7ac2a97a5\t227\t3427\t282825712746\t0" )); mapDriver.withOutput(new Text("accessoires"), new LongWritable(1)); mapDriver.withOutput(new Text("de"), new LongWritable(1)); mapDriver.withOutput(new Text("auto"), new LongWritable(1)); mapDriver.runTest(); } }
package com.example.legia.mobileweb.DTO; import java.io.Serializable; public class User implements Serializable { private static final long serialVersionUID = 1L; private int iduser; private String username; private String password; private String ho_user; private String ten_user; private int sdt; private String email; private String dia_chi; private String thanh_pho; private String nuoc; private String zip_code; private String quan; private String phuong; private int id_the_tich_diem; private String loai_the; private int diem; public User() { super(); } public int getIduser() { return iduser; } public void setIduser(int iduser) { this.iduser = iduser; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getHo_user() { return ho_user; } public void setHo_user(String ho_user) { this.ho_user = ho_user; } public String getTen_user() { return ten_user; } public void setTen_user(String ten_user) { this.ten_user = ten_user; } public int getSdt() { return sdt; } public void setSdt(int sdt) { this.sdt = sdt; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getDia_chi() { return dia_chi; } public void setDia_chi(String dia_chi) { this.dia_chi = dia_chi; } public String getQuan() { return quan; } public void setQuan(String quan) { this.quan = quan; } public String getPhuong() { return phuong; } public void setPhuong(String phuong) { this.phuong = phuong; } public String getThanh_pho() { return thanh_pho; } public void setThanh_pho(String thanh_pho) { this.thanh_pho = thanh_pho; } public String getNuoc() { return nuoc; } public void setNuoc(String nuoc) { this.nuoc = nuoc; } public String getZip_code() { return zip_code; } public void setZip_code(String zip_code) { this.zip_code = zip_code; } public int getId_the_tich_diem() { return id_the_tich_diem; } public void setId_the_tich_diem(int id_the_tich_diem) { this.id_the_tich_diem = id_the_tich_diem; } public String getLoai_the() { return loai_the; } public void setLoai_the(String loai_the) { this.loai_the = loai_the; } public int getDiem() { return diem; } public void setDiem(int diem) { this.diem = diem; } }
package binaryTreeAndDivideConquer; import java.util.ArrayList; /*Binary Tree Inorder Traversal question: http://www.lintcode.com/en/problem/binary-tree-inorder-traversal/ answer: http://www.jiuzhang.com/solutions/binary-tree-inorder-traversal/ Given a binary tree, return the inorder traversal of its nodes' values. Example Given binary tree {1,#,2,3}, 1 \ 2 / 3 return [1,3,2]. Challenge Can you do it without recursion? */ //version 2: traverse public class BinaryTreeInorderTraversal2 { public static ArrayList<Integer> inorderTraversal(TreeNode root){ ArrayList<Integer> inorder = new ArrayList<Integer>(); if (root == null){ return inorder; } traverse(root, inorder); return inorder; } public static void traverse(TreeNode root, ArrayList<Integer> list){ if (root == null){ return; } traverse(root.left, list); list.add(root.value); traverse(root.right,list); } public static void main(String[] args) { // TODO Auto-generated method stub TreeNode r1 = new TreeNode(1); TreeNode r2 = new TreeNode(2); TreeNode r3 = new TreeNode(3); r1.left = null; r1.right = r2; r2.left = r3; r2.right = null; r3.left = null; r3.right = null; System.out.println(inorderTraversal(r1)); } }
package main.application; /** * Memento contains state of an object to be restored. * @author Jemish * */ public class Momento { private String state; /** * Parameterized Constructor. * @param state state to be stored */ public Momento(String state) { this.state = state; } /** * This is getter method. * @return state of an object */ public String getState() { return state; } }
package com.app.aztask.ui; import android.content.Intent; import android.location.Location; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.v4.app.Fragment; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import org.json.JSONException; import org.json.JSONObject; import com.app.aztask.R; import com.app.aztask.data.TaskCard; import com.app.aztask.net.TasksDownloaderWorker; import com.app.aztask.util.Util; public class TaskFragment extends Fragment { ArrayList<TaskCard> tasksList = new ArrayList<TaskCard>(); RecyclerView MyRecyclerView; AppCompatActivity mainActivity; public TaskFragment(AppCompatActivity mainActivity){ this.mainActivity=mainActivity; } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); //getActivity().setTitle("Tasks"); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_card, container, false); MyRecyclerView = (RecyclerView) view.findViewById(R.id.cardView); MyRecyclerView.setHasFixedSize(true); getTasksList(); FloatingActionButton fab = (FloatingActionButton) view.findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent=null; if (MainActivity.userRegistered()) { intent = new Intent(getContext(), CreateTaskActivity.class); } else { intent = new Intent(getContext(), UserRegisterationActivity.class); } startActivity(intent); } }); return view; } private void getTasksList(){ try { final JSONObject taskInfo = new JSONObject(); Location location=Util.getDeviceLocation(); try { if(location==null){ taskInfo.put("latitude",""+ MainActivity.getRegisteredUser().getDeviceInfo().getLatitude()); taskInfo.put("longitude",""+ MainActivity.getRegisteredUser().getDeviceInfo().getLongitude()); }else{ taskInfo.put("latitude",""+ location.getLatitude()); taskInfo.put("longitude",""+ location.getLongitude()); } } catch (JSONException e) { e.printStackTrace(); } new TasksDownloaderWorker(mainActivity,MyRecyclerView).execute(taskInfo.toString()); } catch (Exception e) { e.printStackTrace(); } } }
package dao; import dto.PersonnelContractDTO; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; /** * * @author Asus */ public class PersonnelContractDAO { public ArrayList<PersonnelContractDTO> getAllPersonnelContract(Connection connection, String emp_id) throws SQLException { Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery("SELECT wf.emp_id, wf.fname,wf.lname, d.name, cr.name, ct.contract_id, ct.contract_name, ct.period, ct.full_day, ct.short_leave, ce.date, ce.basic_salary FROM work_force wf, department d, cardre cr, contract ct, contract_employee ce WHERE (wf.emp_id=ce.emp_id) AND (wf.dept_id=d.dept_id) AND (wf.cardre_id=cr.cardre_id) AND (ct.contract_id=ce.contract_id) AND (ce.emp_id='" + emp_id + "');"); PersonnelContractDTO con = null; if (result.next()) { con = new PersonnelContractDTO(result.getString(1), result.getString(2) + " " + result.getString(3), result.getString(4), result.getString(5), result.getString(6), result.getString(7), result.getString(8), result.getString(9), result.getString(10), result.getString(11), result.getString(12), "", "", ""); } ResultSet result2 = statement.executeQuery("SELECT a.name, a.description, a.amount from allowance a where allowance_id IN (SELECT allowance_id from contract_allowance where contract_id=(SELECT contract_id FROM contract_employee WHERE contract_employee.emp_id='" + emp_id + "'))"); ArrayList<PersonnelContractDTO> list = new ArrayList<>(); while (result2.next()) { PersonnelContractDTO personnelContractDTO = new PersonnelContractDTO(); personnelContractDTO.setEmpid(con.getEmpid()); personnelContractDTO.setName(con.getName()); personnelContractDTO.setCadre(con.getCadre()); personnelContractDTO.setDept(con.getDept()); personnelContractDTO.setContractid(con.getContractid()); personnelContractDTO.setContractname(con.getContractname()); personnelContractDTO.setPeriod(con.getPeriod()); personnelContractDTO.setFullday(con.getFullday()); personnelContractDTO.setShortleave(con.getShortleave()); personnelContractDTO.setDate(con.getDate()); personnelContractDTO.setBasicsalary(con.getBasicsalary()); personnelContractDTO.setAllowancename(result2.getString(1)); personnelContractDTO.setAllowancedes(result2.getString(2)); personnelContractDTO.setAmount(result2.getString(3)); list.add(personnelContractDTO); } return list; } public ArrayList<PersonnelContractDTO> getAllSalaryDetails(Connection connection, String emp_id) throws SQLException { Statement statement = connection.createStatement(); ResultSet result = statement.executeQuery("SELECT wf.emp_id, wf.fname, wf.lname, ce.basic_salary FROM work_force wf, contract_employee ce where (wf.emp_id=ce.emp_id) AND (ce.emp_id='" + emp_id + "');"); PersonnelContractDTO a = new PersonnelContractDTO(); if (result.next()) { a.setEmpid(result.getString(1)); a.setName(result.getString(2)+" "+result.getString(3)); a.setBasicsalary(result.getString(4)); } ArrayList<PersonnelContractDTO> list= new ArrayList<>(); ResultSet result1 = statement.executeQuery("SELECT name, description, amount FROM allowance WHERE allowance_id IN (SELECT allowance_id FROM contract_allowance WHERE contract_id=(SELECT contract_id FROM contract_employee WHERE emp_id='" + emp_id + "'));"); while(result1.next()){ PersonnelContractDTO pContractDTO = new PersonnelContractDTO(); pContractDTO.setEmpid(a.getEmpid()); pContractDTO.setName(a.getName()); pContractDTO.setBasicsalary(a.getBasicsalary()); pContractDTO.setAllowancename(a.getAllowancename()); pContractDTO.setAllowancedes(a.getAllowancedes()); pContractDTO.setAmount(a.getAmount()); list.add(pContractDTO); System.out.println("89"); } return list; } }
package xdpm.nhom11.angrybirdsproject.xmlbird; import java.io.IOException; import java.util.ArrayList; import org.andengine.entity.IEntity; import org.andengine.util.SAXUtils; import org.andengine.util.level.EntityLoader; import org.andengine.util.level.simple.SimpleLevelEntityLoaderData; import org.andengine.util.level.simple.SimpleLevelLoader; import org.xml.sax.Attributes; import android.util.Log; import xdpm.nhom11.angrybirdsproject.bird.BlackBird; import xdpm.nhom11.angrybirdsproject.bird.BlueBird; import xdpm.nhom11.angrybirdsproject.bird.RedBird; import xdpm.nhom11.angrybirdsproject.bird.WhiteBird; import xdpm.nhom11.angrybirdsproject.bird.YellowBird; import xdpm.nhom11.angrybirdsproject.entities.Bird; public class DTOBird { public int finalscore; public String id; public float x; public float y; public DTOBird() { this.id = ""; this.x = 0; this.y = 0; this.finalscore = 0; } public Bird getBird() { if (id.equalsIgnoreCase("RED BIRD")) { return new RedBird(x, y, null); } else if (id.equalsIgnoreCase("YELLOW BIRD")) { return new YellowBird(x, y, null); } else if (id.equalsIgnoreCase("BLUE BIRD")) { return new BlueBird(x, y, null); } else if (id.equalsIgnoreCase("BLACK BIRD")) { return new BlackBird(x, y, null); } else if (id.equalsIgnoreCase("WHITE BIRD")) { return new WhiteBird(x, y, null); } return new RedBird(x, y, null); } }
package x.ctrl; import x.java.SourceCodeFileFormatter4JavaDefault; import x.xml.SourceCodeFileFormatter4XmlDefault; class SourceCodeFileFormatterFactory { public static SourceCodeFileFormatter get(KnownSourceFileType type, SourceCodeFile file) { switch (type) { case JAVA: return new SourceCodeFileFormatter4JavaDefault(file); case XML: return new SourceCodeFileFormatter4XmlDefault(); default: throw new AssertionError("201612170736"); } } }
import java.util.Scanner; class prog29 { public static void main(String args[]) { Scanner sc = new Scanner(System.in); int arr[][] = new int [3][3]; int i,j; int count_arr = 0; int count_ele = 0; System.out.println("Enter Elements : "); for(i=0; i<3; i++) { for(j=1; j<3; j++) { arr[i][j] = sc.nextInt(); count_ele++; } count_arr++; } System.out.println("1D array : "+count_arr+ "\nElements : "+count_ele); } }
package com.lera.vehicle.reservation.controller; import com.lera.vehicle.reservation.command.customer.AddCustomerObject; import com.lera.vehicle.reservation.command.customer.EditCustomerObject; import com.lera.vehicle.reservation.domain.customer.*; import com.lera.vehicle.reservation.service.customer.CustomerService; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; @Controller @SuppressWarnings("Duplicates") public class CustomerController { private CustomerService customerService; public CustomerController(CustomerService customerService) { this.customerService = customerService; } @GetMapping("/list_customers") public String listCustomers(Model model) { model.addAttribute("customers", customerService.listCustomers()); return "customers_list"; } @GetMapping("/customer/{id}") public String getCustomer(@PathVariable long id, Model model) { model.addAttribute("customer", customerService.getCustomerById(id)); return "customer"; } @GetMapping("/add_customer") public String addCustomer(Model model) { model.addAttribute("addCustomerObject", new AddCustomerObject()); return "add_customers"; } @PostMapping("/add_customer") public String addCustomerPost(@ModelAttribute AddCustomerObject addCustomerObject) { Licence licence = new Licence(); licence.setLicenceNo(addCustomerObject.getLicenceNo()); licence.setIssueDate(addCustomerObject.getLicenceIssueDate()); licence.setExpiryDate(addCustomerObject.getLicenceExpiryDate()); Passport passport = new Passport(); passport.setPassportNo(addCustomerObject.getPassportNo()); passport.setIssueDate(addCustomerObject.getPassportIssueDate()); passport.setExpiryDate(addCustomerObject.getPassportExpiryDate()); Insurance insurance = new Insurance(); insurance.setCompany(addCustomerObject.getInsuranceCompany()); insurance.setPolicyNo(addCustomerObject.getInsurancePolicyNo()); insurance.setExpiryDate(addCustomerObject.getInsuranceExpiryDate()); CreditCard creditCard = new CreditCard(); creditCard.setCreditCardNo(addCustomerObject.getCreditCardNo()); creditCard.setCreditCardType(addCustomerObject.getCreditCardType()); creditCard.setNameOnCard(addCustomerObject.getNameOnCard()); creditCard.setExpiryDate(addCustomerObject.getCreditCardExpiryDate()); Customer customer = new Customer(); customer.setFullName(addCustomerObject.getFullName()); customer.setDateOfBirth(addCustomerObject.getDateOfBirth()); customer.setAddress(addCustomerObject.getAddress()); customer.setMobilePhone(addCustomerObject.getMobilePhone()); customer.setEmail(addCustomerObject.getEmail()); customer.setCustomerType(addCustomerObject.getCustomerType()); customer.setCompanyName(addCustomerObject.getCompanyName()); customer.setLicence(licence); customer.setPassport(passport); customer.setInsurance(insurance); customer.setCreditCard(creditCard); customerService.createCustomer(customer); return "redirect:/list_customers"; } @GetMapping("/edit_customer/{id}") public String editCustomer(@PathVariable long id, Model model) { Customer customer = customerService.getCustomerById(id); EditCustomerObject editCustomerObject = new EditCustomerObject(); editCustomerObject.setFullName(customer.getFullName()); editCustomerObject.setDateOfBirth(customer.getDateOfBirth()); editCustomerObject.setAddress(customer.getAddress()); editCustomerObject.setMobilePhone(customer.getMobilePhone()); editCustomerObject.setCompanyName(customer.getCompanyName()); editCustomerObject.setEmail(customer.getEmail()); editCustomerObject.setCustomerType(customer.getCustomerType()); editCustomerObject.setLicenceNo(customer.getLicence().getLicenceNo()); editCustomerObject.setLicenceIssueDate(customer.getLicence().getIssueDate()); editCustomerObject.setLicenceExpiryDate(customer.getLicence().getExpiryDate()); editCustomerObject.setPassportNo(customer.getPassport().getPassportNo()); editCustomerObject.setPassportIssueDate(customer.getPassport().getIssueDate()); editCustomerObject.setPassportExpiryDate(customer.getPassport().getExpiryDate()); editCustomerObject.setInsurancePolicyNo(customer.getInsurance().getPolicyNo()); editCustomerObject.setInsuranceCompany(customer.getInsurance().getCompany()); editCustomerObject.setInsuranceExpiryDate(customer.getInsurance().getExpiryDate()); editCustomerObject.setCreditCardNo(customer.getCreditCard().getCreditCardNo()); editCustomerObject.setCreditCardType(customer.getCreditCard().getCreditCardType()); editCustomerObject.setNameOnCard(customer.getCreditCard().getNameOnCard()); editCustomerObject.setCreditCardExpiryDate(customer.getCreditCard().getExpiryDate()); model.addAttribute("editCustomerObject", editCustomerObject); model.addAttribute("customerId", id); return "customer_edit"; } @PostMapping("/edit_customer/{id}") public String editCustomerPost(@ModelAttribute EditCustomerObject editCustomerObject, @PathVariable long id) { Customer customer = customerService.getCustomerById(id); Licence licence = customer.getLicence(); licence.setLicenceNo(editCustomerObject.getLicenceNo()); licence.setIssueDate(editCustomerObject.getLicenceIssueDate()); licence.setExpiryDate(editCustomerObject.getLicenceExpiryDate()); Passport passport = customer.getPassport(); passport.setPassportNo(editCustomerObject.getPassportNo()); passport.setIssueDate(editCustomerObject.getPassportIssueDate()); passport.setExpiryDate(editCustomerObject.getPassportExpiryDate()); Insurance insurance = customer.getInsurance(); insurance.setCompany(editCustomerObject.getInsuranceCompany()); insurance.setPolicyNo(editCustomerObject.getInsurancePolicyNo()); insurance.setExpiryDate(editCustomerObject.getInsuranceExpiryDate()); CreditCard creditCard = customer.getCreditCard(); creditCard.setCreditCardNo(editCustomerObject.getCreditCardNo()); creditCard.setCreditCardType(editCustomerObject.getCreditCardType()); creditCard.setNameOnCard(editCustomerObject.getNameOnCard()); creditCard.setExpiryDate(editCustomerObject.getCreditCardExpiryDate()); customer.setFullName(editCustomerObject.getFullName()); customer.setDateOfBirth(editCustomerObject.getDateOfBirth()); customer.setAddress(editCustomerObject.getAddress()); customer.setMobilePhone(editCustomerObject.getMobilePhone()); customer.setEmail(editCustomerObject.getEmail()); customer.setCustomerType(editCustomerObject.getCustomerType()); customer.setCompanyName(editCustomerObject.getCompanyName()); customer.setLicence(licence); customer.setPassport(passport); customer.setInsurance(insurance); customer.setCreditCard(creditCard); customerService.editCustomer(customer); return "redirect:/list_customers"; } @GetMapping("/delete_customer/{id}") public String deleteCustomer(@PathVariable long id) { customerService.deleteCustomer(id); return "redirect:/list_customers"; } }
/* * 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 cyhserver2; import Logica.Clases; import Logica.CreadorLog; import Logica.CreadorStackObjeto; import Logica.Cronica; import Logica.Enemigo; import Logica.Habilidad; import Logica.Log; import Logica.NieblasTerritorios; import Logica.Personaje; import Logica.Posiciones; import Logica.StackObjeto; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.net.ServerSocket; import java.net.Socket; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author mmancora */ public class VentanaPrincipal extends javax.swing.JFrame implements Runnable { Cronica cronica; public VentanaPrincipal() { initComponents(); Thread hilo = new Thread(this); hilo.start(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jScrollPane1 = new javax.swing.JScrollPane(); areaLog = new javax.swing.JTextArea(); jButton1 = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE); areaLog.setColumns(20); areaLog.setRows(5); jScrollPane1.setViewportView(areaLog); jButton1.setText("Limpiar"); jButton1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton1ActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 388, Short.MAX_VALUE) .addContainerGap()) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jButton1) .addGap(147, 147, 147)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 248, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jButton1) .addContainerGap(11, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed this.areaLog.setText(""); }//GEN-LAST:event_jButton1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(VentanaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(VentanaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(VentanaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(VentanaPrincipal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new VentanaPrincipal().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextArea areaLog; private javax.swing.JButton jButton1; private javax.swing.JScrollPane jScrollPane1; // End of variables declaration//GEN-END:variables @Override public void run() { int port = 2000; try { ServerSocket server = new ServerSocket(port); areaLog.append("Conexión establecida (puerto: "+port+")\n"); while(true){ Socket socket = server.accept(); DataInputStream entrada = new DataInputStream(socket.getInputStream()); String mensaje = entrada.readUTF(); String [] desglose = mensaje.split(">>"); String [] argumentos; switch(desglose[0]){ case "cronica": areaLog.append("Personaje 1 pide Crónica inicial.\n"); crearCronica(); break; case "mover": argumentos = desglose[1].split(","); areaLog.append("Personaje "+argumentos[0]+" pide moverse a la posicion "+argumentos[1]+".\n"); moverPersonaje(argumentos[0],argumentos[1]); break; case "usarObjeto": argumentos = desglose[1].split(","); areaLog.append("Personaje "+argumentos[0]+" usa objeto "+argumentos[1]+".\n"); usarObjeto(argumentos[0],argumentos[1]); } } } catch (IOException ex) { areaLog.append("Servidor sin construir/n"); } } public void enviarCronica(){ Socket socket; try { socket = new Socket("192.168.1.83",2000); ObjectOutputStream salida = new ObjectOutputStream(socket.getOutputStream()); salida.writeObject(cronica); areaLog.append("Se envia la crónica inicial al personaje 1.\n"); socket.close(); } catch (IOException ex) { areaLog.append("No se pudo enviar la cronica al personaje 1.\n"); } } public void moverPersonaje(String idPersonaje, String nuevaPos){ int id = Integer.parseInt(idPersonaje); int pos = Posiciones.getIntPosicion(nuevaPos); for (int i=0;i<cronica.getPersonajes().size();i++){ if (cronica.getPersonajes().get(i).getId()==id){ cronica.getPersonajes().get(i).setPosicion(pos); Log log = CreadorLog.personajeSeMueve(cronica.getPersonajes().get(i).getNombre(), nuevaPos,true); cronica.getPersonajes().get(i).getLogs().add(log); break; } } enviarCronica(); } public void usarObjeto(String idPersonaje,String idObjeto){ int idPj = Integer.parseInt(idPersonaje); int idObj = Integer.parseInt(idObjeto); switch(idObj){ case CreadorStackObjeto.ORBE_CURATIVO: for (int i=0;i<cronica.getPersonajes().size();i++){ if (cronica.getPersonajes().get(i).getId()==idPj){ for(int j =0; j<cronica.getPersonajes().get(i).getObjetos().size();j++){ if (cronica.getPersonajes().get(i).getObjetos().get(j).getId()==idObj){ cronica.getPersonajes().get(i).getObjetos().get(j).setCantidad(cronica.getPersonajes().get(i).getObjetos().get(j).getCantidad() -1); Log log = CreadorLog.personajeUsaObjeto(cronica.getPersonajes().get(i).getNombre(), cronica.getPersonajes().get(i).getObjetos().get(j).getNombre(),true); cronica.getPersonajes().get(i).getLogs().add(log); break; } } cronica.getPersonajes().get(i).setSalud(cronica.getPersonajes().get(i).getSalud()+3); cronica.getPersonajes().get(i).setAcciones(cronica.getPersonajes().get(i).getAcciones()-1); } } break; default: break; } enviarCronica(); } public void crearCronica(){ ArrayList<Enemigo> enemigos = new ArrayList(); enemigos.add(new Enemigo("Wargo1",10,6,5,6,1,2,1,Posiciones.O2,10,0,"wargo.png")); ArrayList<Personaje> personajes = new ArrayList(); personajes.add(new Personaje(1,"Anaxímenes", Clases.COMBATIENTE,13,5,4,5,1,2,2,Posiciones.NE2,"emblema_combatiente.png")); personajes.add(new Personaje(2,"Caztiel",Clases.ACROBATA,16,2,4,2,7,1,2,Posiciones.N,"emblema_acrobata.png")); personajes.add(new Personaje(3,"Eilien",Clases.GUARDIA,16,2,4,2,7,1,2,Posiciones.N2,"emblema_guardia.png")); personajes.add(new Personaje(4,"Luna",Clases.ESTRATEGA,16,2,4,2,7,1,2,Posiciones.C,"emblema_estratega.png")); personajes.get(0).getObjetos().add(CreadorStackObjeto.crearStack(CreadorStackObjeto.ORBE_CURATIVO,9)); personajes.get(0).getObjetos().add(CreadorStackObjeto.crearStack(CreadorStackObjeto.PIEL_WARGO,3)); personajes.get(0).getObjetos().add(CreadorStackObjeto.crearStack(CreadorStackObjeto.PLASMA_WARGO,6)); personajes.get(0).getObjetos().add(CreadorStackObjeto.crearStack(CreadorStackObjeto.PROTEINA,1)); personajes.get(0).getObjetos().add(CreadorStackObjeto.crearStack(CreadorStackObjeto.CAL_VIVA,7)); personajes.get(0).getObjetos().add(CreadorStackObjeto.crearStack(CreadorStackObjeto.ANIMA_DE_LA_IRA,1)); cronica = new Cronica(personajes, enemigos, NieblasTerritorios.CODIGOBLANCO, NieblasTerritorios.TERRITORIO_BOSQUENEGRO); Log log = CreadorLog.crearBienvenida(cronica.getNiebla(), cronica.getTerritorio(), 1); personajes.get(0).getLogs().add(log); enviarCronica(); } }
package com.tencent.mm.plugin.appbrand.jsapi.a; import com.tencent.mm.ab.b; import com.tencent.mm.ipcinvoker.wx_extension.b$a; import com.tencent.mm.plugin.appbrand.jsapi.a; import com.tencent.mm.plugin.appbrand.page.p; import com.tencent.mm.protocal.c.bif; import com.tencent.mm.protocal.c.big; import com.tencent.mm.sdk.platformtools.x; import org.json.JSONObject; public final class g extends a { public static final int CTRL_INDEX = 205; public static final String NAME = "setUserAutoFillData"; public final void a(final p pVar, JSONObject jSONObject, final int i) { if (jSONObject == null) { x.e("MicroMsg.JsApiSetUserAutoFillData", "setUserAutoFillData data is invalid"); pVar.E(i, f("fail:data is invalid", null)); return; } String optString = jSONObject.optString("dataList"); x.i("MicroMsg.JsApiSetUserAutoFillData", "setUserAutoFillData appId:%s, dataList:%s", new Object[]{pVar.mAppId, optString}); b.a aVar = new b.a(); aVar.dIG = new bif(); aVar.dIH = new big(); aVar.uri = "/cgi-bin/mmbiz-bin/wxaapp/autofill/saveinfo"; aVar.dIF = 1180; aVar.dII = 0; aVar.dIJ = 0; b KT = aVar.KT(); bif bif = (bif) KT.dID.dIL; bif.bPS = r2; bif.rLM = optString; com.tencent.mm.ipcinvoker.wx_extension.b.a(KT, new b$a() { public final void a(int i, int i2, String str, b bVar) { if (i == 0 && i2 == 0 && bVar.dIE.dIL != null) { x.i("MicroMsg.JsApiSetUserAutoFillData", "setUserAutoFillData success"); pVar.E(i, g.this.f("ok", null)); return; } x.e("MicroMsg.JsApiSetUserAutoFillData", "setUserAutoFillData SaveUserAutoFillInfo cgi failed, errType = %d, errCode = %d, errMsg = %s, rr.resp = %s", new Object[]{Integer.valueOf(i), Integer.valueOf(i2), str, bVar.dIE.dIL}); pVar.E(i, g.this.f("fail:cgi fail", null)); } }); } }
package com.cskaoyan.bean; /** * @auther 芮狼Dan * @date 2019-05-19 18:02 */ public class FCountCheck { private String fCountCheckId; //成品计数质检编号 private String orderId; //订单编号 private String checkItem; //检验项目 private int sample; //样本总数 private int checkNumber; //抽检数 private int unqualify; //不合格数 private double qualify; //合格率 private String cdate; //检验时间 private String measureData; //实际测量数据 private String empId; //检验人ID private String empName; //检验人姓名 private String result; //检验结果 private String note; //备注 public FCountCheck() { } public FCountCheck(String fCountCheckId, String orderId, String checkItem, int sample, int checkNumber, int unqualify, double qualify, String cdate, String measureData, String empId, String empName, String result, String note) { this.fCountCheckId = fCountCheckId; this.orderId = orderId; this.checkItem = checkItem; this.sample = sample; this.checkNumber = checkNumber; this.unqualify = unqualify; this.qualify = qualify; this.cdate = cdate; this.measureData = measureData; this.empId = empId; this.empName = empName; this.result = result; this.note = note; } public String getfCountCheckId() { return fCountCheckId; } public void setfCountCheckId(String fCountCheckId) { this.fCountCheckId = fCountCheckId; } public String getOrderId() { return orderId; } public void setOrderId(String orderId) { this.orderId = orderId; } public String getCheckItem() { return checkItem; } public void setCheckItem(String checkItem) { this.checkItem = checkItem; } public int getSample() { return sample; } public void setSample(int sample) { this.sample = sample; } public int getCheckNumber() { return checkNumber; } public void setCheckNumber(int checkNumber) { this.checkNumber = checkNumber; } public int getUnqualify() { return unqualify; } public void setUnqualify(int unqualify) { this.unqualify = unqualify; } public double getQualify() { return qualify; } public void setQualify(double qualify) { this.qualify = qualify; } public String getCdate() { return cdate; } public void setCdate(String cdate) { this.cdate = cdate; } public String getMeasureData() { return measureData; } public void setMeasureData(String measureData) { this.measureData = measureData; } public String getEmpId() { return empId; } public void setEmpId(String empId) { this.empId = empId; } public String getEmpName() { return empName; } public void setEmpName(String empName) { this.empName = empName; } public String getResult() { return result; } public void setResult(String result) { this.result = result; } public String getNote() { return note; } public void setNote(String note) { this.note = note; } @Override public String toString() { return "FCountCheck{" + "fCountCheckId='" + fCountCheckId + '\'' + ", orderId='" + orderId + '\'' + ", checkItem='" + checkItem + '\'' + ", sample=" + sample + ", checkNumber=" + checkNumber + ", unqualify=" + unqualify + ", qualify=" + qualify + ", cdate='" + cdate + '\'' + ", measureData='" + measureData + '\'' + ", empId='" + empId + '\'' + ", empName='" + empName + '\'' + ", result='" + result + '\'' + ", note='" + note + '\'' + '}'; } }
package marchal.gabriel.bl; import marchal.gabriel.bl.Subasta.Subasta; import marchal.gabriel.bl.Usuario.Usuario; public class ColectorsBazarBL { private static Usuario usuarioLogeado; private static Subasta subastaObservado; public ColectorsBazarBL(){ } public void setUsuarioLogeado(Usuario usuario) throws Exception{ this.usuarioLogeado = usuario; } public Usuario getUsuarioLogeado(){ return usuarioLogeado; } public Subasta getSubastaObservado() { return subastaObservado; } public void setSubastaObservado(Subasta subastaObservado) { this.subastaObservado = subastaObservado; } }
package com.example.softwarePatterns; import org.springframework.data.repository.CrudRepository; public interface CartRepository extends CrudRepository<Cart, Integer>{ Cart findById(int id); }
import java.util.Arrays; import java.util.Scanner; public class SortArrayOfNumbers { //Write a program to enter a number n and n integer numbers and sort and print them. //Keep the numbers in array of integers: int[]. public static void main(String[] args){ //Read the input from the console, create an array with length "n",store the input in it ,sort //the array and print it Scanner reader = new Scanner(System.in); int n = reader.nextInt(); reader.nextLine(); int[] numbers = new int[n]; for (int i = 0; i < n; i++) { numbers[i] = reader.nextInt(); } Arrays.sort(numbers); for (int i : numbers) { System.out.print( i + " "); } } }
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.github.somi92.seecsk.gui; import com.github.somi92.seecsk.data.Sesija; import com.github.somi92.seecsk.server.ServerInstance; import com.github.somi92.seecskcommon.domain.Clan; import com.github.somi92.seecskcommon.domain.Grupa; import com.github.somi92.seecskcommon.domain.Prisustvo; import com.github.somi92.seecskcommon.domain.Trening; import com.github.somi92.seecskcommon.transfer.OdgovorObjekat; import com.github.somi92.seecskcommon.transfer.ZahtevObjekat; import com.github.somi92.seecskcommon.util.Ref; import com.github.somi92.seecskcommon.util.SistemskeOperacije; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import javax.swing.JOptionPane; import javax.swing.JSpinner; import javax.swing.SpinnerDateModel; /** * * @author milos */ public class FNewTraining extends javax.swing.JDialog { private Grupa grupa; private Trening trening; private boolean update; /** * Creates new form FNewTraining */ public FNewTraining(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); grupa = (Grupa) Sesija.vratiInstancu().vratiMapuSesije().get(Sesija.GRUPA); trening = (Trening) Sesija.vratiInstancu().vratiMapuSesije().get(Sesija.TRENING); Sesija.vratiInstancu().vratiMapuSesije().put(Sesija.GRUPA, null); Sesija.vratiInstancu().vratiMapuSesije().put(Sesija.TRENING, null); initForm(); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); jdccDatum = new datechooser.beans.DateChooserCombo(); jspnTime = new javax.swing.JSpinner(); jspnDuration = new javax.swing.JSpinner(); jScrollPane1 = new javax.swing.JScrollPane(); jtxtDesc = new javax.swing.JTextArea(); jLabel4 = new javax.swing.JLabel(); jbtnSave = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Dodaj novi trening"); jLabel1.setText("Datum:"); jLabel2.setText("Trajanje (min):"); jLabel3.setText("Opis treninga:"); jdccDatum.setFormat(2); jdccDatum.setLocale(new java.util.Locale("sr", "BA", "")); jspnTime.setModel(new javax.swing.SpinnerDateModel()); jspnDuration.setModel(new javax.swing.SpinnerNumberModel(0, 0, 360, 15)); jtxtDesc.setColumns(20); jtxtDesc.setLineWrap(true); jtxtDesc.setRows(5); jtxtDesc.setWrapStyleWord(true); jScrollPane1.setViewportView(jtxtDesc); jLabel4.setText("Vreme:"); jbtnSave.setText("Sačuvaj"); jbtnSave.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jbtnSaveActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jbtnSave, javax.swing.GroupLayout.PREFERRED_SIZE, 96, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jLabel3) .addGap(18, 18, 18) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jspnDuration, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jdccDatum, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jspnTime, javax.swing.GroupLayout.PREFERRED_SIZE, 112, javax.swing.GroupLayout.PREFERRED_SIZE))))) .addContainerGap(21, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(jdccDatum, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(12, 12, 12) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jspnTime, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel4)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(jspnDuration, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(jbtnSave, javax.swing.GroupLayout.PREFERRED_SIZE, 33, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(17, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void jbtnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jbtnSaveActionPerformed Date tempDate = (Date) jspnTime.getValue(); Calendar tempCal = Calendar.getInstance(); tempCal.setTime(tempDate); Calendar c = jdccDatum.getSelectedDate(); c.set(Calendar.HOUR_OF_DAY, tempCal.get(Calendar.HOUR_OF_DAY)); c.set(Calendar.MINUTE, tempCal.get(Calendar.MINUTE)); Date datum = new Date(c.getTimeInMillis()); int trajanjeMin = Integer.parseInt(jspnDuration.getValue().toString()); String opis = jtxtDesc.getText().trim(); if(!update) { trening = new Trening(); trening.setGrupa(grupa); Ref<Trening> treningRef = new Ref(trening); ZahtevObjekat zo = new ZahtevObjekat(); zo.setSistemskaOperacija(SistemskeOperacije.SO_KREIRAJ_TRENING); zo.setParametar(treningRef); ServerInstance.vratiInstancu().posaljiZahtev(zo); OdgovorObjekat oo = ServerInstance.vratiInstancu().vratiOdgovor(); treningRef = oo.getPodaci(); // KontrolerPL.kreirajTrening(treningRef); trening = treningRef.get(); } trening.setDatumVreme(datum); trening.setTrajanjeMin(trajanjeMin); trening.setOpisTreninga(opis); // if(!update) { // initAttendance(); // } Trening t = new Trening(); t.setIdTrening(trening.getIdTrening()); t.setDatumVreme(datum); t.setTrajanjeMin(trajanjeMin); t.setOpisTreninga(opis); t.setGrupa(grupa); if(!update) { initAttendance(); t.setPrisustva(trening.getPrisustva()); } ZahtevObjekat zo = new ZahtevObjekat(); zo.setSistemskaOperacija(SistemskeOperacije.SO_ZAPAMTI_TRENING); zo.setParametar(t); ServerInstance.vratiInstancu().posaljiZahtev(zo); OdgovorObjekat oo = ServerInstance.vratiInstancu().vratiOdgovor(); if(oo.getStatusOperacije()==0) { JOptionPane.showMessageDialog(this, "Trening je uspešno sačuvan."); } else { JOptionPane.showMessageDialog(this, "Greška! Trening nije uspešno sačuvan!"); } // KontrolerPL.sacuvajIliAzurirajTrening(trening); dispose(); }//GEN-LAST:event_jbtnSaveActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JButton jbtnSave; private datechooser.beans.DateChooserCombo jdccDatum; private javax.swing.JSpinner jspnDuration; private javax.swing.JSpinner jspnTime; private javax.swing.JTextArea jtxtDesc; // End of variables declaration//GEN-END:variables private void initForm() { SpinnerDateModel sdm = new SpinnerDateModel(); sdm.setCalendarField(Calendar.MINUTE); jspnTime.setModel(sdm); jspnTime.setEditor(new JSpinner.DateEditor(jspnTime, "HH:mm")); if(trening == null) { setTitle(grupa.getNaziv()+" - novi trening"); update = false; } else { setTitle(grupa.getNaziv()+" - izmena treninga"); update = true; jspnTime.setValue(trening.getDatumVreme()); Calendar c = Calendar.getInstance(); c.setTime(trening.getDatumVreme()); jdccDatum.setSelectedDate(c); jspnDuration.setValue(trening.getTrajanjeMin()); jtxtDesc.setText(trening.getOpisTreninga()); } } private void initAttendance() { List<Clan> clanovi = new ArrayList<>(); Clan clan = new Clan(); clan.setGrupa(grupa); clanovi.add(clan); Ref<List<Clan>> clanoviRef = new Ref(clanovi); List<String> kriterijumPretrage = new ArrayList<>(); kriterijumPretrage.add("grupa"); ZahtevObjekat zo = new ZahtevObjekat(); zo.setSistemskaOperacija(SistemskeOperacije.SO_PRONADJI_CLANOVE); zo.setKriterijumPretrage(kriterijumPretrage); zo.setUcitajListe(false); zo.setParametar(clanoviRef); ServerInstance.vratiInstancu().posaljiZahtev(zo); OdgovorObjekat oo = ServerInstance.vratiInstancu().vratiOdgovor(); clanoviRef = oo.getPodaci(); // KontrolerPL.pronadjiClanove(clanoviRef, kriterijumPretrage, false); clanovi = clanoviRef.get(); ArrayList<Prisustvo> prisustva = new ArrayList<>(); for(Clan c : clanovi) { Prisustvo p = new Prisustvo(true, 0, trening, c); prisustva.add(p); } trening.setPrisustva(prisustva); } }
package myUtilities; import java.awt.Graphics; import java.awt.Image; import java.awt.Rectangle; import java.awt.Toolkit; import logica.Game; public class RectangleImage extends Rectangle{ public Image img; public RectangleImage(String path, int x, int y, int imgWidth, int imgHeight) { super(x, y, imgWidth, imgHeight); try { img = Toolkit.getDefaultToolkit().getImage(this.getClass().getResource(path)); } catch (Exception e) { System.out.println("Image not found: "+ e.getMessage()); } } public void moveRight() { x += 5; } public void moveLeft() { x += -5; } public void moveDown() { y += 5; } public void moveUp() { y += -5; } }
/* * 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 impl; import adt.Deque; /** * * @author технодом */ public class LinkedListDeque <T> implements Deque<T> { private DoublyLinkedNode<T> front; private DoublyLinkedNode <T> back; private int size; public LinkedListDeque(){ front = null; back = null; size = 0; } @Override public void pushToFront(T value) { //push from stack DoublyLinkedNode <T> newItem = new DoublyLinkedNode(value); if (size == 0) { front = newItem; back = front; } else { newItem.setNext(front); front.setPrevious(newItem); front = newItem; } size++; } @Override public void pushToBack(T value) { DoublyLinkedNode<T> newObj = new DoublyLinkedNode(value); if(size == 0) { front = newObj; back = front; } else { back.setNext(newObj); newObj.setPrevious(back); back = newObj; } size++; } @Override public T popFromFront() throws Exception { if(size == 0) throw new Exception("Cannot pop from empty deque"); T result = front.getValue(); if(size == 1) { front = null; back= null; } else { DoublyLinkedNode current = front; current = current.getNext(); current.setPrevious(null); front = current; } size--; return result; } @Override public T popFromBack() throws Exception { if (size == 0) throw new Exception ("Cannot pop from empty deque"); T result = back.getValue(); if (size == 1) { front = null; back = null; } else { DoublyLinkedNode current = back; current = current.getPrevious(); current.setNext(null); back = current; } size--; return result; } @Override public int getSize() { return size; } @Override public void clear() { front = null; back = null; size = 0; } public String toString(){ String result="front[ "; DoublyLinkedNode<T> current = front; while(current != null){ result += current.getValue()+" "; current = current.getNext(); } return result+"]back"; } }
package testFunction; public class TestVarargs { static int sumvarargs(int... intArrays) { int sum, i; sum = 0; for(i = 0; i < intArrays.length; i++){ sum += intArrays[i]; } return (sum); } public static void main(String args[]) { int sum = 0; sum = sumvarargs(new int[]{10,15,16}); System.out.println("数字相加之和为:" + sum); } }
package se.kth.iv1350.pointofsale.view; import se.kth.iv1350.pointofsale.controller.Controller; import se.kth.iv1350.pointofsale.integration.ItemDTO; import se.kth.iv1350.pointofsale.integration.ItemID; import se.kth.iv1350.pointofsale.model.Amount; import java.io.IOException; import se.kth.iv1350.pointofsale.controller.OperationFailedException; import se.kth.iv1350.pointofsale.util.LogHandler; /** * This program has no view, instead, this class is a placeholder for the entire * view. */ public class View { private Controller controller; private ErrorMessageHandler errorMsgHandler = new ErrorMessageHandler(); private LogHandler logger; /** * Creates a new instance. * * @param controller The controller that is used for all operations. */ public View(Controller controller) throws IOException { this.controller = controller; controller.addSaleObserver(new TotalRevenueDisplay()); this.logger = new LogHandler(); } /** * Simulates a user input that generates calls to all system operations. */ public void sampleExcecution() { try { ItemID unavailableItemID = new ItemID("000004"); ItemID availableItemID = new ItemID("000002"); ItemID anotherAvailableItemID = new ItemID("000001"); ItemID oneMoreAvailableItemID = new ItemID("000000"); int tooLargePaidAmount = 500; int acceptablePaidAmount = 499; System.out.println("UNAVAILABLE ITEM ID:"); makeASale(unavailableItemID, acceptablePaidAmount); System.out.println("AVAILABLE ITEM ID, PAID AMOUNT BELOW 500 SEK:"); makeASale(availableItemID, acceptablePaidAmount); System.out.println("AVAILABLE ITEM ID, PAID AMOUNT ABOVE 500 SEK:"); makeASale(anotherAvailableItemID, tooLargePaidAmount); System.out.println("AVAILABLE ITEM ID, PAID AMOUNT BELOW 500 SEK:"); makeASale(oneMoreAvailableItemID, acceptablePaidAmount); } catch (Exception exc) { handleException("Failed to register, please try again", exc); } } private void makeASale(ItemID itemID, int paidAmount) { controller.startSale(); try { ItemDTO registeredItem = controller.registerItem(itemID); printRegisteredItemInfo(registeredItem); } catch (OperationFailedException exc) { handleException("This item is invalid.", exc); } controller.finishItemRegistration(); controller.pay(new Amount(paidAmount)); controller.calculateTotal(); try { controller.finishSale(); } catch(OperationFailedException exc) { handleException("Paid amount too large to register.", exc); } System.out.println("Amount to pay: " + controller.calculateTotal() + " SEK\n"); } private void printRegisteredItemInfo(ItemDTO registeredItem) { System.out.println("Registered item: " + registeredItem); //System.out.println("Running total: " + controller.getRunningTotal().toString()); } private void handleException (String uiMsg, Exception exc){ errorMsgHandler.showErrorMsg(uiMsg); logger.logException(exc); } }
import javax.swing.JFrame; import javax.swing.SwingUtilities; import java.io.File; import java.io.IOException; import javax.imageio.ImageIO; public class Runner { public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { JFrame frame = new JFrame("Power Grid"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); Interface panel = new Interface(); frame.add(panel); frame.setSize(panel.getWidth(), panel.getHeight()); try { frame.setIconImage(ImageIO.read(new File("assets/images/icon.png"))); } catch (IOException e) { System.out.println("Could not load icon!"); } // frame.pack(); // frame.setExtendedState(JFrame.MAXIMIZED_BOTH); // frame.setUndecorated(true); try { frame.setIconImage(ImageIO.read(new File("assets/images/icon.png"))); } catch (IOException e) { System.out.println("Could not load icon!"); } frame.setVisible(true); } }); } }
package com.tencent.mm.plugin.brandservice.ui.base; import android.graphics.Bitmap; import android.view.View; import android.widget.ImageView; import android.widget.TextView; import com.tencent.mm.ac.m; import com.tencent.mm.ac.m.a.a; import com.tencent.mm.ac.z; import com.tencent.mm.plugin.brandservice.b.c; import com.tencent.mm.sdk.platformtools.ah; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; public class BrandServiceSortView$b implements a { static Bitmap hqv = null; public View contentView; ImageView eCl; TextView eTm; public TextView hoc; ImageView hpA; View hpB; String iconUrl; String username; public BrandServiceSortView$b() { z.Ni().a(this); } public final void ave() { if (this.eCl != null) { Bitmap d = m.d(this.username, this.iconUrl, 0); if (d == null) { this.eCl.setImageResource(c.brand_default_head); } else if (bi.oW(this.username) || this.eCl.getTag() == null) { x.e("MicroMsg.BrandServiceSortView", "error in refreshAvatar, %s", new Object[]{this.username}); } else if (this.username.equals(this.eCl.getTag())) { this.eCl.setImageBitmap(d); } } } public final void kX(String str) { if (str != null && str.equals(this.username)) { ah.A(new 1(this)); } } }
package generatorRaderketen; /** * Created by Thomas on 1/11/2015. */ public class Route { private String delay,distanceToLoadingDock; private String centralId; public Route(String delay, String centralId,String distanceToLoadingDock) { this.delay = delay; this.distanceToLoadingDock = distanceToLoadingDock; this.centralId = centralId; } public String getDelay() { return delay; } public String getDistanceToLoadingDock() { return distanceToLoadingDock; } public String getCentralId() { return centralId; } @Override public String toString() { return "Route{" + "delay='" + delay + '\'' + ", distanceToLoadingDock='" + distanceToLoadingDock + '\'' + ", centralId='" + centralId + '\'' + '}'; } }
package net.iz44kpvp.kitpvp.Comandos; import org.bukkit.Bukkit; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import net.iz44kpvp.kitpvp.Sistemas.API; public class TogglePvP implements CommandExecutor { public boolean onCommand(final CommandSender sender, final Command cmd, final String label, final String[] args) { final Player p = (Player) sender; if (cmd.getName().equalsIgnoreCase("pvp")) { if (p.hasPermission("Ninho.staff")) { if (args.length == 0) { p.sendMessage(String.valueOf(String.valueOf(API.preffix)) + "§cSintaxe correta: /pvp (on/off)"); return true; } if (args[0].equalsIgnoreCase("on")) { Bukkit.getWorld("world").setPVP(true); Bukkit.broadcastMessage(String.valueOf(String.valueOf(API.preffix)) + "§aPvP Ativado"); } if (args[0].equalsIgnoreCase("off")) { Bukkit.getWorld("world").setPVP(false); Bukkit.broadcastMessage(String.valueOf(String.valueOf(API.preffix)) + "§cPvP Desativado"); } } else { p.sendMessage(API.semperm); } } return false; } }
package com.tencent.mm.g.a; public final class od$a { public long bJC = 0; }
/** * OpenKM, Open Document Management System (http://www.openkm.com) * Copyright (c) 2006-2015 Paco Avila & Josep Llort * * No bytes were intentionally harmed during the development of this application. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.openkm.frontend.client.bean; import java.util.List; import com.google.gwt.user.client.rpc.IsSerializable; /** * GWTPaginated * * @author jllort * */ @SuppressWarnings("unused") public class GWTPaginated implements IsSerializable { public static final int COL_NONE = 0; public static final int COL_TYPE = 1; public static final int COL_NAME = 2; public static final int COL_SIZE = 3; public static final int COL_DATE = 4; public static final int COL_AUTHOR = 5; public static final int COL_VERSION = 6; private int totalFolder = 0; private int totalDocuments = 0; private int totalMails = 0; private int total = 0; private boolean outOfRange = false; private int newOffset = 0; private GWTFolder fld = new GWTFolder(); // Used to do not get serialization error private GWTDocument doc = new GWTDocument(); // Used to do not get serialization error private GWTMail mail = new GWTMail(); // Used to do not get serialization error private List<Object> objects; public int getTotal() { return total; } public void setTotal(int total) { this.total = total; } public int getTotalFolder() { return totalFolder; } public void setTotalFolder(int totalFolder) { this.totalFolder = totalFolder; } public int getTotalDocuments() { return totalDocuments; } public void setTotalDocuments(int totalDocuments) { this.totalDocuments = totalDocuments; } public int getTotalMails() { return totalMails; } public void setTotalMails(int totalMails) { this.totalMails = totalMails; } public boolean isOutOfRange() { return outOfRange; } public void setOutOfRange(boolean outOfRange) { this.outOfRange = outOfRange; } public int getNewOffset() { return newOffset; } public void setNewOffset(int newOffset) { this.newOffset = newOffset; } public List<Object> getObjects() { return objects; } public void setObjects(List<Object> objects) { this.objects = objects; } }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.commerceservices.order.strategies.impl; import de.hybris.platform.commerceservices.order.CommerceQuoteAssignmentException; import de.hybris.platform.commerceservices.order.strategies.QuoteActionValidationStrategy; import de.hybris.platform.commerceservices.order.strategies.QuoteAssignmentValidationStrategy; import de.hybris.platform.core.model.order.QuoteModel; import de.hybris.platform.core.model.user.UserModel; import org.apache.commons.lang.StringUtils; /** * Default implementation of {@link QuoteActionValidationStrategy}. */ public class DefaultQuoteAssignmentValidationStrategy implements QuoteAssignmentValidationStrategy { @Override public void validateQuoteAssignment(final QuoteModel quote, final UserModel assignee, final UserModel assigner) { if (quote.getAssignee() != null && !StringUtils.equals(quote.getAssignee().getUid(), assignee.getUid())) { throw new CommerceQuoteAssignmentException( String.format("Assigner:%s is not authorized to assign Quote code:%s to assignee:%s. " + "Reasons: quote is already assigned", assigner.getUid(), quote.getCode(), assignee.getUid()), quote.getAssignee().getDisplayName()); } if (!StringUtils.equals(assignee.getUid(), assigner.getUid())) { throw new CommerceQuoteAssignmentException( String.format( "Assigner:%s is not authorized to assign Quote code:%s to assignee:%s. " + "Reasons: assignee & assigner are not the same", assigner.getUid(), quote.getCode(), assignee.getUid()), assignee.getDisplayName()); } } @Override public void validateQuoteUnassignment(final QuoteModel quote, final UserModel assigner) { if (quote.getAssignee() != null && !StringUtils.equals(quote.getAssignee().getUid(), assigner.getUid())) { throw new CommerceQuoteAssignmentException(String.format( "Assigner:%s is not authorized to unassign Quote code:%s. Reason: assignee & assigner are not the same", assigner.getUid(), quote.getCode()), quote.getAssignee().getDisplayName()); } } }
package com.mantouland.fakeelf.controller; import android.util.Log; import com.mantouland.atool.HTTPHelper; import com.mantouland.atool.callback.impl.JsonCallBack; import com.mantouland.fakeelf.bean.ListBean; import com.mantouland.fakeelf.bean.ListDetailBean; import com.mantouland.fakeelf.bean.LyricBean; import java.util.HashMap; /** * Created by asparaw on 2019/5/18. */ public class MusicLoader { //singleton private static class instanceHolder{ private static final MusicLoader instance = new MusicLoader(); } public static MusicLoader getInstance(){ return instanceHolder.instance; } private MusicLoader(){ //DO_NOTHING } private static final String TAG= "LOADER"; private static final String MOOD_LIST ="http://elf.egos.hosigus.com/getSongListID.php"; private static final String DETAIL="http://elf.egos.hosigus.com/music/playlist/detail/"; private static final String LRC="http://elf.egos.hosigus.com/lyric"; private ListBean listBean; private ListDetailBean listDetailBean; /** * following is * http_loader */ public void loadMood(String mood, final JsonCallBack jsonCallBack){ String path= MOOD_LIST; path=path+"?type="+mood; Log.d(TAG, "loadMood: "+path); HTTPHelper.getInstance().doJsonString(path, null, null, false, new JsonCallBack() { @Override public void onSuccess(Object jsonBean) { listBean=(ListBean) jsonBean; jsonCallBack.onSuccess(listBean); Log.d(TAG, "onSuccess: "+listBean.getStatus()); } }, ListBean.class); Log.d(TAG, "loadMood: "); } public void loadDetail(long id,final JsonCallBack jsonCallBack){ String path=DETAIL; HashMap<String,String> map=new HashMap(); map.put("id",String.valueOf(id) ); Log.d(TAG, "loadDetail: "+path); HTTPHelper.getInstance().doJsonString(path, map, null, false, new JsonCallBack() { @Override public void onSuccess(Object jsonBean) { listDetailBean=(ListDetailBean) jsonBean; jsonCallBack.onSuccess(listDetailBean); } }, ListDetailBean.class); } public LyricBean loadLyric(String id){ return null; } public void setList(ListBean listBean){ this.listBean=listBean; } /** * following is * data automachine */ private void toPlayList(){ } }
package com.jk.jkproject.ui.entity.pay; public class AppPayInfo { /** * msg : 成功 * code : 200 * data : {"pay_type":0,"ali":{"app_id":"2021001165604654","biz_content":"{\"body\":\"JK直播钻石购买\",\"out_trade_no\":\"2020110515561716826978559962337\",\"product_code\":\"QUICK_MSECURITY_PAY\",\"subject\":\"JK直播钻石购买\",\"total_amount\":\"0.01\"}","charset":"utf-8","format":"json","method":"alipay.trade.app.pay","notify_url":"http://www.baidu.com","sign":"Xrj+KqfroXvGhbKf2FR5320mo1CEea6DRl1GtxZN+8WqVnFav3jFNTw27bcz8/nfS1/SIjJZ9qOH+0hd9A34GCvAg0fQJZFaEv7m5b1Dj9IwHRQrGdWmvPqf7C1or8yeQ1wgM9qDJp+1ijn20Yx+Uf26aGv0uDO691Nicpm2Tw2yNVsu4GrkT18go4c8PNDuocWJsFt4jjqOFww0qr/tQeYUBVkAg+n/pvhTs+883mVYngt+50Jx5/6NXFc1UaWMnz3Q1/T8gPimBpWTroTOzwKpiEACxtBNnP5oyTJ82636OaAxLZ/2mzkjeySWSU24665BC6NXqSOzxA4veV3cTQ==","sign_type":"RSA2","timestamp":"2020-11-05 15:56:17","version":"1.0"}} */ private String msg; private Integer code; private DataBean data; public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } public DataBean getData() { return data; } public void setData(DataBean data) { this.data = data; } public static class DataBean { /** * pay_type : 0 * ali : {"app_id":"2021001165604654","biz_content":"{\"body\":\"JK直播钻石购买\",\"out_trade_no\":\"2020110515561716826978559962337\",\"product_code\":\"QUICK_MSECURITY_PAY\",\"subject\":\"JK直播钻石购买\",\"total_amount\":\"0.01\"}","charset":"utf-8","format":"json","method":"alipay.trade.app.pay","notify_url":"http://www.baidu.com","sign":"Xrj+KqfroXvGhbKf2FR5320mo1CEea6DRl1GtxZN+8WqVnFav3jFNTw27bcz8/nfS1/SIjJZ9qOH+0hd9A34GCvAg0fQJZFaEv7m5b1Dj9IwHRQrGdWmvPqf7C1or8yeQ1wgM9qDJp+1ijn20Yx+Uf26aGv0uDO691Nicpm2Tw2yNVsu4GrkT18go4c8PNDuocWJsFt4jjqOFww0qr/tQeYUBVkAg+n/pvhTs+883mVYngt+50Jx5/6NXFc1UaWMnz3Q1/T8gPimBpWTroTOzwKpiEACxtBNnP5oyTJ82636OaAxLZ/2mzkjeySWSU24665BC6NXqSOzxA4veV3cTQ==","sign_type":"RSA2","timestamp":"2020-11-05 15:56:17","version":"1.0"} */ private Integer pay_type; //0.支付宝 1.微信 private String ali; private WxBean wx; public Integer getPay_type() { return pay_type; } public void setPay_type(Integer pay_type) { this.pay_type = pay_type; } public String getAli() { return ali; } public void setAli(String ali) { this.ali = ali; } public WxBean getWx() { return wx; } public void setWx(WxBean wx) { this.wx = wx; } public static class WxBean { private String appid; private String noncestr; private String _package; private String partnerid; private String prepayid; private String sign; private long timestamp; public String getAppid() { return appid; } public void setAppid(String appid) { this.appid = appid; } public String getNoncestr() { return noncestr; } public void setNoncestr(String noncestr) { this.noncestr = noncestr; } public String get_package() { return _package; } public void set_package(String _package) { this._package = _package; } public String getPartnerid() { return partnerid; } public void setPartnerid(String partnerid) { this.partnerid = partnerid; } public String getPrepayid() { return prepayid; } public void setPrepayid(String prepayid) { this.prepayid = prepayid; } public String getSign() { return sign; } public void setSign(String sign) { this.sign = sign; } public long getTimestamp() { return timestamp; } public void setTimestamp(long timestamp) { this.timestamp = timestamp; } @Override public String toString() { return "WxBean{" + "appid='" + appid + '\'' + ", noncestr='" + noncestr + '\'' + ", _package='" + _package + '\'' + ", partnerid='" + partnerid + '\'' + ", prepayid='" + prepayid + '\'' + ", sign='" + sign + '\'' + ", timestamp=" + timestamp + '}'; } } } }
package com.funlib.file; import java.io.File; import java.io.Serializable; import java.util.List; import android.content.Context; import android.os.Handler; import android.os.Message; public class SDCardSearch { private Context mContext; private List<SDCardSearchModel> mSearchResults; private FileSearchListener mFileSearchListener; private Thread mSearchThread; public SDCardSearch(Context context , FileSearchListener l , List<SDCardSearchModel> result){ mContext = context; mSearchResults = result; mFileSearchListener = l; } private Handler mSearchHandler = new Handler(){ public void handleMessage(Message msg){ if(mFileSearchListener != null) mFileSearchListener.onFileSearchStatusChanged(msg.arg1, mSearchResults); } }; private void sendMessage(int status){ Message msg = Message.obtain(); msg.what = 0; msg.arg1 = status; mSearchHandler.sendMessage(msg); } public void startSearch(final String rootPath , final String suffix , final long sizeLimit , final boolean visitSubFolder){ mSearchThread = new Thread(){ public void run(){ sendMessage(SDCardSearchStatus.STATUS_SEARCH_BEGIN.ordinal()); //first from cache //delete not exist files from cache //update background searchFiles(rootPath , suffix ,sizeLimit , visitSubFolder); //save search result sendMessage(SDCardSearchStatus.STATUS_SEARCH_END.ordinal()); } }; mSearchThread.start(); } private void searchFiles(String rootPath, String suffix ,long sizeLimit, boolean visitSubFolder){ File rootFile = new File(rootPath); File[] files = rootFile.listFiles(); if(files == null) return; for (File file : files) { if(file.isHidden()) continue; if(file.isDirectory() && visitSubFolder){ searchFiles(file.getAbsolutePath() , suffix , sizeLimit,visitSubFolder); }else{ long size = file.length(); if(size < sizeLimit) continue; { String name = file.getName(); int index = name.lastIndexOf("."); if(index == -1) continue; String tmpSuffix = name.substring(index+1); if(suffix.toLowerCase().contains(tmpSuffix.toLowerCase()) == false) continue; } { SDCardSearchModel ssm = new SDCardSearchModel(); ssm.fileFullPath = file.getAbsolutePath(); ssm.fileName = file.getName(); ssm.fileSize = size; mSearchResults.add(ssm); sendMessage(SDCardSearchStatus.STATUS_SEARCH_ING.ordinal()); } } } } public void stop(){ if(mSearchThread != null){ mSearchThread.stop(); mSearchThread = null; } } public interface FileSearchListener{ public void onFileSearchStatusChanged(int status , List<SDCardSearchModel> result); } public enum SDCardSearchStatus{ STATUS_SEARCH_BEGIN, STATUS_SEARCH_ING, STATUS_SEARCH_END } public class SDCardSearchModel implements Serializable{ /** * */ private static final long serialVersionUID = 1L; public String fileName; public long fileSize; public String fileFullPath; public boolean selected; public int flag; } }
package colas.simulador; import DataPersistence.Data; import java.io.*; import java.util.ArrayList; import java.util.Scanner; public class Logic { private Scanner input = new Scanner(System.in); public ArrayList<BankTeller> cashier = new ArrayList<>(); ArrayList<Inventory> registry; public int numberQueue = 0; //con cuantas colas voy a trabajar public int totalQueueTime; // public int totalTransactionsTime; public int totalPeopleAttended = 0; Queue normalQueue = new Queue(); Queue specialQueue = new Queue(); Data data = new Data(); public void QueueQuantity() { do { System.out.println("¿Cuantas colas desea utilizar 1 o 2?"); numberQueue = input.nextInt(); switch (numberQueue) { case 1: numberQueue = 1; break; case 2: numberQueue = 2; break; default: numberQueue = 0; System.out.println("Los unicos valores validos son: 1 o 2"); break; } } while (numberQueue == 0); } public void createTellers() { System.out.println("¿Cuantas cajas desea crear?"); int tellerQ = input.nextInt(); for (int i = 0; i < tellerQ; i++) { BankTeller teller = new BankTeller(0); cashier.add(teller); } System.out.println("¿Cuantas cajas nuevas en su puesto desea crear"); int tellerSlow = input.nextInt(); for (int i = 0; i < tellerSlow; i++) { BankTeller teller = new BankTeller(1); //.................... cashier.add(teller); } } public void simulation() { if (cashier.size() == 0 || numberQueue == 0) { System.out.println("Ingrese el numero de colas y cajas"); } else { registry = data.loadD(); for (int i = 0; i < registry.size(); i++) { loadPeopleQueue(i); dequeuePeople(); //sacar personas de las colas para meterlas a las cajas if (i != 0) { calculateTimes(); } dequeuePeopleBankTeller(); print(i); } } totalAverage(); } private void print(int i) { int peopleInTeller = 0; System.out.println(""); System.out.println("**********************************Minuto " + "[" + i + "]*********************************"); System.out.println("--> Personas en cola normal: " + "(" + normalQueue.list.size() + ")"); System.out.println("--> Personas en cola especial: " + "(" + specialQueue.list.size() + ")"); for (int k = 0; k < cashier.size(); k++) { if (cashier.get(k).isBusy()) { peopleInTeller++; } } System.out.println("--> Personas en caja: " + "(" + peopleInTeller + ")"); System.out.println("--> Personas atendidas: " + "(" + totalPeopleAttended + ")"); System.out.println("*******************************************************************************"); } private void dequeuePeopleBankTeller() { //sacar gente de las cajas for (int i = 0; i < cashier.size(); i++) { if (cashier.get(i).isBusy()) { if (cashier.get(i).getTransactTime() == cashier.get(i).getAttentionTime()) { totalTransactionsTime += cashier.get(i).getAttentionTime(); //+= lo que ya tengo más lo que viene cashier.get(i).setBusy(false); cashier.get(i).setTransactTime(0); cashier.get(i).setAttentionTime(0); totalPeopleAttended = totalPeopleAttended + 1; } } } } private void calculateTimes() { //calcular tiempo if (!normalQueue.isEmpty()) { for (int i = 0; i < normalQueue.list.size(); i++) { normalQueue.list.get(i).timeIncrease(); } if (!specialQueue.isEmpty()) { for (int j = 0; j < specialQueue.list.size(); j++) { specialQueue.list.get(j).timeIncrease(); } } } for (int i = 0; i < cashier.size(); i++) { if (cashier.get(i).isBusy()) { cashier.get(i).increaseAttentionTime(); } } } public void dequeuePeople() { //sacar personas para que sean atendidas en la caja for (int i = 0; i < cashier.size(); i++) { if (!cashier.get(i).isBusy()) { if (!specialQueue.isEmpty()) { Person newPerson; newPerson = specialQueue.dequeue(); totalQueueTime += newPerson.getTime(); //TIMMMMMMME cashier.get(i).setBusy(true); //ahora la caja esta ocupada double randomValue = Math.random(); if (cashier.get(i).getNormalBankTeller() == 0) { cashier.get(i).setTransactTime(getMinutes(randomValue)); } else { cashier.get(i).setTransactTime(getMinutes(randomValue) + 1); } } if (!normalQueue.isEmpty() && !cashier.get(i).isBusy()) { Person newPerson; newPerson = normalQueue.dequeue(); totalQueueTime += newPerson.getTime(); cashier.get(i).setBusy(true); double randomValue = Math.random(); if (cashier.get(i).getNormalBankTeller() == 0) { cashier.get(i).setTransactTime(getMinutes(randomValue)); } else { cashier.get(i).setTransactTime(getMinutes(randomValue) + 1); } } } } } private int getMinutes(double value) { //arreglo int minutes = 0; if (value >= 0 || value <= 0.20) minutes = 1; if (value > 0.20 || value <= 0.40) minutes = 2; if (value > 0.40 || value <= 0.60) minutes = 3; if (value > 0.60 || value <= 0.80) minutes = 5; if (value > 0.80 || value <= 0.90) minutes = 8; if (value > 0.90 || value <= 0.95) minutes = 13; if (value > 0.95) minutes = 13 + (int) (13 * Math.random()); return minutes; } private void loadPeopleQueue(int i) { // 3 2 int normal = registry.get(i).getNormal(); int special = registry.get(i).getSpecial(); if (numberQueue == 1) { for (int l = 0; l < normal; l++) { Person normalPerson = new Person(); normalQueue.insert(normalPerson); } for (int k = 0; k < special; k++) { //se le debe de dar prioridad a esta Person specialPerson = new Person(); normalQueue.insert(specialPerson); } } if (numberQueue == 2) { for (int a = 0; a < normal; a++) { Person normalPerson = new Person(); normalQueue.insert(normalPerson); } for (int b = 0; b < special; b++) { Person specialPerson = new Person(); specialQueue.insert(specialPerson); } } } public void totalAverage() { //promedio de trámites de todas las personas int transact = 0; int totalWaitTransact = 0; int averageWait = 0; int peopleInTeller = 0; for (int k = 0; k < cashier.size(); k++) { if (cashier.get(k).isBusy()) { peopleInTeller++; } } averageWait = totalQueueTime / (specialQueue.list.size() + normalQueue.list.size() + totalPeopleAttended + peopleInTeller); System.out.println(""); System.out.println("Promedio de espera de todas las personas --> " + averageWait + " min"); System.out.println(""); transact = totalTransactionsTime / totalPeopleAttended; System.out.println("Tiempo promedio de tramites --> " + transact + " min"); System.out.println(""); totalWaitTransact = (totalQueueTime + totalTransactionsTime) / totalPeopleAttended; System.out.println("Tiempo promedio total --> " + totalWaitTransact + " min"); System.out.println(""); } }
package tk.imdt.aqi; public class Position { public double latitude = 0; public double longtitude = 0; public Position(double latitude, double longtitude){ this.latitude = latitude; this.longtitude = longtitude; } @Override public String toString() { return this.latitude + "," + this.longtitude; } }
package com.tencent.mm.plugin.wallet.balance.ui; import android.view.MenuItem; import android.view.MenuItem.OnMenuItemClickListener; import com.tencent.mm.ui.widget.a.d; import java.util.List; import org.json.JSONObject; class WalletBalanceManagerUI$3 implements OnMenuItemClickListener { final /* synthetic */ List jLK; final /* synthetic */ WalletBalanceManagerUI pax; final /* synthetic */ JSONObject paz; WalletBalanceManagerUI$3(WalletBalanceManagerUI walletBalanceManagerUI, JSONObject jSONObject, List list) { this.pax = walletBalanceManagerUI; this.paz = jSONObject; this.jLK = list; } public final boolean onMenuItemClick(MenuItem menuItem) { d dVar = new d(this.pax.mController.tml, 1, false); dVar.ofp = new 1(this); dVar.ofq = new 2(this); dVar.bXO(); return false; } }
package com.ricettadem.model; import java.util.Objects; public class AnnullaRicetta { private String pinCode; private String codiceFiscale; private String nre; public String getPinCode() { return pinCode; } public void setPinCode(String pinCode) { this.pinCode = pinCode; } public String getCodiceFiscale() { return codiceFiscale; } public void setCodiceFiscale(String codiceFiscale) { this.codiceFiscale = codiceFiscale; } public String getNre() { return nre; } public void setNre(String nre) { this.nre = nre; } @Override public int hashCode() { return Objects.hash(pinCode, codiceFiscale, nre); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } final AnnullaRicetta that = (AnnullaRicetta) obj; return Objects.equals(pinCode, that.pinCode) && Objects.equals(codiceFiscale, that.codiceFiscale) && Objects.equals(nre, that.nre); } @Override public String toString() { StringBuilder result = new StringBuilder(); result.append("{"); result.append("pinCode: " + pinCode); result.append(", codiceFiscale: " + codiceFiscale); result.append(", nre: " + nre); result.append("}"); return result.toString(); } }
package com.example.lkplaces.web.dto; import com.example.lkplaces.jpa.enums.EnumStatus; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.Setter; import lombok.ToString; @Getter @Setter @Builder @NoArgsConstructor @AllArgsConstructor @ToString @EqualsAndHashCode public class EventDto { private Integer id; private String label; private String description; private String startDate; private String endDate; private EnumStatus status; private Integer mapMarkerId; }
/* * Copyright (c) 2021. Alpha Coders */ package com.abhishek.Videogy.adapter; import android.app.AlertDialog; import android.content.ActivityNotFoundException; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.net.Uri; import android.os.Environment; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.PopupMenu; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.core.content.FileProvider; import androidx.recyclerview.widget.RecyclerView; import com.abhishek.Videogy.R; import com.bumptech.glide.Glide; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class SavedAdapter extends RecyclerView.Adapter<SavedAdapter.SavedHolder> { private final Context context; private List<File> list; public SavedAdapter(List<File> list, Context context) { this.list = list; this.context = context; } @NonNull @Override public SavedHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(context); View view = inflater.inflate(R.layout.downloads_completed_item, parent, false); return new SavedHolder(view); } @Override public void onBindViewHolder(@NonNull SavedHolder holder, final int position) { holder.name.setText(list.get(position).getName()); Glide.with(context) .load(list.get(position).getAbsoluteFile()) .into(holder.thumbnail); holder.thumbnail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(Intent.ACTION_VIEW); Uri fileUri = FileProvider.getUriForFile(context, "com.abhishek.Videogy.fileprovider", list.get(position)); intent.setDataAndType(fileUri, "video/*"); intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); context.startActivity(intent); } }); holder.menu.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { popUp(view, list.get(position)); } }); } private void popUp(View view, final File f) { final PopupMenu popup = new PopupMenu(context.getApplicationContext(), view); popup.getMenuInflater().inflate(R.menu.download_menu, popup.getMenu()); popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { int i = item.getItemId(); if (i == R.id.download_delete) { new AlertDialog.Builder(context) .setMessage("Are you sure you want to delete?") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (f.delete()) { updateList(); } } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //nada dialog.dismiss(); } }) .create() .show(); return true; } else if (i == R.id.download_share) { File file = new File(Environment.getExternalStoragePublicDirectory(context.getResources().getString(R.string.app_name)), f.getName()); Uri fileUri = FileProvider.getUriForFile(context, "com.abhishek.Videogy.fileprovider", file); StringBuilder msg = new StringBuilder(); msg.append(context.getResources().getString(R.string.msg_share)); msg.append("\n"); msg.append(context.getResources().getString(R.string.app_link) + context.getResources().getString(R.string.app_name)); if (fileUri != null) { Intent shareIntent = new Intent(); shareIntent.setAction(Intent.ACTION_SEND); shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); // temp permission for receiving app to read this file shareIntent.setType("*/*"); shareIntent.putExtra(Intent.EXTRA_TEXT, msg.toString()); shareIntent.putExtra(Intent.EXTRA_STREAM, fileUri); try { context.startActivity(Intent.createChooser(shareIntent, "Share via")); } catch (ActivityNotFoundException e) { Toast.makeText(context.getApplicationContext(), "No App Available", Toast.LENGTH_SHORT).show(); } } return true; } else { return onMenuItemClick(item); } } }); popup.show(); } public void updateList() { File videoFile = new File(Environment.getExternalStoragePublicDirectory(context.getResources().getString(R.string.app_name)).getAbsolutePath()); if (videoFile.exists()) { List<File> nonExistentFiles = new ArrayList<>(); nonExistentFiles.addAll(Arrays.asList(videoFile.listFiles())); this.list = nonExistentFiles; notifyDataSetChanged(); } } @Override public int getItemCount() { return list.size(); } public static class SavedHolder extends RecyclerView.ViewHolder { private final TextView name; private final ImageView thumbnail; private final ImageView menu; public SavedHolder(@NonNull View itemView) { super(itemView); name = itemView.findViewById(R.id.downloadCompletedName); thumbnail = itemView.findViewById(R.id.downloadThumnail); menu = itemView.findViewById(R.id.download_menu); } } }
package com.yinghai.a24divine_user.module.login.findpassword; import android.content.Intent; import android.os.Bundle; import android.os.CountDownTimer; import android.text.TextUtils; import android.view.View; import android.view.animation.Animation; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.example.fansonlib.utils.SharePreferenceHelper; import com.example.fansonlib.utils.ShowToast; import com.yinghai.a24divine_user.R; import com.yinghai.a24divine_user.animation.CubeAnimation; import com.yinghai.a24divine_user.base.MyBaseMvpFragment; import com.yinghai.a24divine_user.constant.ConFragment; import com.yinghai.a24divine_user.constant.ConstantPreference; import com.yinghai.a24divine_user.function.internationalCode.InternationalCodeActivity; import com.yinghai.a24divine_user.module.login.state.LoginState; import com.yinghai.a24divine_user.module.login.state.LoginStateManager; import com.yinghai.a24divine_user.module.main.MainActivity; import com.yinghai.a24divine_user.widget.DrawableEditText; import static com.youth.banner.BannerConfig.DURATION; /** * Created by chenjianrun on 2017/12/19. * */ public class FindPasswordFragment extends MyBaseMvpFragment<FindPasswordPresenter> implements ContractFindPassword.IRegisterView{ private static final int REQUEST_AREA_CODE = 746; public static final int PASSWORD_COUNT = 6; public static final int TYPE_REGISTER = 0; public static final int TYPE_FIND_PASSWORD = 1; private int mType = TYPE_REGISTER; private DrawableEditText mEtTel; private DrawableEditText mEtVerifyCode; private DrawableEditText mEtPassword; private DrawableEditText mEtPasswordAgain; private TextView mTvCountryCode; private Button mBtnGetVerifyCode; private Button mBtnConfirm; // 获取验证码计时器 private CountDownTimer mCountDownTimer; private ImageView mIVBack; public static FindPasswordFragment newInstance(int type){ FindPasswordFragment registerFragment = new FindPasswordFragment(); Bundle bundle = new Bundle(); bundle.putInt("type",type); registerFragment.setArguments(bundle); return registerFragment; } @Override protected void initToolbarTitle() { TextView tv_title = findMyViewId(R.id.tv_title_toolbar); if (mType == TYPE_REGISTER) { tv_title.setText(getString(R.string.register)); }else{ tv_title.setText(getString(R.string.find_password)); } } @Override public Animation onCreateAnimation(int transit, boolean enter, int nextAnim) { if (isDestroyView){ return CubeAnimation.create(CubeAnimation.RIGHT, enter, DURATION); } if (enter) { return CubeAnimation.create(CubeAnimation.LEFT, enter, DURATION); } else { return CubeAnimation.create(CubeAnimation.LEFT, enter, DURATION); } } @Override protected FindPasswordPresenter createPresenter() { return new FindPasswordPresenter(this,hostActivity); } @Override protected int getLayoutId() { return R.layout.fragment_register; } @Override protected View initView(View view, Bundle bundle) { mEtTel = findMyViewId(R.id.et_phone); mEtVerifyCode = findMyViewId(R.id.et_verify_code); mEtPassword = findMyViewId(R.id.et_password); mEtPasswordAgain = findMyViewId(R.id.et_password_again); mBtnConfirm = findMyViewId(R.id.btn_confirm); mBtnGetVerifyCode = findMyViewId(R.id.btn_get_verify_code); mTvCountryCode = findMyViewId(R.id.tv_country_code); mIVBack = findMyViewId(R.id.btn_back_toolbar); return super.initView(view, bundle); } @Override protected void initData() { if (getArguments() != null) { mType = getArguments().getInt("type"); } if (mType == TYPE_REGISTER) { ((LinearLayout)findMyViewId(R.id.linear_password)).setVisibility(View.GONE); ((LinearLayout)findMyViewId(R.id.linear_password_again)).setVisibility(View.GONE); } } @Override protected void listenEvent() { super.listenEvent(); mBtnConfirm.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mType == TYPE_REGISTER) { mPresenter.register(); }else{ mPresenter.findPassword(); } } }); mBtnGetVerifyCode.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mBtnGetVerifyCode.setEnabled(false); mPresenter.sendVerifyCode(mType); } }); mTvCountryCode.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(hostActivity, InternationalCodeActivity.class); startActivityForResult(intent, REQUEST_AREA_CODE); } }); mIVBack.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onBackClick(); } }); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_AREA_CODE && resultCode == InternationalCodeActivity.RESULT_CODE) { mTvCountryCode.setText(data.getStringExtra(InternationalCodeActivity.AREA_CODE)); } } @Override public void onGetVerifyCodeSuccess() { startCountTimer(); } @Override public void onGetdVerifyCodeFailure(String errMsg) { mBtnGetVerifyCode.setEnabled(true); ShowToast.singleShort(errMsg); } @Override public void onRegisterSuccess(boolean isHasPassword) { if (isHasPassword) { SharePreferenceHelper.putBoolean(ConstantPreference.B_USER_LOGIN,true); SharePreferenceHelper.apply(); stopCountTimer(); //状态模式,设置为已登陆 LoginStateManager.getInstance().setState(new LoginState()); startMyActivity(MainActivity.class); hostActivity.finish(); }else{ // 设置密码 mFragmentListener.onFragment(ConFragment.SET_PASSWORD); } } @Override public void onRegisterFailure(String errMsg) { ShowToast.singleLong(errMsg); } @Override public void onFindPasswordSuccess() { if (mType == TYPE_FIND_PASSWORD) { // 保存密码 String password = mEtPassword.getText().toString().trim(); String tel = mEtTel.getText().toString().trim(); SharePreferenceHelper.putString(ConstantPreference.S_PHONE,tel); SharePreferenceHelper.putString(ConstantPreference.S_PASSWORD,password); SharePreferenceHelper.apply(); } stopCountTimer(); ShowToast.singleLong(getString(R.string.setting_successful)); mFragmentListener.onFragment(ConFragment.FIND_PASSWORD_SUCCESS); } @Override public void onFindPasswordFailure(String errMsg) { ShowToast.singleLong(errMsg); } @Override public String getCountryCode() { return mTvCountryCode.getText().toString().replace("+","").trim(); } @Override public String getTelNo() { String telNo = mEtTel.getText().toString().trim(); String countryCode = getCountryCode(); if (TextUtils.isEmpty(telNo)) { mEtTel.setShakeAnimation(); ShowToast.singleLong(getString(R.string.please_input_tel)); return null; } if (countryCode.equals("86") && telNo.length() != 11){ mEtTel.setShakeAnimation(); ShowToast.singleLong(getString(R.string.enter_correct_phone)); return null; } if (countryCode.equals("853") && telNo.length() != 8){ mEtTel.setShakeAnimation(); ShowToast.singleLong(getString(R.string.enter_correct_phone)); return null; } if (countryCode.equals("852") && telNo.length() != 8){ mEtTel.setShakeAnimation(); ShowToast.singleLong(getString(R.string.enter_correct_phone)); return null; } return telNo; } @Override public String getPassword() { String password = mEtPassword.getText().toString().trim(); if (TextUtils.isEmpty(password)) { mEtPassword.setShakeAnimation(); ShowToast.singleShort(getString(R.string.login_input_word)); return null; } if (password.length() < PASSWORD_COUNT) { mEtPassword.setShakeAnimation(); ShowToast.singleShort(getString(R.string.hint_set_password)); return null; } return password; } @Override public String getVerifyCode() { String verifyCode = mEtVerifyCode.getText().toString().trim(); if (TextUtils.isEmpty(verifyCode)) { mEtVerifyCode.setShakeAnimation(); ShowToast.singleShort(getString(R.string.string_input_code)); return null; } return verifyCode; } @Override public boolean isRepeatPassword() { String password = mEtPassword.getText().toString().trim(); String passwordAgain = mEtPasswordAgain.getText().toString().trim(); if (TextUtils.isEmpty(passwordAgain)) { mEtPasswordAgain.setShakeAnimation(); ShowToast.singleShort(getString(R.string.please_confirm_password)); return false; } if (!TextUtils.equals(password,passwordAgain)) { mEtPasswordAgain.setShakeAnimation(); mEtPassword.setShakeAnimation(); ShowToast.singleShort(getString(R.string.the_password_different)); return false; } return true; } @Override public void setGetVerifyCodeEnable(boolean enable) { mBtnGetVerifyCode.setEnabled(enable); } /** * 开启计时器 */ private void startCountTimer(){ if (mCountDownTimer == null) { mCountDownTimer = new CountDownTimer(60000, 1000) { @Override public void onTick(long millisUntilFinished) { mBtnGetVerifyCode.setText(millisUntilFinished / 1000 + getString(R.string.secs_later)); } @Override public void onFinish() { mCountDownTimer = null; mBtnGetVerifyCode.setEnabled(true); mBtnGetVerifyCode.setText(hostActivity.getString(R.string.login_btn_get_verify_code)); } }.start(); } } /** * 停止计时器 */ private void stopCountTimer(){ if (mCountDownTimer != null) { mCountDownTimer.cancel(); mCountDownTimer = null; } } @Override public void onDestroy() { super.onDestroy(); stopCountTimer(); } }
package q0213_dp_HouseRobber; import java.util.Arrays; public class HouseRobber2 { /** 你是一个专业的小偷,计划偷窃沿街的房屋,每间房内都藏有一定的现金。这个地方所有的房屋都围成一圈,这意味着第一个房屋和最后一个房屋是紧挨着的。 同时,相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警。 给定一个代表每个房屋存放金额的非负整数数组,计算你在不触动警报装置的情况下,能够偷窃到的最高金额。 示例 1: 输入: [2,3,2] 输出: 3 解释: 你不能先偷窃 1 号房屋(金额 = 2),然后偷窃 3 号房屋(金额 = 2), 因为他们是相邻的。 示例 2: 输入: [1,2,3,1] 输出: 4 解释: 你可以先偷窃 1 号房屋(金额 = 1),然后偷窃 3 号房屋(金额 = 3)。   偷窃到的最高金额 = 1 + 3 = 4 。 */ public static int rob(int[] nums) { if(nums.length == 0) return 0; if(nums.length == 1) return nums[0]; return Math.max(robHelper(Arrays.copyOfRange(nums, 0, nums.length - 1)), robHelper(Arrays.copyOfRange(nums, 1, nums.length))); } public static int robHelper(int[] nums){ int pre = 0; int cur = 0; for(int i=0; i<nums.length; i++){ int tmp = cur; cur = Math.max(pre+nums[i], cur); pre = tmp; } return cur; } public static void main(String[] args) { int[] nums = {2,7,9,3,1}; int result = rob(nums); System.out.println(result); } }
package com.stark; import com.stark.entity.User; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import java.util.Date; /** * Created by Stark on 2018/4/13. */ public class App { public static void main(String[] args) { final Configuration configuration = new Configuration().configure(); final SessionFactory factory = configuration.buildSessionFactory(); Session session = factory.openSession(); User user = session.get(User.class, 1); User user2 = session.get(User.class, 1); System.out.println(user); System.out.println(user2); Session session2 = factory.openSession(); User user3 = session2.get(User.class, 1); System.out.println(user3); session.close(); session2.close(); factory.close(); } }
package pl.todoapplication.entity; import javax.persistence.*; import java.util.Date; // nazwa tabeli to TODO_ENTITY @Entity(name = "Todo") public class TodoEntity { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @Column(nullable = false) private String text; private boolean completed; @Temporal(TemporalType.DATE) @Column(nullable = false) private Date createDate; @Temporal(TemporalType.DATE) @Column(nullable = true) private Date completeDate; @ManyToOne @JoinColumn(name = "user_id") private UserEntity user; public TodoEntity() { } public TodoEntity(String text) { this.text = text; this.createDate = new Date(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getText() { return text; } public void setText(String text) { this.text = text; } public boolean isCompleted() { return completed; } public void setCompleted(boolean completed) { this.completed = completed; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public Date getCompleteDate() { return completeDate; } public void setCompleteDate(Date completeDate) { this.completeDate = completeDate; } public UserEntity getUser() { return user; } public void setUser(UserEntity user) { this.user = user; } }
package com.paisheng.instagme.widget.dialog; import android.app.AlertDialog; import android.content.Context; import android.os.Bundle; import android.text.TextUtils; import android.view.Gravity; import android.view.View; import android.widget.Button; import android.widget.TextView; import com.paisheng.instagme.R; import java.util.concurrent.TimeUnit; import io.reactivex.Observable; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.annotations.NonNull; import io.reactivex.functions.Action; import io.reactivex.functions.Consumer; /** * <br> ClassName: SecondTipDialog * <br> Description: 带有确定与取消按钮的弹窗 * <br> * <br> Author: yexiaochuan * <br> Date: 2017/8/21 16:12 */ public class SecondTipDialog extends AlertDialog{ private boolean confirmFlag; private boolean cancelFlag; public SecondTipDialog(Context context) { super(context); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.view_dialog_tips_layout); } /** *<br> Description: 初始化 *<br> Author: yexiaochuan *<br> Date: 2017/8/21 17:20 * @param isCanCancel * 是否可取消 * @return */ public SecondTipDialog init(boolean isCanCancel) { setCancelable(isCanCancel); setCanceledOnTouchOutside(isCanCancel); show(); setOnClickListener(null); return this; } /** *<br> Description: 设置标题 *<br> Author: yexiaochuan *<br> Date: 2017/8/21 17:21 * @param title * 标题 * @return */ public SecondTipDialog setDialogTitle(CharSequence title) { if (TextUtils.isEmpty(title)) { return this; } TextView txtTitle = (TextView) findViewById(R.id.txtTitle); txtTitle.setVisibility(View.VISIBLE); txtTitle.setText(title); return this; } /** *<br> Description: 设置内容 *<br> Author: yexiaochuan *<br> Date: 2017/8/21 17:21 * @param content * 内容 * @return */ public SecondTipDialog setContent(CharSequence content) { setContent(content,Gravity.CENTER); return this; } /** *<br> Description: 设置内容 *<br> Author: yexiaochuan *<br> Date: 2017/8/21 17:58 * @param content * 内容 * @param gravity * 内容布局方向 * @return */ public SecondTipDialog setContent(CharSequence content, int gravity) { if (TextUtils.isEmpty(content)) { return this; } TextView txtMessage = (TextView) findViewById(R.id.txtMessage); txtMessage.setGravity(gravity); txtMessage.setTextColor(0xFF212121); txtMessage.setText(content); txtMessage.setVisibility(View.VISIBLE); return this; } /** *<br> Description: 设置确定按钮 *<br> Author: yexiaochuan *<br> Date: 2017/8/21 17:58 * @param text * 按钮文本 * @return */ public SecondTipDialog setConfirm(CharSequence text) { setConfirm(text,0); return this; } /** *<br> Description: 设置确定按钮,倒计时 *<br> Author: yexiaochuan *<br> Date: 2017/8/21 17:59 * @param text * 按钮文本 * @param time * 倒计时时间 * @return */ public SecondTipDialog setConfirm(CharSequence text, int time) { if (TextUtils.isEmpty(text)) { confirmFlag = false; return this; } confirmFlag = true; Button confirmBtn = (Button) findViewById(R.id.btnOk); confirmBtn.setVisibility(View.VISIBLE); confirmBtn.setText(text); if (time > 0) { setCutDownFunction(confirmBtn, text, time); } setBtnBackground(); return this; } /** *<br> Description: 设置倒计时功能 *<br> Author: yexiaochuan *<br> Date: 2017/8/21 17:59 */ private SecondTipDialog setCutDownFunction(final Button confirmBtn, final CharSequence text, final int time) { confirmBtn.setText(text + "(" + time + ")"); confirmBtn.setEnabled(false); Observable.interval(1, 1, TimeUnit.SECONDS) .take(time) .observeOn(AndroidSchedulers.mainThread()) .subscribe(new Consumer<Long>() { @Override public void accept(@NonNull Long aLong) throws Exception { int count = (int) (time - aLong - 1); if (count > 0) { confirmBtn.setText(text + "(" + count + ")"); } } }, new Consumer<Throwable>() { @Override public void accept(@NonNull Throwable throwable) throws Exception { } }, new Action() { @Override public void run() throws Exception { confirmBtn.setText(text); confirmBtn.setEnabled(true); } }); return this; } /** *<br> Description: 设置取消按钮 *<br> Author: yexiaochuan *<br> Date: 2017/8/21 17:59 * @param text * 按钮文本 * @return */ public SecondTipDialog setCancel(CharSequence text) { if (TextUtils.isEmpty(text)) { cancelFlag = false; return this; } cancelFlag = true; TextView cancelBtn = (TextView) findViewById(R.id.btnCancel); cancelBtn.setText(text); cancelBtn.setVisibility(View.VISIBLE); cancelBtn.setTextColor(0xFF212121); setBtnBackground(); return this; } /** *<br> Description: 设置按钮背景,适配窗口圆角 *<br> Author: yexiaochuan *<br> Date: 2017/8/21 18:00 */ private void setBtnBackground() { if (cancelFlag && confirmFlag) { findViewById(R.id.btnCancel).setBackgroundResource(R.drawable.bg_bottom_left_rounded_box_selector); findViewById(R.id.btnOk).setBackgroundResource(R.drawable.bg_bottom_right_rounded_box_selector); return; } if (cancelFlag) { findViewById(R.id.btnCancel).setBackgroundResource(R.drawable.bg_bottom_rounded_box_selector); } if (confirmFlag) { findViewById(R.id.btnOk).setBackgroundResource(R.drawable.bg_bottom_rounded_box_selector); } } /** *<br> Description: 设置按钮点击事件 *<br> Author: yexiaochuan *<br> Date: 2017/8/21 18:00 */ public SecondTipDialog setOnClickListener(final OnConfirmListener listener) { findViewById(R.id.btnCancel).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); if (listener != null) { listener.clickCancel(); } } }); findViewById(R.id.btnOk).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); if (listener != null) { listener.clickConfirm(); } } }); return this; } public interface OnConfirmListener { void clickConfirm(); void clickCancel(); } /** * <br> ClassName: DialogUtil * <br> Description: OnConfirmListener简单实例 * <br> * <br> Author: 谢文良 * <br> Date: 2017/8/22 10:09 */ public static class SimpleOnConfirmListener implements OnConfirmListener { @Override public void clickConfirm() { } @Override public void clickCancel() { } } }
package com.elasticsearch.elasticsearch.repository; import com.elasticsearch.elasticsearch.model.Book; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.elasticsearch.repository.ElasticsearchRepository; import org.springframework.stereotype.Repository; import java.util.List; @Repository public interface BookRepository extends ElasticsearchRepository<Book, Integer> { // // Page<Book> findByAuthor(String author, Pageable pageable); // // List<Book> findByTitle(String title); // Book findOne(int id); }
package com.app.config; import java.util.HashMap; import java.util.Map; import org.apache.kafka.clients.producer.ProducerConfig; import org.apache.kafka.common.serialization.StringSerializer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.kafka.core.DefaultKafkaProducerFactory; import org.springframework.kafka.core.KafkaTemplate; import org.springframework.kafka.core.ProducerFactory; import org.springframework.kafka.support.serializer.JsonSerializer; import com.app.model.User; //@Configuration public class KafakaProducerConfig { //@Bean ProducerFactory<String, User> producerFactory(){ Map<String, Object> config=new HashMap<>(); config.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"localhost:9092"); config.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,StringSerializer.class); config.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, JsonSerializer.class); return new DefaultKafkaProducerFactory<>(config); } //@Bean KafkaTemplate<String ,User> kafkaTemplate(){ return new KafkaTemplate<>(producerFactory()); } }
package day20; public class test8 { public static void main(String[] args) { int a = 10; int b = 0; int [] arr= {11,22,33,44,55}; try { System.out.println(a/b); System.out.println(arr[10]); arr= null; //System.out.println(arr[0]); } catch (ArithmeticException e) { // TODO: handle exception System.out.println("除数不能为零"); }catch (ArrayIndexOutOfBoundsException e) { // TODO: handle exception System.out.println("脚标越界了"); }catch (Exception e) { // TODO: handle exception System.out.println("出错了"); } System.out.println("over"); } }
package JUnit; import static org.junit.Assert.*; import org.junit.Before; import org.junit.Test; public class TestJava { @Test public void testAddReply() { fail("Not yet implemented"); } @Test public void testSelectReplyByTid() { System.out.println("@Test");//调用自己要测试的方法 } @Test(timeout=1) public void testTimeout() { System.out.println("超时测试"); } @Before public void testBefore(){ System.out.println("@Before"); } }
package com.uwaterloo.watodo; import android.app.DatePickerDialog; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.os.CountDownTimer; import android.provider.OpenableColumns; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.ImageView; import android.widget.RatingBar; import android.widget.TextView; import android.widget.Toast; import android.widget.RadioButton; import android.Manifest; import android.content.pm.PackageManager; import android.net.Uri; import android.os.Environment; import android.provider.MediaStore; import androidx.core.content.FileProvider; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.common.api.Status; import com.google.android.libraries.places.api.Places; import com.google.android.libraries.places.api.model.Place; import com.google.android.libraries.places.api.net.PlacesClient; import com.google.android.libraries.places.widget.AutocompleteSupportFragment; import com.google.android.libraries.places.widget.listener.PlaceSelectionListener; import com.application.isradeleon.notify.Notify; import java.util.Arrays; import java.util.Calendar; import java.io.File; import java.text.SimpleDateFormat; import java.util.Date; public class AddEditTaskActivity extends AppCompatActivity implements View.OnClickListener { public static final String EXTRA_ID = "com.uwaterloo.watodo.EXTRA_ID"; public static final String EXTRA_TITLE = "com.uwaterloo.watodo.EXTRA_TITLE"; public static final String EXTRA_DESCRIPTION = "com.uwaterloo.watodo.EXTRA_DESCRIPTION"; public static final String EXTRA_PRIORITY = "com.uwaterloo.watodo.EXTRA_PRIORITY"; public static final String EXTRA_YEAR = "com.uwaterloo.watodo.EXTRA_YEAR"; public static final String EXTRA_MONTH = "com.uwaterloo.watodo.EXTRA_MONTH"; public static final String EXTRA_DAY = "com.uwaterloo.watodo.EXTRA_DAY"; public static final String EXTRA_COORDS = "com.uwaterloo.watodo.EXTRA_COORDS"; public static final String EXTRA_GROUP = "com.uwaterloo.watodo.EXTRA_GROUP"; // GALLERY/CAMERA REQUESTS public static final int FILE_PICKER_REQUEST = 600; public static final int CAMERA_REQUEST_CODE = 601; public static final int CAMERA_PERMISSION_REQUEST_CODE = 602; public CountDownTimer counter = new CountDownTimer(300,100) { @Override public void onTick(long millisUntilFinished) { } @Override public void onFinish() { } }; private EditText editTextTitle; private EditText editTextDescription; private EditText editGroup; private RatingBar numberPickerPriority; private EditText selectDate; private int ddlYear, ddlMonth, ddlDay; private int mYear, mMonth, mDay; private String group; // Attachments private TextView attachmentFilename; private Uri attachmentUri; private String apiKey = "AIzaSyA-hySyjyBDVSBKnH2GUv87RsEcLhUF7xM"; private double[] coords; private RadioButton selectNotifyTime1; private RadioButton selectNotifyTime3; private RadioButton selectNotifyTime7; private RadioButton selectNotifyLocOnsite; private RadioButton selectNotifyLocClose; private String placeName; private Button cancelReminder; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_task); coords = new double[2]; coords[0] = 0; coords[1] = 0; // Initialize Places. Places.initialize(getApplicationContext(), apiKey); // Create a new Places client instance. PlacesClient placesClient = Places.createClient(this); editTextTitle = findViewById(R.id.edit_text_title); editTextDescription = findViewById(R.id.edit_text_description); editGroup = findViewById(R.id.edit_text_group); numberPickerPriority = findViewById(R.id.priority_stars); selectDate = findViewById(R.id.date); selectDate.setOnClickListener(this); //reminder time selection selectNotifyTime1 = findViewById(R.id.radio_1_day); selectNotifyTime1.setOnClickListener(this); selectNotifyTime3 = findViewById(R.id.radio_3_days); selectNotifyTime3.setOnClickListener(this); selectNotifyTime7 = findViewById(R.id.radio_7_days); selectNotifyTime7.setOnClickListener(this); selectNotifyLocOnsite = findViewById(R.id.radio_onsite); selectNotifyLocOnsite.setOnClickListener(this); selectNotifyLocClose = findViewById(R.id.radio_close); selectNotifyLocClose.setOnClickListener(this); cancelReminder = findViewById(R.id.button_cancel); cancelReminder.setOnClickListener(this); // get a reference to the image view that holds the image that the user will see. attachmentFilename = findViewById(R.id.attachmentFilename); getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_close); // flow for editing an existing task Intent intent = getIntent(); if (intent.hasExtra(EXTRA_ID)) { setTitle("Edit Task"); editTextTitle.setText(intent.getStringExtra(EXTRA_TITLE)); editTextDescription.setText(intent.getStringExtra(EXTRA_DESCRIPTION)); group = intent.getStringExtra(EXTRA_GROUP); if (group != null) { editGroup.setText(intent.getStringExtra(EXTRA_GROUP)); } numberPickerPriority.setRating(intent.getIntExtra(EXTRA_PRIORITY,0)); ddlYear = intent.getIntExtra(EXTRA_YEAR,0); ddlMonth = intent.getIntExtra(EXTRA_MONTH,0); ddlDay = intent.getIntExtra(EXTRA_DAY,0); coords = intent.getDoubleArrayExtra(EXTRA_COORDS); String dateText = ""; if (ddlYear != 0 && ddlMonth != 0 && ddlDay != 0) { dateText = ddlYear+"-"+ddlMonth+"-"+ddlDay; } selectDate.setText(dateText); // numberPickerPriority.setRating(Integer.parseInt(intent.getStringExtra(EXTRA_PRIORITY))); } else { setTitle("Add Task"); } // Initialize the AutocompleteSupportFragment. AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment) getSupportFragmentManager().findFragmentById(R.id.autocomplete_fragment); // Specify the types of place data to return. autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.LAT_LNG)); // Set up a PlaceSelectionListener to handle the response. autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() { @Override public void onPlaceSelected(Place place) { // TODO: Get info about the selected place. Log.i("AddEditTask", "Place: " + place.getName() + ", " + place.getId()); Log.i("AddEditTask", "Lat, Long: " + place.getLatLng()); coords = new double[2]; coords[0] = place.getLatLng().latitude; coords[1] = place.getLatLng().longitude; placeName = place.getName(); } @Override public void onError(Status status) { // TODO: Handle the error. Log.i("AddEditTask", "An error occurred while selecting a Place: " + status); } }); } private void saveTask() { String title = editTextTitle.getText().toString(); String description = editTextDescription.getText().toString(); group = editGroup.getText().toString(); if(group.trim().isEmpty()) {group = null;} int priority = (int) numberPickerPriority.getRating(); if (title.trim().isEmpty() || description.trim().isEmpty()) { Toast.makeText(this, "Please insert a title and description", Toast.LENGTH_SHORT).show(); return; } Intent data = new Intent(); data.putExtra(EXTRA_TITLE, title); data.putExtra(EXTRA_DESCRIPTION, description); data.putExtra(EXTRA_PRIORITY, priority); data.putExtra(EXTRA_YEAR, ddlYear); data.putExtra(EXTRA_MONTH, ddlMonth); data.putExtra(EXTRA_DAY, ddlDay); data.putExtra(EXTRA_COORDS, coords); data.putExtra(EXTRA_GROUP, group); // add id only if the task has been edited (existing task; not new) int id = getIntent().getIntExtra(EXTRA_ID, -1); if (id != -1) { data.putExtra(EXTRA_ID, id); } setResult(RESULT_OK, data); finish(); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.add_task_menu, menu); menu.findItem(R.id.share_task).setVisible(false); // Sharing shouldn't be possible form AddEditActivity. Only from ViewTaskActivity. return true; } @Override public boolean onOptionsItemSelected(@NonNull MenuItem item) { switch (item.getItemId()) { case R.id.save_task: saveTask(); return true; default: return super.onOptionsItemSelected(item); } } @Override public void onClick(View view) { if (view == selectDate) { final Calendar c = Calendar.getInstance(); mYear = c.get(Calendar.YEAR); mMonth = c.get(Calendar.MONTH); mDay = c.get(Calendar.DAY_OF_MONTH); DatePickerDialog datePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { selectDate.setText(year + "-" + (monthOfYear+1) + "-" + dayOfMonth); ddlYear = year; ddlMonth = monthOfYear+1; ddlDay = dayOfMonth; } }, mYear, mMonth, mDay); datePickerDialog.show(); } if (view == cancelReminder){ counter.cancel(); selectNotifyTime1.setChecked(false); selectNotifyTime3.setChecked(false); selectNotifyTime7.setChecked(false); TextView textView=findViewById(R.id.notify); textView.setText("Reminder canceled." ); } if (view == selectNotifyTime1){ counterTime(1, selectNotifyTime1); } if (view == selectNotifyTime3){ counterTime(3, selectNotifyTime3); } if (view == selectNotifyTime7){ counterTime(7, selectNotifyTime7); } if (view == selectNotifyLocOnsite){ Notify.create(getApplicationContext()) .setTitle("You are at:") //.setContent(placeName) //phone version .setContent("University of Waterloo") //emulator version .setColor(R.color.colorPrimary) .setImportance(Notify.NotificationImportance.MAX) .show(); // Finally showing the notification } if (view == selectNotifyLocClose){ Notify.create(getApplicationContext()) .setTitle("You are approaching:") //.setContent(placeName) //phone version .setContent("University of Waterloo") //emulator version .setColor(R.color.colorPrimary) .setImportance(Notify.NotificationImportance.MAX) .show(); // Finally showing the notification } } public void counterTime(int time, final RadioButton selectNotifyTime){ counter = new CountDownTimer(time*10000, 1000) { TextView textView=findViewById(R.id.notify); public void onTick(long millisUntilFinished) { selectNotifyTime.setChecked(true); textView.setText("The reminder will be sent in " + millisUntilFinished / 1000 + " seconds."); } public void onFinish() { selectNotifyTime.setChecked(false); String title = editTextTitle.getText().toString(); String description = editTextDescription.getText().toString(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd 'at' HH:mm:ss z"); String currentDateandTime = "Reminder sent on: "; currentDateandTime = currentDateandTime + sdf.format(new Date()); textView.setText(currentDateandTime); Notify.create(getApplicationContext()) .setTitle("Upcoming deadline: " + title ) .setContent(description) .setColor(R.color.colorPrimary) .setImportance(Notify.NotificationImportance.MAX) .show(); // Finally showing the notification } }.start(); } // CAMERA INTENTS public void onTakePhotoClicked(View v) { if(checkSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) { invokeCamera(); } else { // let's request permission. String[] permissionRequest = {Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}; requestPermissions(permissionRequest, CAMERA_PERMISSION_REQUEST_CODE); } } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); if (requestCode == CAMERA_PERMISSION_REQUEST_CODE) { // we have heard back from our request for camera and write external storage. if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) { invokeCamera(); } else { Toast.makeText(this, "Cannot open camera", Toast.LENGTH_LONG).show(); } } } private void invokeCamera() { // get a file reference Uri pictureUri = FileProvider.getUriForFile(this, getApplicationContext().getPackageName() + ".provider", createImageFile()); Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); // tell the camera where to save the image. intent.putExtra(MediaStore.EXTRA_OUTPUT, pictureUri); // tell the camera to request WRITE permission. intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION); startActivityForResult(intent, CAMERA_REQUEST_CODE); } private File createImageFile() { // the public picture director File picturesDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); // timestamp makes unique name. SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss"); String timestamp = sdf.format(new Date()); // put together the directory and the timestamp to make a unique image location. File imageFile = new File(picturesDirectory, "picture" + timestamp + ".jpg"); return imageFile; } // clear attachments from selection public void onClearClicked(View v) { attachmentFilename.setText(""); attachmentUri = null; Toast.makeText(this, "Attachments cleared", Toast.LENGTH_LONG).show(); } // Open file picker for attachment selection public void onImageGalleryClicked(View v) { // invoke the file picker intent Intent filePickerIntent = new Intent(Intent.ACTION_PICK); // location of attachment storage File fileDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS); String fileDirectoryPath = fileDirectory.getPath(); // finally, get a URI representation Uri data = Uri.parse(fileDirectoryPath); // save attachmentUri = data; // set the data and type. Get all image types. filePickerIntent.setDataAndType(data, "*/*"); // we will invoke this activity, and get something back from it. startActivityForResult(filePickerIntent, FILE_PICKER_REQUEST); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { if (requestCode == CAMERA_REQUEST_CODE) { Toast.makeText(this, "Image saved", Toast.LENGTH_LONG).show(); } if (requestCode == FILE_PICKER_REQUEST) { Uri attachmentUri = data.getData(); String filename = queryName(attachmentUri); // show the attachment filename to the user attachmentFilename.setText(filename); } } } private String queryName(Uri uri) { Cursor returnCursor = getContentResolver().query(uri, null, null, null, null); assert returnCursor != null; int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME); returnCursor.moveToFirst(); String name = returnCursor.getString(nameIndex); returnCursor.close(); return name; } }
package Recursion; import java.util.List; import java.util.ArrayList; /** * * https://leetcode.com/explore/learn/card/recursion-i/251/scenario-i-recurrence-relation/1660/ * Similar to pascals triangle * * Tags - Recursion, Recurrence relation * @author vignesh * */ public class PascalTriangle2UsingRecursion { public List<Integer> getRow(int rowIndex) { List<List<Integer>> result = buildPascalsTriangle(rowIndex+1); return result.get(rowIndex); } List<List<Integer>> buildPascalsTriangle(int numRows) { List<Integer> e = new ArrayList<>(); List<List<Integer>> result = new ArrayList<>(); if(numRows == 0) return result; if(numRows == 1) { e.add(1); result.add(e); return result; } result = buildPascalsTriangle(--numRows); List<Integer> prev = result.get(result.size() - 1); e.add(1); for(int i = 0; i < prev.size() - 1; i++) { e.add(prev.get(i) + prev.get(i+1)); } e.add(1); result.add(e); return result; } }
module labtest0 { }
//package views.grid; // //public enum NeighborType { // EDGE, // DUVALL, // VERTEX //}
package com.spsc.szxq.utils; import android.content.Context; import com.google.gson.Gson; import com.spsc.szxq.view.ToastView; import org.ksoap2.serialization.SoapObject; /** * Created by allens on 2017/3/6. */ public class IntentDataUtils { private Context mContext; public IntentDataUtils(Context context) { mContext = context; } public <T> T getIntentData(final Class<T> claxx, String methordname, String json, final Response<T> response) { Utils.newInstance(mContext).getIntentDataJson(methordname, json, new WebServiceUtil.Response() { @Override public void onSuccess(SoapObject result) { if (result != null) { String mjosn = result.getProperty(0).toString(); LogUtil.LogShitou("mjson------->" + mjosn); Gson gson = new Gson(); T bean = gson.fromJson(mjosn, claxx); response.onSuccess(bean); } } @Override public void onError(Exception e) { response.onError(e); } }); return null; } public interface Response<T> { void onSuccess(T bean); void onError(Exception e); } }
package jc.sugar.JiaHui.jmeter.configtestelement; import jc.sugar.JiaHui.jmeter.*; import org.apache.jmeter.protocol.http.control.DNSCacheManager; import org.apache.jmeter.protocol.http.control.StaticHost; import org.apache.jmeter.testelement.property.JMeterProperty; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.apache.jorphan.util.Converter.getBoolean; import static org.apache.jorphan.util.Converter.getString; @JMeterElementMapperFor(value = JMeterElementType.DNSCacheManager, testGuiClass = JMeterElement.DNSCacheManager) public class DNSCacheManagerMapper extends AbstractJMeterElementMapper<DNSCacheManager> { public static final String WEB_CLEAR_EACH_ITERATION = "clearEachIteration"; public static final String WEB_IS_CUSTOM_RESOLVER = "isCustomResolver"; public static final String WEB_SERVERS = "servers"; public static final String WEB_HOSTS = "hosts"; public static final String WEB_SERVER_NAME = "name"; public static final String WEB_HOST_NAME = "name"; public static final String WEB_HOST_ADDRESS = "address"; private DNSCacheManagerMapper(DNSCacheManager element, Map<String, Object> attributes) { super(element, attributes); } public DNSCacheManagerMapper(Map<String, Object> attributes){ this(new DNSCacheManager(), attributes); } public DNSCacheManagerMapper(DNSCacheManager element){ this(element, new HashMap<>()); } @Override public DNSCacheManager fromAttributes() { element.setClearEachIteration(getBoolean(attributes.get(WEB_CLEAR_EACH_ITERATION))); element.setCustomResolver(getBoolean(attributes.get(WEB_IS_CUSTOM_RESOLVER))); if(getBoolean(attributes.get(WEB_IS_CUSTOM_RESOLVER))){ List<Map<String, Object>> servers = (List<Map<String, Object>>) attributes.get(WEB_SERVERS); List<Map<String, Object>> hosts = (List<Map<String, Object>>) attributes.get(WEB_HOSTS); for(Map<String, Object> server: servers){ element.addServer(getString(server.get(WEB_SERVER_NAME))); } for(Map<String, Object> host: hosts){ element.addHost(getString(host.get(WEB_HOST_NAME)), getString(host.get(WEB_HOST_ADDRESS))); } } return element; } @Override public Map<String, Object> toAttributes() { attributes.put(WEB_CATEGORY, JMeterElementCategory.ConfigElement); attributes.put(WEB_TYPE, JMeterElementType.DNSCacheManager); attributes.put(WEB_CLEAR_EACH_ITERATION, element.isClearEachIteration()); attributes.put(WEB_IS_CUSTOM_RESOLVER, element.isClearEachIteration()); List<Map<String, Object>> serverList = new ArrayList<>(); for(JMeterProperty serverProperty: element.getServers()){ Map<String, Object> server = new HashMap<>(); server.put(WEB_ID, System.identityHashCode(serverProperty)); server.put(WEB_SERVER_NAME, serverProperty.getStringValue()); serverList.add(server); } attributes.put(WEB_SERVERS, serverList); List<Map<String, Object>> hostList = new ArrayList<>(); for(JMeterProperty hostProperty: element.getHosts()){ StaticHost host = (StaticHost) hostProperty.getObjectValue(); Map<String, Object> hostAttributes = new HashMap<>(); hostAttributes.put(WEB_ID, System.identityHashCode(hostProperty)); hostAttributes.put(WEB_HOST_NAME, host.getName()); hostAttributes.put(WEB_HOST_ADDRESS, host.getAddress()); hostList.add(hostAttributes); } attributes.put(WEB_HOSTS, hostList); return attributes; } }
package com.ld.common.model; import java.util.Date; import com.ld.community.bean.CommonRequestParam; public class OwnerCallfixFormModel extends CommonRequestParam{ private Long id; private Long ownerId; private Long communityId; private String organization; private String object; private String name; private String mobile; private String callfixDesc; private Long status; private String responsiblePerson; private String responsiblePersonMobile; private Long processUser; private String remark; private Date createTime; private Date updateTime; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getOwnerId() { return ownerId; } public void setOwnerId(Long ownerId) { this.ownerId = ownerId; } public Long getCommunityId() { return communityId; } public void setCommunityId(Long communityId) { this.communityId = communityId; } public String getOrganization() { return organization; } public void setOrganization(String organization) { this.organization = organization == null ? null : organization.trim(); } public String getObject() { return object; } public void setObject(String object) { this.object = object == null ? null : object.trim(); } public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } public String getMobile() { return mobile; } public void setMobile(String mobile) { this.mobile = mobile == null ? null : mobile.trim(); } public String getCallfixDesc() { return callfixDesc; } public void setCallfixDesc(String callfixDesc) { this.callfixDesc = callfixDesc == null ? null : callfixDesc.trim(); } public Long getStatus() { return status; } public void setStatus(Long status) { this.status = status; } public String getResponsiblePerson() { return responsiblePerson; } public void setResponsiblePerson(String responsiblePerson) { this.responsiblePerson = responsiblePerson == null ? null : responsiblePerson.trim(); } public String getResponsiblePersonMobile() { return responsiblePersonMobile; } public void setResponsiblePersonMobile(String responsiblePersonMobile) { this.responsiblePersonMobile = responsiblePersonMobile == null ? null : responsiblePersonMobile.trim(); } public Long getProcessUser() { return processUser; } public void setProcessUser(Long processUser) { this.processUser = processUser; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark == null ? null : remark.trim(); } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Date getUpdateTime() { return updateTime; } public void setUpdateTime(Date updateTime) { this.updateTime = updateTime; } }
package com.zzlz13.zlibrary.inter; import android.os.Bundle; import com.zzlz13.zlibrary.base.BasePresenter; /** * Created by hjr on 2016/5/10. */ public interface IBase { int getLayout(); void initView(Bundle savedInstanceState); BasePresenter getPresenter(); }
package com.zitiger.plugin.xdkt.coder.utils; import com.intellij.database.model.DasColumn; import com.intellij.database.model.DasTable; import com.intellij.database.psi.DbTable; import com.intellij.database.util.DasUtil; import com.intellij.util.containers.JBIterable; import com.zitiger.plugin.xdkt.coder.model.ColumnInfo; import com.zitiger.plugin.xdkt.coder.model.TableInfo; import com.zitiger.plugin.xdkt.coder.setting.CoderSetting; import com.zitiger.plugin.xdkt.configuration.PluginSetting; import com.zitiger.plugin.xdkt.utils.NameUtils; import org.apache.commons.lang.StringUtils; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; /** * * * @author linglh * @version 2.12.0 on 2018/9/23 */ public class DbUtils { // TODO ingore some columns // remove prefix // not null // 分库分表键 // 打印日志 // 作者 /** * 通过DbTable获取TableInfo * * @param dbTable 原始表对象 * @return 表信息对象 */ public static TableInfo getTableInfoByDbTable(DbTable dbTable) { if (dbTable == null) { return null; } CoderSetting coderSetting = PluginSetting.getInstance().getCoderSetting(); TableInfo tableInfo = new TableInfo(); // 设置原属对象 tableInfo.setDbTable(dbTable); tableInfo.setDbName(dbTable.getName()); // 设置类名 String tablePrefix = coderSetting.getTablePrefix(); String shortTableName = dbTable.getName(); if (dbTable.getName().startsWith(tablePrefix)) { shortTableName = shortTableName.substring(tablePrefix.length()); } tableInfo.setClassName(NameUtils.getClassName(shortTableName)); // 设置类名 tableInfo.setVarName(NameUtils.getVarName(shortTableName)); // 设置注释 tableInfo.setComment(dbTable.getComment()); // 设置所有列 List<ColumnInfo> columnInfoList = new ArrayList<>(); tableInfo.setColumnList(columnInfoList); String[] ignoreColumns = StringUtils.split(coderSetting.getIgnoreColumns(), ","); Set<String> ignoreColumnSet = new HashSet<>(Arrays.asList(ignoreColumns)); // 处理所有列 JBIterable<? extends DasColumn> columns = DasUtil.getColumns(dbTable); for (DasColumn column : columns) { if (ignoreColumnSet.contains(column.getName())) { continue; } ColumnInfo columnInfo = new ColumnInfo(); columnInfoList.add(columnInfo); columnInfo.setDbColumn(column); columnInfo.setDbName(column.getName()); columnInfo.setNotNull(column.isNotNull()); if (StringUtils.equalsIgnoreCase(column.getName(), "id")) { tableInfo.setUseSequence(!isAutoVal(column)); } columnInfo.setTypeName(TypeUtils.getJavaType(column.getDataType().getSpecification())); columnInfo.setJdbcType(TypeUtils.getJdbcType(columnInfo.getTypeName())); // 列类型 columnInfo.setClassName(NameUtils.getClassName(column.getName())); columnInfo.setVarName(NameUtils.getVarName(column.getName())); columnInfo.setComment(column.getComment()); if (coderSetting.getPartitionKey().equalsIgnoreCase(columnInfo.getDbName())) { tableInfo.setPartitionColumn(columnInfo); } } return tableInfo; } private static boolean isAutoVal(@Nullable DasColumn column) { DasTable table = column == null ? null : column.getTable(); return table != null && table.getColumnAttrs(column).contains(DasColumn.Attribute.AUTO_GENERATED); } }
package botenanna.behaviortree.builder; public class MissingBehaviourTreeException extends RuntimeException { public MissingBehaviourTreeException() { } public MissingBehaviourTreeException(String message) { super(message); } }
package controllers; import javafx.application.Application; import javafx.fxml.FXMLLoader; import javafx.scene.Parent; import javafx.scene.Scene; import javafx.stage.Stage; import javax.swing.*; import java.io.IOException; import java.net.URL; import java.util.Objects; public class BattleShips extends Application { @Override public void start(Stage stage) throws IOException { Parent root = FXMLLoader.load(Objects.requireNonNull(getClass().getResource("../FXML/begin.fxml"))); stage.setScene(new Scene(root)); try { URL iconURL = BattleShips.class.getResource("../images/icon.png"); assert iconURL != null; java.awt.Image image = new ImageIcon(iconURL).getImage(); com.apple.eawt.Application.getApplication().setDockIconImage(image); } catch (Exception ignored) { } stage.setTitle("Battleships"); stage.setResizable(false); stage.show(); } public static void main(String[] args) { launch(args); } }
package la.opi.verificacionciudadana.fragments; /** * Created by Jhordan on 09/03/15. */ import android.os.Bundle; import android.support.v4.app.Fragment; import android.support.v4.view.ViewPager; import android.support.v7.app.ActionBarActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import com.google.android.gms.maps.CameraUpdate; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.MapView; import com.google.android.gms.maps.MapsInitializer; import com.google.android.gms.maps.model.BitmapDescriptorFactory; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.MarkerOptions; import java.util.HashMap; import java.util.Map; import la.opi.verificacionciudadana.R; import la.opi.verificacionciudadana.adapters.PagerAdapterDemo; import la.opi.verificacionciudadana.models.Ocurrence; import la.opi.verificacionciudadana.util.Comunicater; import la.opi.verificacionciudadana.util.Config; import la.opi.verificacionciudadana.views.MarkerGoogleMap; public class MapFragment extends Fragment { public MapFragment() { } public static MapFragment newInstance() { MapFragment mapFragment = new MapFragment(); Bundle extraArguments = new Bundle(); mapFragment.setArguments(extraArguments); return mapFragment; } private GoogleMap googleMap; private MapView mapView; // private static final int CAMERA_ZOOM = 16; la ideal private static final int CAMERA_ZOOM = 11; Marker marker; View rootView; ViewPager pager; PagerAdapterDemo pagerAdapterImages; HashMap<Marker, Ocurrence> markerOcurrenceHashMap; Ocurrence ocurrencess; @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_map, container, false); ((ActionBarActivity) getActivity()).getSupportActionBar().setTitle(getResources().getString(R.string.mexico)); pager = (ViewPager) rootView.findViewById(R.id.pager); pagerAdapterImages = new PagerAdapterDemo(getFragmentManager()); mapView = (MapView) rootView.findViewById(R.id.map); mapView.onCreate(savedInstanceState); try { setUpMapIfNeeded(rootView); } catch (Exception e) { e.printStackTrace(); } pager.setAdapter(pagerAdapterImages); return rootView; } @Override public void onResume() { super.onResume(); mapView.onResume(); } @Override public void onPause() { super.onPause(); mapView.onPause(); } @Override public void onDestroy() { super.onDestroy(); mapView.onDestroy(); } private void setUpMapIfNeeded(View rootView) { MapsInitializer.initialize(getActivity()); if (googleMap == null) { googleMap = ((MapView) rootView.findViewById(R.id.map)).getMap(); if (googleMap != null) { markerOcurrenceHashMap = new HashMap<>(); int i = 0; for (Ocurrence ocurrence : Comunicater.getOcurrencesList()) { if (i != 0) { ocurrence.setPositionPager(i); markerOcurrenceHashMap.put(marker(i, ocurrence.getLatitude(), ocurrence.getLongitude()), ocurrence); pagerAdapterImages.addFragment(FragmentInfoWindowMap.newInstance(ocurrence.getPositionPager()+". "+ ocurrence.getAction() , bundleOcurrences((Ocurrence) Comunicater.getOcurrencesList().get(i) ))); } i++; } } } } private Marker marker(final int i, String latitude, String longitude) { LatLng positionOcurrence = new LatLng(Double.parseDouble(latitude), Double.parseDouble(longitude)); CameraUpdate update = CameraUpdateFactory.newLatLngZoom(positionOcurrence, CAMERA_ZOOM); marker = googleMap.addMarker(new MarkerOptions().position(positionOcurrence) .icon(BitmapDescriptorFactory.fromBitmap(MarkerGoogleMap.customMarker(getActivity(), Integer.toString(i))))); googleMap.animateCamera(update); googleMap.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() { @Override public boolean onMarkerClick(Marker marker) { ocurrencess = markerOcurrenceHashMap.get(marker); pager.setCurrentItem(ocurrencess.getPositionPager() - 1); return false; } }); pagerListener(); return marker; } private void pagerListener() { pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() { @Override public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { } @Override public void onPageSelected(int position) { for (Map.Entry<Marker, Ocurrence> entry : markerOcurrenceHashMap.entrySet()) { Marker key = entry.getKey(); Ocurrence value = entry.getValue(); key.setIcon(BitmapDescriptorFactory.fromBitmap(MarkerGoogleMap.customMarker(getActivity(), Integer.toString(value.getPositionPager())))); if ((value.getPositionPager() - 1) == position) { key.setIcon(BitmapDescriptorFactory.fromBitmap(MarkerGoogleMap.customMarkerSelected(getActivity(), Integer.toString(value.getPositionPager())))); CameraUpdate update = CameraUpdateFactory.newLatLngZoom(key.getPosition(), CAMERA_ZOOM); googleMap.animateCamera(update); } } } @Override public void onPageScrollStateChanged(int state) { } }); } private Bundle bundleOcurrences(Ocurrence ocurrence) { Bundle bundle = new Bundle(); bundle.putString(Config.TITLE_OCURRENCE, ocurrence.getAction()); bundle.putString(Config.DATA_OCURRENCE, ocurrence.getOcurrenceData()); bundle.putString(Config.TIME_OCURRENCE, ocurrence.getToHour() + " - " + ocurrence.getFromHour()); bundle.putString(Config.DESCRIPTION_OCURRENCE, ocurrence.getDescription() + "\n \n" + ocurrence.getStrategyDescription()); bundle.putString(Config.PLACE_OCURRENCE, ocurrence.getCalle() + " ," + ocurrence.getColonia() + " " + ocurrence.getAdmin2()); bundle.putString(Config.CONTACT_OCURRENCE, ocurrence.getContactInfo()); return bundle; } }
package it.htm.dto; import it.htm.entity.User; import java.util.List; public class ArchitectureDTO extends BasicDTO { private List<ComponentDTO> components; private User user; public ArchitectureDTO(){} public List<ComponentDTO> getComponents() { return components; } public void setComponents(List<ComponentDTO> components) { this.components = components; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
package edu.kit.pse.osip.core.io.files; import edu.kit.pse.osip.core.model.base.TankSelector; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; /** * Wrapper for client settings file where settings of networking and monitoring are stored. * Keys consist of parameterType_TankSelector. * * @author Maximlian Schwarzmann * @version 1.0 */ public class ClientSettingsWrapper { /** * The file in which the settings are saved. */ private File settingsFile; /** * Properties for actual reading and writing the settings. */ private Properties properties; /** * Constructor of ClientSettingsWrapper. * * @param settingsFile Where to save the settings or from where to load them. */ public ClientSettingsWrapper(File settingsFile) { if (settingsFile == null) { throw new NullPointerException("File parameter is null"); } try { if (!settingsFile.exists() && !settingsFile.createNewFile()) { throw new RuntimeException("Unable to create settings file at " + settingsFile.getAbsolutePath()); } this.settingsFile = settingsFile; properties = new Properties(); FileInputStream in = new FileInputStream(settingsFile); properties.load(in); in.close(); } catch (IOException ex) { ex.printStackTrace(); throw new RuntimeException("Impossible to access provided settings file"); } } /** * Setter method of the server hostname. * * @param tank The tank to save the hostname for. * @param hostname The server hostname. */ public final void setServerHostname(TankSelector tank, String hostname) { String tankString = tank.name(); properties.setProperty("serverHostname_" + tankString, hostname); } /** * Setter method of server port. * * @param tank The tank to save the port for. * @param portServer The port. */ public final void setServerPort(TankSelector tank, int portServer) { String tankString = tank.name(); String portString = String.valueOf(portServer); properties.setProperty("serverPort_" + tankString, portString); } /** * Setter method of fetch interval. * * @param intervalMs fetch interval in milliseconds. */ public final void setFetchInterval(int intervalMs) { String intervalString = String.valueOf(intervalMs); properties.setProperty("fetchInterval", intervalString); } /** * Setter method of overflow alarm. * * @param tank The tank to save the value for. * @param enabled true if alarm is enabled. */ public final void setOverflowAlarm(TankSelector tank, boolean enabled) { String tankString = tank.name(); String enabledString = String.valueOf(enabled); properties.setProperty("overflowAlarm_" + tankString, enabledString); } /** * Setter method of underflow alarm. * * @param tank The tank to save the value for. * @param enabled true if alarm is enabled. */ public final void setUnderflowAlarm(TankSelector tank, boolean enabled) { String tankString = tank.name(); String enabledString = String.valueOf(enabled); properties.setProperty("underflowAlarm_" + tankString, enabledString); } /** * Setter method of overheating alarm. * * @param tank The tank to save the value for. * @param enabled true if alarm is enabled. */ public final void setOverheatingAlarm(TankSelector tank, boolean enabled) { String tankString = tank.name(); String enabledString = String.valueOf(enabled); properties.setProperty("overheatingAlarm_" + tankString, enabledString); } /** * Setter method of undercooling alarm. * * @param tank The tank to save the value for. * @param enabled true if alarm is enabled. */ public final void setUndercoolingAlarm(TankSelector tank, boolean enabled) { String tankString = tank.name(); String enabledString = String.valueOf(enabled); properties.setProperty("undercoolingAlarm_" + tankString, enabledString); } /** * Setter method of temperature diagram. * * @param tank The tank to save the value for. * @param enabled true if diagram is enabled. */ public final void setTempDiagram(TankSelector tank, boolean enabled) { String tankString = tank.name(); String enabledString = String.valueOf(enabled); properties.setProperty("tempDiagram_" + tankString, enabledString); } /** * Setter method of fill level diagram. * * @param tank The tank to save the value for. * @param enabled true if diagram is enabled. */ public final void setFillLevelDiagram(TankSelector tank, boolean enabled) { String tankString = tank.name(); String enabledString = String.valueOf(enabled); properties.setProperty("fillLevelDiagram_" + tankString, enabledString); } /** * Getter method of fetch interval. * * @param defaultValue value on error. * @return fetch interval in ms or defaultValue on error. */ public final int getFetchInterval(int defaultValue) { String entry = properties.getProperty("fetchInterval"); if (entry == null) { return defaultValue; } try { return Integer.parseInt(entry); } catch (NumberFormatException e) { return defaultValue; } } /** * Getter method of overheating alarm. * * @param tank The tank to get the value for. * @param defaultValue value on error. * @return true if alarm is enabled or defaultValue on error. */ public final boolean getOverheatingAlarm(TankSelector tank, boolean defaultValue) { String tankString = tank.name(); String entry = properties.getProperty("overheatingAlarm_" + tankString); if (entry == null || (!entry.equals("true") && !entry.equals("false"))) { return defaultValue; } return Boolean.parseBoolean(entry); } /** * Getter method of undercooling alarm. * * @param tank The tank to get the value for. * @param defaultValue value on error. * @return true if alarm is enabled or defaultValue on error. */ public final boolean getUndercoolingAlarm(TankSelector tank, boolean defaultValue) { String tankString = tank.name(); String entry = properties.getProperty("undercoolingAlarm_" + tankString); if (entry == null || (!entry.equals("true") && !entry.equals("false"))) { return defaultValue; } return Boolean.parseBoolean(entry); } /** * Getter method of overflow alarm. * * @param tank The tank to get the value for. * @param defaultValue value on error. * @return true if alarm is enabled or defaultValue on error. */ public final boolean getOverflowAlarm(TankSelector tank, boolean defaultValue) { String tankString = tank.name(); String entry = properties.getProperty("overflowAlarm_" + tankString); if (entry == null || (!entry.equals("true") && !entry.equals("false"))) { return defaultValue; } return Boolean.parseBoolean(entry); } /** * Getter method of underflow alarm. * * @param tank The tank to get the value for. * @param defaultValue value on error. * @return true if alarm is enabled or defaultValue on error. */ public final boolean getUnderflowAlarm(TankSelector tank, boolean defaultValue) { String tankString = tank.name(); String entry = properties.getProperty("underflowAlarm_" + tankString); if (entry == null || (!entry.equals("true") && !entry.equals("false"))) { return defaultValue; } return Boolean.parseBoolean(entry); } /** * Getter method of temperature diagram. * * @param tank The tank to get the value for. * @param defaultValue value on error. * @return true if diagram is enabled or defaultValue on error. */ public final boolean getTempDiagram(TankSelector tank, boolean defaultValue) { String tankString = tank.name(); String entry = properties.getProperty("tempDiagram_" + tankString); if (entry == null || (!entry.equals("true") && !entry.equals("false"))) { return defaultValue; } return Boolean.parseBoolean(entry); } /** * Getter method of fill level diagram. * * @param tank The tank to get the value for. * @param defaultValue value on error. * @return true if diagram is enabled or defaultValue on error. */ public final boolean getFillLevelDiagram(TankSelector tank, boolean defaultValue) { String tankString = tank.name(); String entry = properties.getProperty("fillLevelDiagram_" + tankString); if (entry == null || (!entry.equals("true") && !entry.equals("false"))) { return defaultValue; } return Boolean.parseBoolean(entry); } /** * Gets the hostname or IP address. * * @param tank The tank to get the hostname for. * @param defaultValue value on error. * @return the hostname or IP address or defaultValue on error. */ public final String getHostname(TankSelector tank, String defaultValue) { String tankString = tank.name(); String entry = properties.getProperty("serverHostname_" + tankString); if (entry == null) { return defaultValue; } return entry; } /** * Gets a port. * * @param tank The tank to get the port for. * @param defaultValue value on error. * @return the port number or defaultValue on error. */ public final int getPort(TankSelector tank, int defaultValue) { String tankString = tank.name(); String entry = properties.getProperty("serverPort_" + tankString); if (entry == null) { return defaultValue; } try { return Integer.parseInt(entry); } catch (NumberFormatException e) { return defaultValue; } } /** * Saves settings in file. */ public final void saveSettings() { try { FileOutputStream out = new FileOutputStream(settingsFile); properties.store(out, null); out.close(); } catch (IOException ex) { System.err.println("Unable to save settings file. Old values will be used on next start"); ex.printStackTrace(); } } }
package com.team.zhihu.controller; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import com.team.zhihu.bean.Comment; import com.team.zhihu.bean.Reply; import com.team.zhihu.bean.User; import com.team.zhihu.service.CommentService; import com.team.zhihu.service.ReplyService; import com.team.zhihu.utils.DateUtil; @Controller public class CommentController{ @Autowired CommentService commenservice; @Autowired ReplyService replyservice; @RequestMapping("/addComment") public String addComment(int essayid,String context,HttpServletRequest req,HttpServletResponse resp) { Date date=new Date(); String dateAdd=DateUtil.dateToString(date); HttpSession session=req.getSession(); User user=(User) session.getAttribute("curUser"); int userid=user.getId(); Comment comment=new Comment(0, essayid, context, userid, dateAdd, user); commenservice.insertComment(comment); return "redirect:/queryCommentByid?id="+essayid; } @RequestMapping("/toUserComment") public String toUserComment(int essayid,int commitid,String context,int touserid,HttpServletRequest req,HttpServletResponse resp) { Date date=new Date(); String dateAdd=DateUtil.dateToString(date); HttpSession session=req.getSession(); User user=(User) session.getAttribute("curUser"); Reply reply=new Reply(0, essayid, commitid, context, user.getId(), touserid, dateAdd, null, null); replyservice.insertReply(reply); return "redirect:/queryCommentByid?id="+essayid; } }
package leetcode_easy; public class Question_806 { public int[] numberOfLines(int[] widths, String S) { int line = 1; int totalLenth = 0; for (char c : S.toCharArray()) { int i = c - 'a'; totalLenth += widths[i]; if (totalLenth > 100) { line++; totalLenth = widths[i]; } } return new int[]{line, totalLenth}; } public void solve() { int[] width = new int[]{4,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10}; String S = "bbbcccdddaaa"; int[] ans = numberOfLines(width, S); System.out.println("ans[0]:" + ans[0] + ", ans[1]:" + ans[1]); } }
package commandline.argument.validator; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * User: gno, Date: 09.02.2015 - 13:36 */ public class MockInvalidArgumentValidator extends ArgumentValidator<String> { public MockInvalidArgumentValidator() { super(); } @Override public boolean isCompatible(@NotNull Class<?> clazz) { return false; } @Override public void validate(@Nullable String value) { throw new ValidationException("This is a mock validation exception message."); } @NotNull @Override public Class<String> getSupportedClass() { return String.class; } }
package org.reasearch.hbase.api; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.CellUtil; import org.apache.hadoop.hbase.HBaseConfiguration; import org.apache.hadoop.hbase.NamespaceDescriptor; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.client.*; import org.apache.hadoop.hbase.security.User; import org.apache.hadoop.hbase.util.Bytes; import java.io.IOException; import java.util.Iterator; /** * @fileName: HBaseClient.java * @description: HbaseAPI使用 * @author: by echo huang * @date: 2020-08-05 21:50 */ public class HBaseClient { private static Connection connection; static { connection = getConnection(); } private static Connection getConnection() { Configuration configuration = HBaseConfiguration.create(); configuration.set("hbase.zookeeper.quorum", "hadoop"); configuration.set("hbase.zookeeper.property.clientPort", "2181"); //your port configuration.set("hbase.master", "hadoop:16000"); try (Connection connection = ConnectionFactory.createConnection(configuration, User.getCurrent())) { return connection; } catch (IOException e) { e.printStackTrace(); throw new NullPointerException(); } } /** * DDL * 判断表是否存在 * * @param tableName 表名 * @return 是否存在 */ public static boolean isTableExist(String tableName) throws IOException { return connection.getAdmin().tableExists(TableName.valueOf(tableName)); } public static void dropTable(String tableName) throws IOException { connection.getAdmin().deleteTable(TableName.valueOf(tableName)); } public static void createTableName(String tableName) throws IOException { ColumnFamilyDescriptor student = ColumnFamilyDescriptorBuilder.newBuilder(ColumnFamilyDescriptorBuilder.of("student")) .setMaxVersions(1000) .build(); TableDescriptor test = TableDescriptorBuilder.newBuilder(TableName.valueOf(tableName)) .setColumnFamily(student) .setSplitEnabled(true) .build(); byte[][] splits = new byte[5][5]; connection.getAdmin().createTable(test); } public static void createNameSpace(String ns) throws IOException { connection.getAdmin().createNamespace(NamespaceDescriptor.create(ns).build()); } /** * DML */ public static void put(String tableName, String rowKey, String cf, String cn, String value, long ts) throws IOException { Put put = new Put(Bytes.toBytes(rowKey), ts) .addColumn(Bytes.toBytes(cf), Bytes.toBytes(cn), Bytes.toBytes(value)); Table table = connection.getTable(TableName.valueOf(tableName)); table.put(put); } /** * get */ public static void getData(String tableName, String rowKey, String cf, String cn) throws IOException { Table table = connection.getTable(TableName.valueOf(tableName)); Get get = new Get(Bytes.toBytes(rowKey)) .addColumn(Bytes.toBytes(cf), Bytes.toBytes(cn)); Result result = table.get(get); for (Cell cell : result.rawCells()) { System.out.println(Bytes.toString(CellUtil.cloneRow(cell))); System.out.println(Bytes.toString(CellUtil.cloneFamily(cell))); System.out.println(Bytes.toString(CellUtil.cloneQualifier(cell))); System.out.println(Bytes.toString(CellUtil.cloneValue(cell))); } } /** * scan * * @param tableName * @throws IOException */ public static void scanTable(String tableName) throws IOException { Table table = connection.getTable(TableName.valueOf(tableName)); Scan scan = new Scan(); Iterator<Result> iterator = table.getScanner(scan).iterator(); while (iterator.hasNext()) { Result next = iterator.next(); for (Cell cell : next.rawCells()) { System.out.println(Bytes.toString(CellUtil.cloneRow(cell))); System.out.println(Bytes.toString(CellUtil.cloneFamily(cell))); System.out.println(Bytes.toString(CellUtil.cloneQualifier(cell))); System.out.println(Bytes.toString(CellUtil.cloneValue(cell))); } } } /** * delete * * @param tableName * @param rowKey * @param cf * @param cn * @throws IOException */ public static void deleteRowKey(String tableName, String rowKey, String cf, String cn) throws IOException { Table table = connection.getTable(TableName.valueOf(tableName)); //删除rowkey Delete deleteRowKey = new Delete(Bytes.toBytes(rowKey)); // type标记 DeleteFamily,删除整个列族 table.delete(deleteRowKey); //删除cf Delete deleteCf = new Delete(Bytes.toBytes(rowKey)) .addFamily(Bytes.toBytes(cf)); //type标记 DeleteFamily,删除整个列族 table.delete(deleteCf); //fixme 删除cn,删除单个版本,其他版本的数据会显示,慎用 Delete delete = new Delete(Bytes.toBytes(rowKey)) .addColumn(Bytes.toBytes(cf), Bytes.toBytes(cn)); // 删除对应版本数据,type为Delete,只删除当前时间戳 Delete deletets = new Delete(Bytes.toBytes(rowKey)) .addColumn(Bytes.toBytes(cf), Bytes.toBytes(cn), 123421512555L); //type标记 Delete table.delete(delete); // 删除cn,删除多个版本,其他版本数据不会显示 Delete deletecn = new Delete(Bytes.toBytes(rowKey)) .addColumns(Bytes.toBytes(cf), Bytes.toBytes(cn)); //type标记 DeleteColumn,删除整个column table.delete(deletecn); } public static void main(String[] args) throws Exception { System.out.println(isTableExist("stu")); } }
package test; import java.awt.Color; import se.lth.cs.ptdc.fractal.MandelbrotGUI; public class TestColor { public static void main(String[] args) { MandelbrotGUI gui = new MandelbrotGUI(); Color[] colors = { new Color(236, 240, 241), new Color(189, 195, 199), new Color(149, 165, 166), new Color(127, 140, 141), new Color(241, 196, 15), new Color(243, 156, 18), new Color(230, 126, 34), new Color(211, 84, 0), new Color(231, 76, 60), new Color(192, 57, 43), new Color(46, 204, 113), new Color(39, 174, 96), new Color(26, 188, 156), new Color(22, 160, 133), new Color(52, 152, 219), new Color(41, 128, 185), new Color(155, 89, 182), new Color(142, 68, 173), new Color(52, 73, 94), new Color(44, 62, 80), }; Color a = new Color(0, 0, 255); Color b = new Color(255, 0, 0); Color[][] picture = new Color[100][200]; for(int i=0; i<200; i++){ for(int j=0; j<100; j++){ //picture[j][i] = Color.getHSBColor(i/(float)200, 1, 1); picture[j][i] = colors[(int)(i/(float)10)]; } } gui.putData(picture, 3, 3); } }
import java.awt.Color; import java.awt.Container; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.Image; import java.awt.Toolkit; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.image.BufferedImage; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JPanel; import java.awt.BorderLayout; import javax.swing.BorderFactory; import javax.swing.BoxLayout; import java.awt.CardLayout; import javax.swing.JSplitPane; import java.awt.FlowLayout; import javax.swing.SpringLayout; import javax.swing.border.LineBorder; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import java.awt.SystemColor; import javax.swing.JLabel; import java.awt.Font; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import javax.swing.SwingConstants; import javax.swing.JTextField; import javax.swing.JPasswordField; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import javax.swing.UIManager; import java.awt.GridBagLayout; import java.awt.GridBagConstraints; import java.awt.Insets; import java.awt.RenderingHints; import javax.swing.border.BevelBorder; import javax.swing.JTextArea; import javax.swing.JScrollPane; import javax.swing.ScrollPaneConstants; public class EduFunds { Color eduFundsGreenLightest = new Color(150,200,80); Color eduFundsGreenLighter = new Color(135,180,72); static Color eduFundsGreen = new Color(120,160,64); Color eduFundsGreenDarker = new Color(105,140,56); Color eduFundsGreenDarkest = new Color(90,120,49); private JFrame frame; private JTextField tfLoginUsername; private JPasswordField pfLoginPassword; private static Connection con; //Components private static JLabel lblLoginErrorMessage; private static JLabel lblCreateAccountErrorMessage; //Data retreived from the MySql Database private static ResultSet userData; private JTextField tfCreateAccountUsername; private JTextField tfCreateAccountFirstName; private JTextField tfCreateAccountLastName; private JPasswordField pfCreateAccountPassword; private JPasswordField pfCreateAccountConfirmPassword; //CURRENT USER private static User user; //Account Creation Variables private static int selectedAvatar = 12; //Profile form details static JLabel lblLandingProfileDonatedVal; static JLabel lblLandingProfileUsername; static JLabel lblLandingProfileFirstname; static JLabel lblLandingProfileSecondname; static JPanel panelLandingProfileDP; //PanelLandingCard static JPanel panelLandingCard; protected Container paneLandingCard; //Organization data static ResultSet orgData; static ArrayList<Organisation> organisationData; //LandingAnalyticsVariables static User highestDonor; static Organisation highestOrganisation; //Donation Data static ResultSet donData; static ArrayList<Donation> donationData; //Landing Page Buttons static JButton btnFooterNews, btnFooterAnalytics, btnFooterProfile, btnFooterDonate; //DonationHistory Panel static JScrollPane spLandingProfile; static JPanel panelDHView; //LandingDonate static JPanel panelLandingDonateList; static JPanel panelLandingDonateToOrg; //Landing News static JPanel panelLandingFeedList; private static JTextField tfDonate; //Donate Organisation static Organisation donateOrganisation; static JLabel lblDonateOrgName; static JLabel lblDonationResult; /** * Launch the application. * @throws ClassNotFoundException * @throws SQLException */ public static void main(String[] args) throws ClassNotFoundException, SQLException { Class.forName("com.mysql.cj.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/edufunds?autoReconnect=true&useSSL=false&allowPublicKeyRetrieval=true"; String password = ""; //ENTER YOUR MYSQL PASSWORD HERE String username = "root"; //ENTER YOUR MYSQL USERNAME HERE con = DriverManager.getConnection(url,username,password); //String url, username, password //Get the organisation database from mysql getOrganisationData(); //Gets the user database from mysql getUserData(); //Getting donation data getDonationData(); EventQueue.invokeLater(new Runnable() { public void run() { try { EduFunds window = new EduFunds(); window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } private static void getUserData() throws SQLException { String query = "select * from user"; Statement st = con.createStatement(); userData = st.executeQuery(query); //Updating highest donor information int max =0; userData.beforeFirst(); while(userData.next()) { if(userData.getInt(5)>max) { max = userData.getInt(5); highestDonor = new User(userData.getString(1), userData.getString(2), userData.getString(3), userData.getString(4), userData.getInt(5), userData.getInt(6) ); } } userData.beforeFirst(); } private static void getOrganisationData() throws SQLException { String query = "select * from organisation"; Statement st = con.createStatement(); orgData = st.executeQuery(query); organisationData = new ArrayList<Organisation>(); while(orgData.next()) { organisationData.add(new Organisation( orgData.getString(1), orgData.getString(2), orgData.getString(3), orgData.getString(4), orgData.getString(5), orgData.getInt(6) )); } //Setting max to first organisation int max = organisationData.get(0).getDonations(); int indexOfMax = 0; for(int i =1; i<organisationData.size(); i++) { if(organisationData.get(i).getDonations()>max) { max = organisationData.get(i).getDonations(); indexOfMax = i; } } highestOrganisation = organisationData.get(indexOfMax); System.out.println("Name of highest receiving organisation is " + highestOrganisation.getName() ); // for(int i =0; i <organisationData.size(); i++) { // System.out.println(organisationData.get(i).getName()); // } } private static void getDonationData() throws SQLException { String query = "select * from donation"; Statement st = con.createStatement(); donData = st.executeQuery(query); //Printing out the donation data // while(donData.next()) { // System.out.println(donData.getString(2)+" "+donData.getString(3)); // } //Filling the donation data list donationData = new ArrayList<Donation>(); while(donData.next()) { donationData.add(new Donation(donData.getInt(1), donData.getString(2), donData.getString(3), donData.getInt(4), donData.getString(5), donData.getInt(6))); } } public static boolean createAccount( String username, String firstName, String lastName, String password, String confirmPassword ) throws SQLException { if(!password.equals(confirmPassword)) { lblCreateAccountErrorMessage.setText("The passwords do not match"); System.out.println("Account cannot be created"); return false; } userData.beforeFirst(); while(userData.next()) { if(userData.getString(1).equals(username)) { lblCreateAccountErrorMessage.setText("The username already exists please pick another one"); System.out.println("Account cannot be created"); return false; } } if(firstName.isEmpty()) { lblCreateAccountErrorMessage.setText("First name field is empty"); System.out.println("Account cannot be created"); return false; } if(lastName.isEmpty()) { lblCreateAccountErrorMessage.setText("Last name field is empty"); System.out.println("Account cannot be created"); return false; } if(password.isEmpty()) { lblCreateAccountErrorMessage.setText("Password field is empty"); System.out.println("Account cannot be created"); return false; } String query = "insert into user(username,first_name,second_name,password, donations, avatar) values(?,?,?,?,?,?)"; PreparedStatement ps = con.prepareStatement(query); ps.setString(1, username); ps.setString(2, firstName); ps.setString(3, lastName); ps.setString(4, password); ps.setInt(5, 0); ps.setInt(6, selectedAvatar); ps.executeUpdate(); ps.close(); user = new User(username,firstName,lastName, password, 0, selectedAvatar); initProfileFormDetails(); return true; } private static boolean checkLoginCredentials(String username, String password) throws SQLException { System.out.println(password); boolean allowLogin = false; while(userData.next()) { if(userData.getString(1).equals(username) && userData.getString(4).equals(password)) { allowLogin = true; user = new User(userData.getString(1), userData.getString(2), userData.getString(3), userData.getString(4), userData.getInt(5), userData.getInt(6) ); break; } } userData.beforeFirst(); //IF LOGIN IS DENIED if(!allowLogin) { Toolkit.getDefaultToolkit().beep(); lblLoginErrorMessage.setText("Wrong username or password"); lblLoginErrorMessage.setForeground(Color.red); } //Fill profile form details initProfileFormDetails(); //Get donation history of the Current user and fill donation history scroll pane fillDonationHistory(); //Populating the landingDonate page fillLandingDonate(); //Populating the ladingFeed page fillFeed(); return allowLogin; } /** * Create the application. */ public EduFunds() { initialize(); } /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame(); frame.setBounds(100,0,1000,700); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); Image eduFundsLogo = new ImageIcon(getClass().getResource("Logos/eduFundsIcon.jpg")).getImage(); frame.setTitle("EduFunds"); frame.setIconImage(eduFundsLogo); frame.getContentPane().setLayout(new BoxLayout(frame.getContentPane(), BoxLayout.X_AXIS)); frame.setResizable(false); JPanel panelBody = new JPanel(); panelBody.setBackground(Color.RED); frame.getContentPane().add(panelBody); panelBody.setLayout(new CardLayout(0, 0)); panelBody.addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } } ); JPanel panelLogin = new JPanel() { @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; //g2.drawImage(new ImageIcon(getClass().getResource("Wallpapers/library.jpeg")).getImage(), //0, 0, frame.getWidth(), frame.getHeight(), null); g2.setPaint(new Color(250,250,250)); g2.fillRect(0, 0, frame.getWidth()/2, frame.getHeight()); g2.setPaint(new Color(250,250,250)); g2.fillRect(frame.getWidth()/2, 0, frame.getWidth(), frame.getHeight()); g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); int w = getWidth(); int h = getHeight(); Color color1 = eduFundsGreenLighter; Color color2 = eduFundsGreenDarker; GradientPaint gp = new GradientPaint(0, 0, color1, w, 0, color2); g2.setPaint(gp); g2.fillRect(0, 0, w/2, h); GradientPaint gp2 = new GradientPaint(0, 0, color2, w, 0, color1); g2.setPaint(gp2); g2.fillRect(w/2, 0, w, h); g2.setPaint(eduFundsGreenDarker); g2.fillRect(320, 142, 370, 396); Color glassyWhite = new Color(255,255,255,50); g2.setPaint(glassyWhite); g2.fillRect(0,0,frame.getWidth(),frame.getHeight()); } }; panelBody.add(panelLogin, "panel_Login"); panelLogin.setLayout(null); JPanel panelLoginForm = new JPanel(); panelLoginForm.setBounds(311, 131, 372, 400); panelLoginForm.setBorder(null); panelLoginForm.setBackground(Color.WHITE); panelLogin.add(panelLoginForm); GridBagLayout gbl_panelLoginForm = new GridBagLayout(); gbl_panelLoginForm.columnWidths = new int[]{370, 0}; gbl_panelLoginForm.rowHeights = new int[]{62, 14, 44, 14, 44, 14, 44, 42, 14, 0}; gbl_panelLoginForm.columnWeights = new double[]{1.0, Double.MIN_VALUE}; gbl_panelLoginForm.rowWeights = new double[]{1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, Double.MIN_VALUE}; panelLoginForm.setLayout(gbl_panelLoginForm); JButton btnLogin = new JButton("Log in\r\n"); btnLogin.setFont(new Font("Trebuchet MS", Font.PLAIN, 16)); btnLogin.setForeground(Color.white); btnLogin.setEnabled(false); btnLogin.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { try { if(checkLoginCredentials(tfLoginUsername.getText(),new String(pfLoginPassword.getPassword()))) { CardLayout cl = (CardLayout)(panelBody.getLayout()); cl.next(panelBody); frame.repaint(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }); JLabel lblLoginFormHeader = new JLabel("EduFunds "); lblLoginFormHeader.setForeground(eduFundsGreen); lblLoginFormHeader.setHorizontalAlignment(SwingConstants.CENTER); lblLoginFormHeader.setFont(new Font("Trebuchet MS", Font.BOLD, 30)); GridBagConstraints gbc_lblLoginFormHeader = new GridBagConstraints(); gbc_lblLoginFormHeader.fill = GridBagConstraints.BOTH; gbc_lblLoginFormHeader.insets = new Insets(0, 20, 0, 20); gbc_lblLoginFormHeader.gridx = 0; gbc_lblLoginFormHeader.gridy = 0; panelLoginForm.add(lblLoginFormHeader, gbc_lblLoginFormHeader); JLabel lblUsername = new JLabel("Username\r\n"); lblUsername.setForeground(Color.GRAY); lblUsername.setFont(new Font("Trebuchet MS", Font.PLAIN, 16)); GridBagConstraints gbc_lblUsername = new GridBagConstraints(); gbc_lblUsername.fill = GridBagConstraints.BOTH; gbc_lblUsername.insets = new Insets(0, 20, 0, 20); gbc_lblUsername.gridx = 0; gbc_lblUsername.gridy = 1; panelLoginForm.add(lblUsername, gbc_lblUsername); tfLoginUsername = new JTextField(); tfLoginUsername.setFont(new Font("Trebuchet MS", Font.PLAIN, 14)); GridBagConstraints gbc_tfLoginUsername = new GridBagConstraints(); gbc_tfLoginUsername.fill = GridBagConstraints.BOTH; gbc_tfLoginUsername.insets = new Insets(10, 20, 10, 20); gbc_tfLoginUsername.gridx = 0; gbc_tfLoginUsername.gridy = 2; panelLoginForm.add(tfLoginUsername, gbc_tfLoginUsername); tfLoginUsername.setColumns(10); //CardLayout cl = (CardLayout)(panelBody.getLayout()); //cl.show(panelBody,"name_147168431510941"); // Listen for changes in the text tfLoginUsername.getDocument().addDocumentListener(new DocumentListener() { public void changedUpdate(DocumentEvent e) { check(); } public void removeUpdate(DocumentEvent e) { check(); } public void insertUpdate(DocumentEvent e) { check(); } public void check() { if (tfLoginUsername.getText().length()==0 || pfLoginPassword.getPassword().length==0){ btnLogin.setBackground(Color.gray); btnLogin.setEnabled(false); } else { btnLogin.setBackground(eduFundsGreen); btnLogin.setEnabled(true); } } }); JLabel lblLoginPassword = new JLabel("Password"); lblLoginPassword.setForeground(Color.GRAY); lblLoginPassword.setFont(new Font("Trebuchet MS", Font.PLAIN, 16)); GridBagConstraints gbc_lblLoginPassword = new GridBagConstraints(); gbc_lblLoginPassword.fill = GridBagConstraints.BOTH; gbc_lblLoginPassword.insets = new Insets(0, 20, 0, 20); gbc_lblLoginPassword.gridx = 0; gbc_lblLoginPassword.gridy = 3; panelLoginForm.add(lblLoginPassword, gbc_lblLoginPassword); pfLoginPassword = new JPasswordField(); pfLoginPassword.setFont(new Font("Trebuchet MS", Font.PLAIN, 16)); GridBagConstraints gbc_pfLoginPassword = new GridBagConstraints(); gbc_pfLoginPassword.fill = GridBagConstraints.BOTH; gbc_pfLoginPassword.insets = new Insets(10, 20, 10, 20); gbc_pfLoginPassword.gridx = 0; gbc_pfLoginPassword.gridy = 4; panelLoginForm.add(pfLoginPassword, gbc_pfLoginPassword); pfLoginPassword.getDocument().addDocumentListener(new DocumentListener() { public void changedUpdate(DocumentEvent e) { check(); } public void removeUpdate(DocumentEvent e) { check(); } public void insertUpdate(DocumentEvent e) { check(); } public void check() { if (tfLoginUsername.getText().length()==0 || pfLoginPassword.getPassword().length==0){ btnLogin.setBackground(Color.gray); btnLogin.setEnabled(false); } else { btnLogin.setBackground(eduFundsGreen); btnLogin.setEnabled(true); } } }); lblLoginErrorMessage = new JLabel(""); lblLoginErrorMessage.setFont(new Font("Trebuchet MS", Font.PLAIN, 14)); lblLoginErrorMessage.setHorizontalAlignment(SwingConstants.CENTER); lblLoginErrorMessage.setForeground(UIManager.getColor("ToolBar.dockingForeground")); GridBagConstraints gbc_lblLoginErrorMessage = new GridBagConstraints(); gbc_lblLoginErrorMessage.fill = GridBagConstraints.BOTH; gbc_lblLoginErrorMessage.insets = new Insets(0, 20, 0, 20); gbc_lblLoginErrorMessage.gridx = 0; gbc_lblLoginErrorMessage.gridy = 5; panelLoginForm.add(lblLoginErrorMessage, gbc_lblLoginErrorMessage); btnLogin.setFocusPainted(false); btnLogin.setContentAreaFilled(true); btnLogin.setBackground(Color.gray); btnLogin.setFocusable(true); GridBagConstraints gbc_btnLogin = new GridBagConstraints(); gbc_btnLogin.fill = GridBagConstraints.BOTH; gbc_btnLogin.insets = new Insets(20, 20, 0, 20); gbc_btnLogin.gridx = 0; gbc_btnLogin.gridy = 6; panelLoginForm.add(btnLogin, gbc_btnLogin); JLabel lblCreateAccount = new JLabel("Create an account\r\n"); lblCreateAccount.setForeground(eduFundsGreen); lblCreateAccount.setHorizontalAlignment(SwingConstants.CENTER); lblCreateAccount.setFont(new Font("Trebuchet MS", Font.PLAIN, 16)); lblCreateAccount.addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent arg0) { // TODO Auto-generated method stub CardLayout cl = (CardLayout)(panelBody.getLayout()); cl.show(panelBody, "panel_CreateAccount"); frame.repaint(); } @Override public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub lblCreateAccount.setForeground(eduFundsGreenDarker); } @Override public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub lblCreateAccount.setForeground(eduFundsGreen); } @Override public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } } ); GridBagConstraints gbc_lblCreateAccount = new GridBagConstraints(); gbc_lblCreateAccount.fill = GridBagConstraints.VERTICAL; gbc_lblCreateAccount.gridx = 0; gbc_lblCreateAccount.gridy = 8; panelLoginForm.add(lblCreateAccount, gbc_lblCreateAccount); JPanel panelLanding = new JPanel(); panelLanding.setBackground(UIManager.getColor("ToggleButton.highlight")); panelBody.add(panelLanding, "panel_Dashboard"); panelLanding.setLayout(null); JPanel panelFooter = new JPanel(); panelFooter.setBounds(0, 604, 994, 67); panelLanding.add(panelFooter); panelFooter.setLayout(null); btnFooterNews = new JButton("News"); ImageIcon footer_icon = new ImageIcon(EduFunds.class.getResource("/Icons/news.png")); Image img = footer_icon.getImage() ; Image newimg = img.getScaledInstance( 45, 45, java.awt.Image.SCALE_SMOOTH ) ; footer_icon = new ImageIcon( newimg ); btnFooterNews.setIcon(footer_icon); btnFooterNews.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { CardLayout cl2 = (CardLayout)(panelLandingCard.getLayout()); cl2.show(panelLandingCard, "panel_landingNews"); setActive("News"); frame.repaint(); } }); btnFooterNews.setForeground(Color.black); btnFooterNews.setFocusable(false); btnFooterNews.setBackground(Color.WHITE); btnFooterNews.setBounds(0, 0, 260, 67); panelFooter.add(btnFooterNews); btnFooterDonate = new JButton("Donate"); footer_icon = new ImageIcon(EduFunds.class.getResource("/Icons/donate.png")); img = footer_icon.getImage() ; newimg = img.getScaledInstance( 40, 40, java.awt.Image.SCALE_SMOOTH ) ; footer_icon = new ImageIcon( newimg ); btnFooterDonate.setIcon(footer_icon); btnFooterDonate.setBackground(Color.WHITE); btnFooterDonate.setBounds(259, 0, 260, 67); btnFooterDonate.setFocusable(false); btnFooterDonate.setForeground(Color.black); panelFooter.add(btnFooterDonate); btnFooterDonate.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { CardLayout cl2 = (CardLayout)(panelLandingCard.getLayout()); cl2.show(panelLandingCard, "panel_landingDonate"); setActive("Donate"); frame.repaint(); } }); btnFooterAnalytics = new JButton("Analytics\r\n"); footer_icon = new ImageIcon(EduFunds.class.getResource("/Icons/analytics.png")); img = footer_icon.getImage() ; newimg = img.getScaledInstance( 40, 40, java.awt.Image.SCALE_SMOOTH ) ; footer_icon = new ImageIcon( newimg ); btnFooterAnalytics.setIcon(footer_icon); btnFooterAnalytics.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { CardLayout cl2 = (CardLayout)(panelLandingCard.getLayout()); cl2.show(panelLandingCard, "panel_landingAnalytics"); setActive("Analytics"); frame.repaint(); } }); btnFooterAnalytics.setForeground(Color.black); btnFooterAnalytics.setFocusable(false); btnFooterAnalytics.setBackground(Color.WHITE); btnFooterAnalytics.setBounds(517, 0, 248, 67); panelFooter.add(btnFooterAnalytics); btnFooterProfile = new JButton("Profile"); footer_icon = new ImageIcon(EduFunds.class.getResource("/Icons/profile.png")); img = footer_icon.getImage() ; newimg = img.getScaledInstance( 40, 40, java.awt.Image.SCALE_SMOOTH ) ; footer_icon = new ImageIcon( newimg ); btnFooterProfile.setIcon(footer_icon); btnFooterProfile.setFocusable(false); btnFooterProfile.setForeground(Color.white); btnFooterProfile.setBackground(eduFundsGreen); btnFooterProfile.setBounds(764, 0, 230, 67); panelFooter.add(btnFooterProfile); btnFooterProfile.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { CardLayout cl2 = (CardLayout)(panelLandingCard.getLayout()); cl2.show(panelLandingCard, "panel_landingProfile"); setActive("Profile"); frame.repaint(); } }); panelLandingCard = new JPanel(); panelLandingCard.setBackground(Color.WHITE); panelLandingCard.setBounds(0, 0, 994, 606); panelLanding.add(panelLandingCard); panelLandingCard.setLayout(new CardLayout(0, 0)); JPanel panelLandingDonate = new JPanel(); panelLandingDonate.setBackground(Color.WHITE); panelLandingDonate.setBorder(new LineBorder(new Color(0, 0, 0))); panelLandingCard.add(panelLandingDonate, "panel_landingDonate"); panelLandingCard.setBackground(Color.white); panelLandingDonate.setLayout(null); panelLandingDonateList = new JPanel(); panelLandingDonateList.setBackground(Color.WHITE); JScrollPane spLandingDonate = new JScrollPane(panelLandingDonateList); spLandingDonate.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); panelLandingDonateList.setLayout(new BoxLayout(panelLandingDonateList, BoxLayout.Y_AXIS)); spLandingDonate.setBounds(247, 0, 530, 606); spLandingDonate.setBackground(Color.white); spLandingDonate.getViewport().setBackground(Color.white); spLandingDonate.setHorizontalScrollBar(null); panelLandingDonate.add(spLandingDonate); panelLandingDonateToOrg = new JPanel(); panelLandingDonateToOrg.setBorder(new LineBorder(new Color(0, 0, 0))); panelLandingDonateToOrg.setBackground(Color.WHITE); panelLandingCard.add(panelLandingDonateToOrg, "panel_landingDonateToOrg"); panelLandingDonateToOrg.setLayout(null); JButton btnOpenLandingDonate = new JButton("<html><u>Back</u></html>"); btnOpenLandingDonate.setHorizontalAlignment(SwingConstants.LEADING); btnOpenLandingDonate.setFont(new Font("Trebuchet MS", Font.PLAIN, 16)); btnOpenLandingDonate.setBackground(Color.WHITE); btnOpenLandingDonate.setForeground(eduFundsGreen); btnOpenLandingDonate.setOpaque(false); btnOpenLandingDonate.setContentAreaFilled(true); btnOpenLandingDonate.setEnabled(true); btnOpenLandingDonate.setBounds(10, 11, 58, 23); btnOpenLandingDonate.setBorderPainted(false); btnOpenLandingDonate.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { lblDonationResult.setText(""); CardLayout cl2 = (CardLayout)(panelLandingCard.getLayout()); cl2.show(panelLandingCard, "panel_landingDonate"); } } ); panelLandingDonateToOrg.add(btnOpenLandingDonate); JPanel panelDonateOrgDP = new JPanel() { @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; g2.setColor(Color.white); g2.fillRect(0, 0, 160, 100); if(donateOrganisation!=null) { g2.drawImage(new ImageIcon(getClass().getResource(donateOrganisation.getLogo())).getImage(),10,10,230,180,this); } } }; panelDonateOrgDP.setBackground(Color.WHITE); panelDonateOrgDP.setBounds(372, 85, 250, 200); panelLandingDonateToOrg.add(panelDonateOrgDP); lblDonateOrgName = new JLabel("Org Name"); lblDonateOrgName.setHorizontalAlignment(SwingConstants.CENTER); lblDonateOrgName.setFont(new Font("Trebuchet MS", Font.BOLD | Font.ITALIC, 18)); lblDonateOrgName.setBounds(372, 296, 250, 44); panelLandingDonateToOrg.add(lblDonateOrgName); JLabel lblNewLabel_6 = new JLabel("How much do you wish to donate?"); lblNewLabel_6.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel_6.setFont(new Font("Trebuchet MS", Font.PLAIN, 16)); lblNewLabel_6.setBounds(284, 351, 442, 44); panelLandingDonateToOrg.add(lblNewLabel_6); tfDonate = new JTextField(); tfDonate.setBounds(372, 404, 250, 44); panelLandingDonateToOrg.add(tfDonate); tfDonate.setColumns(10); JButton btnDonateToOrg = new JButton("Donate"); btnDonateToOrg.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { if(!tfDonate.getText().equals("")) { try { makeDonation(); } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } } }); btnDonateToOrg.setForeground(Color.white); btnDonateToOrg.setBackground(eduFundsGreen); btnDonateToOrg.setFocusable(false); btnDonateToOrg.setFont(new Font("Trebuchet MS", Font.PLAIN, 16)); btnDonateToOrg.setBounds(394, 501, 201, 44); panelLandingDonateToOrg.add(btnDonateToOrg); lblDonationResult = new JLabel(""); lblDonationResult.setFont(new Font("Trebuchet MS", Font.ITALIC, 16)); lblDonationResult.setBounds(623, 501, 226, 44); lblDonationResult.setForeground(eduFundsGreen); panelLandingDonateToOrg.add(lblDonationResult); JPanel panelLandingNews = new JPanel(); panelLandingNews.setBorder(new LineBorder(new Color(0, 0, 0))); panelLandingNews.setBackground(Color.WHITE); panelLandingCard.add(panelLandingNews, "panel_landingNews"); panelLandingNews.setLayout(null); panelLandingFeedList = new JPanel(); panelLandingFeedList.setBorder(new LineBorder(new Color(0, 0, 0))); JScrollPane spLandingFeed = new JScrollPane(panelLandingFeedList); spLandingFeed.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); panelLandingFeedList.setLayout(new BoxLayout(panelLandingFeedList, BoxLayout.Y_AXIS)); spLandingFeed.setBounds(236, 0, 560, 606); panelLandingNews.add(spLandingFeed); JPanel panelLandingAnalytics = new JPanel(); panelLandingAnalytics.setBorder(new LineBorder(new Color(0, 0, 0))); panelLandingAnalytics.setBackground(Color.WHITE); panelLandingCard.add(panelLandingAnalytics, "panel_landingAnalytics"); panelLandingAnalytics.setLayout(null); JPanel panelLandingAnalyticsDonor = new JPanel(); panelLandingAnalyticsDonor.setBorder(new LineBorder(new Color(0, 0, 0))); panelLandingAnalyticsDonor.setBackground(Color.WHITE); panelLandingAnalyticsDonor.setBounds(20, 121, 466, 393); panelLandingAnalytics.add(panelLandingAnalyticsDonor); panelLandingAnalyticsDonor.setLayout(null); JLabel lblNewLabel_2 = new JLabel("Highest Donor"); lblNewLabel_2.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel_2.setFont(new Font("Trebuchet MS", Font.PLAIN, 20)); lblNewLabel_2.setBounds(10, 6, 446, 54); panelLandingAnalyticsDonor.add(lblNewLabel_2); JLabel lblNewLabel_4 = new JLabel("Donated"); lblNewLabel_4.setFont(new Font("Trebuchet MS", Font.BOLD, 16)); lblNewLabel_4.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel_4.setBounds(37, 328, 192, 54); panelLandingAnalyticsDonor.add(lblNewLabel_4); JLabel lblLandingHighestDonatedVal = new JLabel(""+highestDonor.getDonated()); lblLandingHighestDonatedVal.setFont(new Font("Trebuchet MS", Font.BOLD, 16)); lblLandingHighestDonatedVal.setHorizontalAlignment(SwingConstants.CENTER); lblLandingHighestDonatedVal.setBounds(239, 328, 192, 54); panelLandingAnalyticsDonor.add(lblLandingHighestDonatedVal); JLabel lblLandingHighestDonorUsername = new JLabel(highestDonor.getUserName()); lblLandingHighestDonorUsername.setHorizontalAlignment(SwingConstants.CENTER); lblLandingHighestDonorUsername.setFont(new Font("Trebuchet MS", Font.BOLD | Font.ITALIC, 16)); lblLandingHighestDonorUsername.setBounds(125, 266, 200, 50); panelLandingAnalyticsDonor.add(lblLandingHighestDonorUsername); JPanel panelHighestDonorDP = new JPanel() { public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; g2.setColor(Color.white); g2.fillRect(0, 0, 240, 200); int pointer = highestDonor.getAvatar(); System.out.println("Avatar is "+ pointer); int horVal = 975/5; int vertVal = 780/4; int vertMult = pointer/5; int horMult = pointer%5; g2.drawImage(new ImageIcon(getClass().getResource("Avatars/Avatars.jpeg")).getImage(), 10,10,220,190, (horVal * (horMult))+20, (vertVal*vertMult), (horVal * (horMult +1)), (vertVal*(vertMult+1)), this); } }; panelHighestDonorDP.setBackground(Color.WHITE); panelHighestDonorDP.setBounds(113, 66, 240, 200); panelLandingAnalyticsDonor.add(panelHighestDonorDP); JPanel panelLandingAnalyticsReceiver = new JPanel(); panelLandingAnalyticsReceiver.setLayout(null); panelLandingAnalyticsReceiver.setBorder(new LineBorder(new Color(0, 0, 0))); panelLandingAnalyticsReceiver.setBackground(Color.WHITE); panelLandingAnalyticsReceiver.setBounds(518, 121, 466, 393); panelLandingAnalytics.add(panelLandingAnalyticsReceiver); JLabel lblHighestReceiver = new JLabel("Highest Receiver"); lblHighestReceiver.setHorizontalAlignment(SwingConstants.CENTER); lblHighestReceiver.setFont(new Font("Trebuchet MS", Font.PLAIN, 20)); lblHighestReceiver.setBounds(10, 6, 446, 54); panelLandingAnalyticsReceiver.add(lblHighestReceiver); JLabel lblReceived = new JLabel("Received"); lblReceived.setHorizontalAlignment(SwingConstants.CENTER); lblReceived.setFont(new Font("Trebuchet MS", Font.BOLD, 16)); lblReceived.setBounds(39, 328, 192, 54); panelLandingAnalyticsReceiver.add(lblReceived); JLabel lblReceivedval = new JLabel(highestOrganisation.getDonations()+""); lblReceivedval.setHorizontalAlignment(SwingConstants.CENTER); lblReceivedval.setFont(new Font("Trebuchet MS", Font.BOLD, 16)); lblReceivedval.setBounds(241, 328, 192, 54); panelLandingAnalyticsReceiver.add(lblReceivedval); JPanel panel = new JPanel() { public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; g2.setColor(Color.white); g2.fillRect(0, 0, 240, 200); g2.drawImage(new ImageIcon(getClass().getResource(highestOrganisation.getLogo())).getImage(), 10,10,220,190,this); } } ; panel.setBackground(Color.WHITE); panel.setBounds(112, 71, 240, 200); panelLandingAnalyticsReceiver.add(panel); JLabel lblNewLabel_3 = new JLabel(highestOrganisation.getName()); lblNewLabel_3.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel_3.setFont(new Font("Trebuchet MS", Font.BOLD | Font.ITALIC, 16)); lblNewLabel_3.setBounds(122, 277, 200, 50); panelLandingAnalyticsReceiver.add(lblNewLabel_3); JPanel panelLandingProfile = new JPanel(); panelLandingProfile.setBorder(new LineBorder(new Color(0, 0, 0))); panelLandingCard.add(panelLandingProfile, "panel_landingProfile"); panelLandingProfile.setBackground(Color.WHITE); panelLandingProfile.setLayout(null); CardLayout cl2 = (CardLayout)(panelLandingCard.getLayout()); cl2.show(panelLandingCard, "panel_landingProfile"); panelLandingProfileDP = new JPanel() { @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; g2.setColor(Color.white); g2.fillRect(0, 0, 280, 200); int pointer = user.getAvatar(); System.out.println("Avatar is "+ pointer); int horVal = 975/5; int vertVal = 780/4; int vertMult = pointer/5; int horMult = pointer%5; g2.drawImage(new ImageIcon(getClass().getResource("Avatars/Avatars.jpeg")).getImage(), 10,10,270,190, (horVal * (horMult))+20, (vertVal*vertMult), (horVal * (horMult +1)), (vertVal*(vertMult+1)), this); } }; panelLandingProfileDP.setBorder(new LineBorder(new Color(0, 0, 0))); panelLandingProfileDP.setBounds(40, 11, 280, 200); panelLandingProfile.add(panelLandingProfileDP); JPanel panelLandingProfileForm = new JPanel(); panelLandingProfileForm.setBorder(new LineBorder(new Color(0, 0, 0))); panelLandingProfileForm.setBackground(Color.WHITE); panelLandingProfileForm.setBounds(40, 222, 280, 323); panelLandingProfile.add(panelLandingProfileForm); panelLandingProfileForm.setLayout(null); lblLandingProfileUsername = new JLabel(user!=null?user.getUserName():""); lblLandingProfileUsername.setHorizontalAlignment(SwingConstants.CENTER); lblLandingProfileUsername.setFont(new Font("Trebuchet MS", Font.BOLD | Font.ITALIC, 24)); lblLandingProfileUsername.setBounds(10, 11, 260, 57); lblLandingProfileUsername.setForeground(eduFundsGreen); panelLandingProfileForm.add(lblLandingProfileUsername); lblLandingProfileFirstname = new JLabel(user!=null?user.getFirstName():""); lblLandingProfileFirstname.setHorizontalAlignment(SwingConstants.CENTER); lblLandingProfileFirstname.setFont(new Font("Trebuchet MS", Font.PLAIN, 24)); lblLandingProfileFirstname.setBounds(10, 69, 260, 57); panelLandingProfileForm.add(lblLandingProfileFirstname); lblLandingProfileSecondname = new JLabel(user!=null?user.getLastName():""); lblLandingProfileSecondname.setHorizontalAlignment(SwingConstants.CENTER); lblLandingProfileSecondname.setFont(new Font("Trebuchet MS", Font.PLAIN, 24)); lblLandingProfileSecondname.setBounds(10, 123, 260, 57); panelLandingProfileForm.add(lblLandingProfileSecondname); JLabel lblLandingProfileDonated = new JLabel("Donated "); lblLandingProfileDonated.setHorizontalAlignment(SwingConstants.CENTER); lblLandingProfileDonated.setFont(new Font("Trebuchet MS", Font.BOLD, 20)); lblLandingProfileDonated.setBounds(10, 204, 260, 33); lblLandingProfileDonated.setForeground(eduFundsGreen); panelLandingProfileForm.add(lblLandingProfileDonated); lblLandingProfileDonatedVal = new JLabel(user!=null?""+user.getDonated():""); lblLandingProfileDonatedVal.setFont(new Font("Tahoma", Font.BOLD, 36)); lblLandingProfileDonatedVal.setHorizontalAlignment(SwingConstants.CENTER); lblLandingProfileDonatedVal.setBounds(10, 224, 260, 88); lblLandingProfileDonatedVal.setForeground(eduFundsGreen); panelLandingProfileForm.add(lblLandingProfileDonatedVal); JButton btnLandingLogOut = new JButton("Log out"); btnLandingLogOut.setFont(new Font("Trebuchet MS", Font.PLAIN, 16)); btnLandingLogOut.setBackground(eduFundsGreen); btnLandingLogOut.setForeground(Color.white); btnLandingLogOut.setBounds(40, 556, 280, 36); btnLandingLogOut.setFocusable(false); panelLandingProfile.add(btnLandingLogOut); JLabel lblLandingProfileDonationHistory = new JLabel("Donation History"); lblLandingProfileDonationHistory.setHorizontalAlignment(SwingConstants.CENTER); lblLandingProfileDonationHistory.setFont(new Font("Trebuchet MS", Font.BOLD | Font.ITALIC, 24)); lblLandingProfileDonationHistory.setBounds(330, 11, 654, 43); lblLandingProfileDonationHistory.setForeground(eduFundsGreen); panelLandingProfile.add(lblLandingProfileDonationHistory); panelDHView = new JPanel(); spLandingProfile = new JScrollPane(panelDHView); spLandingProfile.setHorizontalScrollBar(null); panelDHView.setLayout(new BoxLayout(panelDHView, BoxLayout.Y_AXIS)); spLandingProfile.setBounds(340, 65, 640, 480); panelLandingProfile.add(spLandingProfile); spLandingProfile.getViewport().setOpaque(false); spLandingProfile.setOpaque(false); spLandingProfile.getViewport().setLayout(new FlowLayout()); btnLandingLogOut.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent arg0) { // TODO Auto-generated method stub CardLayout cl = (CardLayout)(panelBody.getLayout()); cl.show(panelBody, "panel_Login"); frame.repaint(); } } ); JPanel panelCreateAccount = new JPanel(); panelCreateAccount.setBorder(new LineBorder(new Color(0, 0, 0))); panelCreateAccount.setBackground(Color.WHITE); panelBody.add(panelCreateAccount, "panel_CreateAccount"); panelCreateAccount.setLayout(null); JLabel lblCreateAccountHeader = new JLabel("Create an Edufunds account"); lblCreateAccountHeader.setFont(new Font("Trebuchet MS", Font.PLAIN, 24)); lblCreateAccountHeader.setBounds(23, 37, 454, 61); lblCreateAccountHeader.setForeground(eduFundsGreen); panelCreateAccount.add(lblCreateAccountHeader); JLabel lblNewLabel_1 = new JLabel("Enter a username so we know it's you."); lblNewLabel_1.setFont(new Font("Trebuchet MS", Font.BOLD, 16)); lblNewLabel_1.setBounds(41, 133, 465, 31); panelCreateAccount.add(lblNewLabel_1); tfCreateAccountUsername = new JTextField(); tfCreateAccountUsername.setBounds(41, 175, 258, 31); panelCreateAccount.add(tfCreateAccountUsername); tfCreateAccountUsername.setColumns(10); JLabel lblEnterYourFirst = new JLabel("Enter your first name."); lblEnterYourFirst.setFont(new Font("Trebuchet MS", Font.BOLD, 16)); lblEnterYourFirst.setBounds(41, 217, 465, 31); panelCreateAccount.add(lblEnterYourFirst); tfCreateAccountFirstName = new JTextField(); tfCreateAccountFirstName.setColumns(10); tfCreateAccountFirstName.setBounds(41, 259, 258, 31); panelCreateAccount.add(tfCreateAccountFirstName); JLabel lblEnterYourLast = new JLabel("Enter your last name."); lblEnterYourLast.setFont(new Font("Trebuchet MS", Font.BOLD, 16)); lblEnterYourLast.setBounds(41, 301, 465, 31); panelCreateAccount.add(lblEnterYourLast); tfCreateAccountLastName = new JTextField(); tfCreateAccountLastName.setColumns(10); tfCreateAccountLastName.setBounds(41, 343, 258, 31); panelCreateAccount.add(tfCreateAccountLastName); JLabel lblPasswordsHelpKeep = new JLabel("Passwords help keep your account secure."); lblPasswordsHelpKeep.setFont(new Font("Trebuchet MS", Font.BOLD, 16)); lblPasswordsHelpKeep.setBounds(41, 395, 465, 31); panelCreateAccount.add(lblPasswordsHelpKeep); pfCreateAccountPassword = new JPasswordField(); pfCreateAccountPassword.setBounds(41, 437, 258, 31); panelCreateAccount.add(pfCreateAccountPassword); JLabel lblConfirmPassword = new JLabel("Confirm Password."); lblConfirmPassword.setFont(new Font("Trebuchet MS", Font.BOLD, 16)); lblConfirmPassword.setBounds(41, 479, 465, 31); panelCreateAccount.add(lblConfirmPassword); pfCreateAccountConfirmPassword = new JPasswordField(); pfCreateAccountConfirmPassword.setBounds(41, 521, 258, 31); panelCreateAccount.add(pfCreateAccountConfirmPassword); JButton btnCreateAccount = new JButton("Create Account"); btnCreateAccount.setContentAreaFilled(true); btnCreateAccount.setFocusable(false); btnCreateAccount.setBackground(eduFundsGreen); btnCreateAccount.setForeground(Color.white); btnCreateAccount.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { try { if(createAccount(tfCreateAccountUsername.getText(), tfCreateAccountFirstName.getText(), tfCreateAccountLastName.getText(), new String(pfCreateAccountPassword.getPassword()), new String( pfCreateAccountConfirmPassword.getPassword()) )) { CardLayout cl = (CardLayout)(panelBody.getLayout()); cl.show(panelBody, "panel_Dashboard"); frame.repaint(); } } catch (SQLException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } } }); btnCreateAccount.setBounds(783, 629, 174, 31); panelCreateAccount.add(btnCreateAccount); JButton btnCreateAccountBack = new JButton("Back"); btnCreateAccountBack.setContentAreaFilled(true); btnCreateAccountBack.setFocusable(false); btnCreateAccountBack.setBackground(Color.white); btnCreateAccountBack.setForeground(eduFundsGreen); btnCreateAccountBack.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { CardLayout cl = (CardLayout)(panelBody.getLayout()); cl.show(panelBody, "panel_Login"); frame.repaint(); } }); btnCreateAccountBack.setBounds(663, 629, 105, 31); panelCreateAccount.add(btnCreateAccountBack); lblCreateAccountErrorMessage = new JLabel(""); lblCreateAccountErrorMessage.setForeground(Color.RED); lblCreateAccountErrorMessage.setFont(new Font("Trebuchet MS", Font.PLAIN, 14)); lblCreateAccountErrorMessage.setBounds(41, 578, 436, 31); panelCreateAccount.add(lblCreateAccountErrorMessage); JLabel lblNewLabel = new JLabel("Select An Avatar"); lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER); lblNewLabel.setFont(new Font("Trebuchet MS", Font.PLAIN, 16)); lblNewLabel.setBounds(400, 519, 557, 31); panelCreateAccount.add(lblNewLabel); JPanel avatarContainer = new JPanel() { @Override public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D) g; g2.fillRect(0, 0, 400, 400); g2.drawImage(new ImageIcon(getClass().getResource("Avatars/Avatars.jpeg")).getImage(),0,0,560,400,this); g2.drawImage(new ImageIcon(getClass().getResource("Avatars/tick.png")).getImage(), (560/5)*(selectedAvatar%5)+80, (400/4)*(selectedAvatar/5)+10, 30, 30, this); } }; avatarContainer.addMouseListener(new MouseListener() { @Override public void mouseClicked(MouseEvent e) { // TODO Auto-generated method stub int x = e.getX(); int y = e.getY(); //Accounting for x coordinate selectedAvatar= x*5/560; //Accounting for y coordinate selectedAvatar+= (y/100)*5; avatarContainer.repaint(); } @Override public void mouseEntered(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseExited(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mousePressed(MouseEvent arg0) { // TODO Auto-generated method stub } @Override public void mouseReleased(MouseEvent arg0) { // TODO Auto-generated method stub } } ); avatarContainer.setBounds(400, 110, 560, 400); panelCreateAccount.add(avatarContainer); } private static void initProfileFormDetails() { lblLandingProfileFirstname.setText(user.getFirstName()); lblLandingProfileSecondname.setText(user.getLastName()); lblLandingProfileUsername.setText(user.getUserName()); lblLandingProfileDonatedVal.setText(user.getDonated()+""); System.out.println(user.getAvatar()+" is the avatar value"); panelLandingProfileDP.repaint(); } private static void setActive(String buttonName) { btnFooterProfile.setBackground(Color.white); btnFooterNews.setBackground(Color.white); btnFooterAnalytics.setBackground(Color.white); btnFooterDonate.setBackground(Color.white); btnFooterProfile.setForeground(Color.black); btnFooterAnalytics.setForeground(Color.black); btnFooterNews.setForeground(Color.black); btnFooterDonate.setForeground(Color.black); if(buttonName.equals("News")) { btnFooterNews.setBackground(eduFundsGreen); btnFooterNews.setForeground(Color.white); } else if(buttonName.equals("Profile")) { btnFooterProfile.setBackground(eduFundsGreen); btnFooterProfile.setForeground(Color.white); } else if(buttonName.equals("Analytics")) { btnFooterAnalytics.setBackground(eduFundsGreen); btnFooterAnalytics.setForeground(Color.white); } else { btnFooterDonate.setBackground(eduFundsGreen); btnFooterDonate.setForeground(Color.white); } } private static void fillDonationHistory() { panelDHView.removeAll(); for(int i =0; i<donationData.size(); i++) { if(donationData.get(i).getDonor().equals(user.getUserName())) { panelDHView.add(new DonationHistoryListItem(donationData.get(i).getReceiver(), donationData.get(i).getDonation(), donationData.get(i).getLogo() )); System.out.println("Added component to screen"); } } spLandingProfile.repaint(); } private static void fillLandingDonate() { panelLandingDonateList.removeAll(); for(int i =0; i < organisationData.size(); i++) { panelLandingDonateList.add(new DonateListItem(organisationData.get(i))); System.out.println("Added donate List Item to screen"); } } private static void fillFeed() { panelLandingFeedList.removeAll(); for(int i =donationData.size()-1; i >= 0; i--) { panelLandingFeedList.add(new FeedListItem(donationData.get(i))); System.out.println("Added feed List Item to screen"); } } public static void switchToDonateScreen(Organisation org) { CardLayout cl2 = (CardLayout)(panelLandingCard.getLayout()); cl2.show(panelLandingCard, "panel_landingDonateToOrg"); donateOrganisation = org; lblDonateOrgName.setText(donateOrganisation.getName()); lblDonationResult.setText(""); } public static void makeDonation() throws SQLException { String query = "insert into donation(donor,receiver, avatar, logo, donation) values(?,?,?,?,?)"; PreparedStatement ps = con.prepareStatement(query); ps.setString(1, user.getUserName()); ps.setString(2, donateOrganisation.getName()); ps.setInt(3, user.getAvatar()); ps.setString(4, donateOrganisation.getLogo()); ps.setInt(5, Integer.parseInt(tfDonate.getText())); ps.executeUpdate(); ps.close(); String user_query = "update user set donations = ? where username = ?"; PreparedStatement ps2 = con.prepareStatement(user_query); int don_val = user.getDonated() + Integer.parseInt(tfDonate.getText()); lblLandingProfileDonatedVal.setText(""+don_val); ps2.setInt(1, don_val); ps2.setString(2, user.getUserName()); ps2.close(); String org_query = "update organisation set donations = ? where username= ?"; PreparedStatement ps3 = con.prepareStatement(org_query); int org_val = donateOrganisation.getDonations() + Integer.parseInt(tfDonate.getText()); ps3.setInt(1, org_val); ps3.setString(2, donateOrganisation.getName()); ps3.close(); Toolkit.getDefaultToolkit().beep(); lblDonationResult.setText("Donation made! Great Going!"); System.out.println("Made donation"); getDonationData(); fillFeed(); fillDonationHistory(); } }
package com.yunhe.systemsetup.service; import com.yunhe.systemsetup.entity.Guider; import com.baomidou.mybatisplus.extension.service.IService; /** * <p> * 导购员管理 服务类 * </p> * * @author 刘延奇,heyuji * @since 2019-01-02 */ public interface IGuiderService extends IService<Guider> { }
package com.ryit.service.admin.impl; import java.util.ArrayList; import java.util.List; import java.util.ListIterator; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ryit.entity.admin.AdminRole; import com.ryit.entity.admin.AdminUser; import com.ryit.entity.admin.AdminUserRoleMapping; import com.ryit.mapper.admin.AdminRoleMapper; import com.ryit.mapper.admin.AdminUserMapper; import com.ryit.service.admin.AdminUserService; /** * Created by 722665 on 2015/8/1. */ @Service public class AdminUserServiceImpl implements AdminUserService { //注入用户管理后台业务DAO层 @Autowired private AdminUserMapper adminUserMapper; @Autowired private AdminRoleMapper adminRoleMapper; @Override public AdminUser getUserByName(String name) { return adminUserMapper.getUserByName(name); } @Override public AdminUser addAdminUser(AdminUser users) { AdminUser user = null; if(null != users){ adminUserMapper.addAdminUser(users); user = adminUserMapper.getUserById(users.getId()); } return user; } @Override public List<AdminUser> getAllUser() { return adminUserMapper.getAllUser(); } @Override public List<AdminRole> getallRole() { return adminRoleMapper.findAll(); } /** * 保存 和 修改 */ @Override public void saveUserAndRole(AdminUser user, String roles) { if(user != null && roles != null){ AdminUser userByName = adminUserMapper.getUserByName(user.getLoginName()); String[] split = roles.split(","); List<Integer> ids=new ArrayList<>(); for (String roleId : split) { if((!"".equals(roleId.trim())) && roleId.matches("^[0-9]*$")){ Integer integer = Integer.valueOf(roleId); ids.add(integer); } } List<AdminRole> adminRoles=adminRoleMapper.getRoleByIds(ids); if(userByName == null){ //添加新 用户 adminUserMapper.addAdminUser(user); if(adminRoles != null && adminRoles.size() > 0){ //获取新用户id int t_admin_user_id = user.getId(); for(AdminRole ar : adminRoles){ //添加 第三张表 (用户角色mapping)表数据; adminUserMapper.addAdminUserRoleMapping(new AdminUserRoleMapping(t_admin_user_id,ar.getId())); } } }else{//进行修改操作 adminUserMapper.editUser(user); //删除第三张表 用户的角色数据; adminUserMapper.deleteAdminUserRoleMapping(user.getId()); Integer t_admin_user_id = user.getId(); for(AdminRole ar : adminRoles){ //添加 第三张表 (用户角色mapping)表数据; adminUserMapper.addAdminUserRoleMapping(new AdminUserRoleMapping(t_admin_user_id,ar.getId())); } } } } @Override public void delete(String userIds) { String[] split = userIds.split(","); List<Integer> ids=new ArrayList<>(); for (int i = 0; i < split.length; i++) { String userId = split[i]; if(!"".equals(userId.trim()) && userId.matches("^[0-9]*$")){ Integer id = Integer.valueOf(userId); ids.add(id); adminUserMapper.deleteAdminUserRoleMapping(id); } } adminUserMapper.delete(ids); } @Override public AdminUser getUserById(Integer id) { return adminUserMapper.getUserById(id); } @Override public Integer findUserIsExist(AdminUser user) { return adminUserMapper.findUserIsExist(user); } public List<AdminUser> findAll(){ return adminUserMapper.findAll(); } /** * 查询 用户关联角色表 */ public List<AdminUser> findUserRole(){ //查询用户关联菜单 List<AdminUser> userRoleAll = adminUserMapper.findUserRole(); //查询所有用户,(包括未关联角色的) List<AdminUser> userAll = findAll(); //进行去重: if(userRoleAll != null && userRoleAll.size() > 0 && userAll != null && userAll.size()>0){ ListIterator<AdminUser> ua = userAll.listIterator(); while(ua.hasNext()){ boolean flag = true; AdminUser user = ua.next(); if(user != null && user.getId() != null){ Integer rid = user.getId(); for(AdminUser ar : userRoleAll){ if(ar != null && ar.getId() != null){ if(rid.equals(ar.getId())){ flag = false; break; } } } } if(flag) userRoleAll.add(user); } } userAll = null;//清除无用列表; return userRoleAll; } /** * 分页查询用户的数据 */ public List<AdminUser> getAllAdminUser(Map<String, Integer> map) { List<AdminUser> list = adminUserMapper.getAllAdminUser(map); if(list != null && list.size() > 0){ //为拥有菜单的角色 匹配 菜单功能; for(AdminUser user : list){ List<AdminRole> roles = adminRoleMapper.getUserIdByRole(user.getId()); if(roles != null && roles.size() > 0) user.setRoles(roles); } } return list; } /** * 获取 用户的总数进行分页操作; */ public Integer getAllRecord() { return adminUserMapper.getAllRecord(); } }
import java.io.*; import java.util.StringTokenizer; public class HowManyDigits { public static void main(String[] args) { Kattio in = new Kattio(System.in); double[] digArr = new double[1000001]; digArr[0] = 1; for (int i = 1; i < digArr.length; i++) { digArr[i] = digArr[i - 1] + Math.log10(i); } while (in.hasMoreTokens()) { in.println(((int) Math.floor(digArr[in.getInt()]))); in.flush(); } in.close(); } public static class Kattio extends PrintWriter { public Kattio(InputStream i) { super(new BufferedOutputStream(System.out)); r = new BufferedReader(new InputStreamReader(i)); } public Kattio(InputStream i, OutputStream o) { super(new BufferedOutputStream(o)); r = new BufferedReader(new InputStreamReader(i)); } public boolean hasMoreTokens() { return peekToken() != null; } public int getInt() { return Integer.parseInt(nextToken()); } public double getDouble() { return Double.parseDouble(nextToken()); } public long getLong() { return Long.parseLong(nextToken()); } public String getWord() { return nextToken(); } private BufferedReader r; private String line; private StringTokenizer st; private String token; private String peekToken() { if (token == null) try { while (st == null || !st.hasMoreTokens()) { line = r.readLine(); if (line == null) return null; st = new StringTokenizer(line); } token = st.nextToken(); } catch (IOException e) { } return token; } private String nextToken() { String ans = peekToken(); token = null; return ans; } } }
package com.example.springbootrestdemo.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.repository.query.Param; import org.springframework.stereotype.Repository; import com.example.springbootrestdemo.entites.MobilePhone; @Repository public interface MobilePhoneRepository extends JpaRepository<MobilePhone, Long> { //In-build methods //or //Custom query @Query(value = "select m from MobilePhone m") public List<MobilePhone> getAllMobileDetails(); @Query(value = "select m from MobilePhone m where m.mobileId = :id") public MobilePhone getMobilePhoneById(@Param(value = "id") long id); }
package main.java.viewcontroller.views; import javafx.animation.*; import javafx.fxml.FXML; import javafx.fxml.Initializable; import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.ProgressBar; import javafx.scene.control.ScrollPane; import javafx.scene.layout.AnchorPane; import javafx.scene.layout.VBox; import javafx.util.Duration; import main.java.viewcontroller.PrimaryController; import main.java.viewcontroller.views.dynamiccomponents.FindLocationViewController; import main.java.viewcontroller.views.dynamiccomponents.PropertyQuestionViewController; import main.java.viewcontroller.views.dynamiccomponents.SolarPanelQuestionViewController; import main.java.viewcontroller.views.dynamiccomponents.SpaceQuestionViewController; import java.net.URL; import java.util.ResourceBundle; // Author: Alexander Larnemo Ask, Jonatan Bunis, Vegard Landrö, Mohamad Melhem, Alexander Larsson Vahlberg // Responsibility: The controller of the main view of the program. // Used by: Initialized in the primaryController and set as the current stage in the sceneSwitcher. // Uses: Controls the interaction of the main view and communicates with the model through the primarycontroller. public class MainViewController extends AnchorPane implements Initializable { SolarPanelQuestionViewController solarQ; SpaceQuestionViewController spaceQ; FindLocationViewController locationQ; PropertyQuestionViewController propertyQ; private int state = 0; private PrimaryController primaryController; @FXML private ScrollPane questionScrollPane; @FXML private VBox questionList; @FXML private Button calculateButton; @FXML private Button upNavigation; @FXML private Label questionNumber; @FXML private Button downNavigation; @FXML private AnchorPane root; public MainViewController(PrimaryController controller) { this.primaryController = controller; System.out.println("in here"); } @Override public void initialize(URL location, ResourceBundle resources) { //clearing the list and initializing question indicator. questionList.getChildren().clear(); //Adding questions to the list solarQ = new SolarPanelQuestionViewController(primaryController); spaceQ = new SpaceQuestionViewController(primaryController); locationQ = new FindLocationViewController(primaryController); propertyQ = new PropertyQuestionViewController(primaryController); questionList.getChildren().add(locationQ); questionList.getChildren().add(spaceQ); questionList.getChildren().add(solarQ); questionList.getChildren().add(propertyQ); questionNumber.setText(state + 1 + "/" + questionList.getChildren().size()); // For each node is list of question, add change listener to update calculate button for (Node n : questionList.getChildren()) { n.setOnMouseExited(event -> checkIfReadyForCalculation()); } //go to resultpage and show results. calculateButton.setOnAction(event -> { primaryController.goToResultView(); }); //scroll to next question upNavigation.setOnAction(event -> { if (state > 0) { slowScrollToNode(--state); } questionNumber.setText(state + 1 + "/" + questionList.getChildren().size()); }); //scroll to previous question downNavigation.setOnAction(event -> { if (state < questionList.getChildren().size() - 1) { slowScrollToNode(++state); } questionNumber.setText(state + 1 + "/" + questionList.getChildren().size()); }); } //Scrolls the scrollbar to specified node. (doesnt work properly) private void slowScrollToNode(int node) { double scrollPaneHeight = questionList.getHeight(); double nodeHeight = questionList.getChildren().get(node).getLayoutBounds().getHeight(); double relativeY = questionList.getChildren().get(node).getBoundsInParent().getMinY() + nodeHeight; double scrollProcent = relativeY / scrollPaneHeight; System.out.println(scrollProcent); slowScrollToPosition(questionScrollPane, scrollProcent); } // scrolls scrollpane to specified percentage. private void slowScrollToPosition(ScrollPane scrollPane, double pos) { Animation animation = new Timeline( new KeyFrame(Duration.seconds(0.2), new KeyValue(scrollPane.vvalueProperty(), pos, Interpolator.EASE_BOTH))); animation.play(); } //Checks each question for input. private void checkIfReadyForCalculation() { boolean spaceQready = spaceQ.isDataGathered(); boolean propertyQReady = propertyQ.isDataGathered(); //Also checks that data isnt currently being gathered from an API. boolean locationQReady = (!locationQ.isGatheringData()) && locationQ.isDataGathered(); if (spaceQready && propertyQReady && locationQReady) { calculateButton.setDisable(false); } else { calculateButton.setDisable(true); } } }
package it.polimi.ingsw.GC_21.VIEW; import it.polimi.ingsw.GC_21.ACTION.Pass; public class PassInput extends InputForm { @Override public void execute(RemoteView remoteView) { Pass pass = new Pass(remoteView.getPlayer()); remoteView.notifyObservers(pass); } }
package com.example.billage.frontend; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import com.example.billage.R; import com.example.billage.backend.GetSetADUserInfo; import com.example.billage.backend.HowMuchPay; import com.example.billage.backend.QuestChecker; import com.example.billage.backend.QuestProcessor; import com.example.billage.backend.api.UserInfo; import com.example.billage.backend.api.AccountBalance; import com.example.billage.backend.common.AppData; import com.example.billage.backend.common.Utils; import com.example.billage.frontend.data.QuestList; import com.example.billage.frontend.data.UsageList; import com.example.billage.frontend.ui.signup.SignupActivity; import com.google.android.material.bottomnavigation.BottomNavigationView; import com.unity3d.player.*; import androidx.appcompat.app.AppCompatActivity; import androidx.navigation.NavController; import androidx.navigation.Navigation; import androidx.navigation.ui.AppBarConfiguration; import androidx.navigation.ui.NavigationUI; import java.util.ArrayList; import okhttp3.internal.Util; public class MainActivity extends AppCompatActivity { private UnityPlayer mUnityPlayer; //이름 바꾸지말 것. Unityplayer @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Utils.getTestUserToken(); mUnityPlayer = new UnityPlayer(this); setContentView(R.layout.activity_main); BottomNavigationView navView = findViewById(R.id.nav_view); // Passing each menu ID as a set of Ids because each // menu should be considered as top level destinations. AppBarConfiguration appBarConfiguration = new AppBarConfiguration.Builder( R.id.navigation_home, R.id.navigation_billage, R.id.navigation_quest,R.id.navigation_mypage) .build(); NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment); NavigationUI.setupActionBarWithNavController(this, navController, appBarConfiguration); NavigationUI.setupWithNavController(navView, navController); //유저정보 조회 UserInfo.request_userInfo(); //잔액 조회 // AccountBalance.request_balance(); //잔액 및 거래내역 조회 Utils.getUserTrans(); Utils.getUserBalance(); //퀘스트 보상획득 정보 리셋 GetSetADUserInfo resetReward=new GetSetADUserInfo(); // resetReward.initializeRewardInfo(); resetReward.reset_dailyRewardInfo(); resetReward.reset_weeklyRewardInfo(); resetReward.reset_monthlyRewardInfo(); QuestProcessor questProcessor = new QuestProcessor(); questProcessor.questPreprocessing(); //// //서버 꺼져서 유저 정보 못불러올 때 이거 쓰셈 // Utils.getTestUserInfo(); // //AVD에서 인증 불가할 때 걍 이거 쓰셈 //얼마썼는지궁금해 // ArrayList<HowMuchPay> tt= Utils.getHowMuchPays(4700000000.0); // for(int i=0;i<tt.size();i++){ // Log.d("how",tt.get(i).getName()+" "+tt.get(i).getValue()+tt.get(i).getUnit()); // } } @Override public void onDestroy () { Log.d("Main1","Destroy"); super.onDestroy(); mUnityPlayer.quit(); } // Pause Unity @Override public void onPause() { Log.d("Main1","Pause"); super.onPause(); mUnityPlayer.pause(); } // Resume Unity @Override public void onResume() { Log.d("Main1","Resume"); super.onResume(); mUnityPlayer.resume(); } @Override public void onStart() { Log.d("Main1","start"); super.onStart(); mUnityPlayer.start(); } @Override public void onStop() { Log.d("Main1","stop"); super.onStop(); mUnityPlayer.stop(); } public UnityPlayer GetUnityPlayer() { return this.mUnityPlayer; } }
/** * Paintroid: An image manipulation application for Android. * Copyright (C) 2010-2013 The Catrobat Team * (<http://developer.catrobat.org/credits>) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.catrobat.paintroid.test.integration.dialog; import org.catrobat.paintroid.PaintroidApplication; import org.catrobat.paintroid.dialog.IndeterminateProgressDialog; import org.catrobat.paintroid.test.integration.BaseIntegrationTestClass; import org.catrobat.paintroid.tools.ToolType; import android.graphics.Color; import android.graphics.PointF; public class IndeterminateProgressDialogIntegrationTest extends BaseIntegrationTestClass { public IndeterminateProgressDialogIntegrationTest() throws Exception { super(); // TODO Auto-generated constructor stub } public void testDialogIsNotCancelable() { PointF point = new PointF(mCurrentDrawingSurfaceBitmap.getWidth() / 2, mCurrentDrawingSurfaceBitmap.getHeight() / 2); mSolo.clickOnScreen(point.x, point.y); selectTool(ToolType.FILL); PaintroidApplication.currentTool.changePaintColor(Color.BLUE); point = new PointF(mCurrentDrawingSurfaceBitmap.getWidth() / 4, mCurrentDrawingSurfaceBitmap.getHeight() / 4); mSolo.clickOnScreen(point.x, point.y); assertTrue("Progress Dialog is not showing", IndeterminateProgressDialog.getInstance().isShowing()); mSolo.clickOnScreen(point.x, point.y); assertTrue("Progress Dialog is not showing", IndeterminateProgressDialog.getInstance().isShowing()); } }
import javafx.application.Application; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.geometry.Insets; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.input.MouseButton; import javafx.scene.input.MouseEvent; import javafx.scene.layout.HBox; import javafx.scene.layout.Pane; import javafx.scene.layout.VBox; import javafx.scene.paint.Color; import javafx.stage.Stage; import javafx.scene.shape.Rectangle; public class Main extends Application { @Override public void start(Stage primaryStage) throws Exception { Group root = new Group(); VBox vb = new VBox(); vb.setSpacing(10); vb.setPadding(new Insets(10, 50, 50, 50)); final Rectangle rect = new Rectangle(20, 20, 350, 200); rect.setId("rect"); final ContextMenu context = new ContextMenu(); MenuItem item1 = new MenuItem("Red"); item1.setId("item1"); MenuItem item2 = new MenuItem("Green"); item2.setId("item2"); MenuItem item3 = new MenuItem("Yellow"); item3.setId("item3"); MenuItem item4 = new MenuItem("Blue"); item4.setId("item4"); item1.setOnAction(event -> { rect.setFill(Color.RED); }); item2.setOnAction(event -> rect.setFill(Color.GREEN)); item3.setOnAction(event -> rect.setFill(Color.YELLOW)); item4.setOnAction(event -> rect.setFill(Color.BLUE)); context.getItems().addAll(item1,new SeparatorMenuItem(),item2, new SeparatorMenuItem(),item3); rect.setFill(Color.GRAY); rect.setStroke(Color.BLACK); rect.addEventFilter(MouseEvent.MOUSE_CLICKED, event -> { if(event.getButton()== MouseButton.SECONDARY){ context.show(rect,event.getScreenX(),event.getScreenY()); } }); HBox hb = new HBox(); hb.setSpacing(10); hb.setPadding(new Insets(10, 50, 50, 50)); final TextField tf = new TextField(); tf.setId("tf"); tf.setPadding(new Insets(10, 10, 10, 10)); tf.setOnAction(event -> { if (tf.getText().equals("Red") && rect.getFill() != Color.RED) { rect.setFill(Color.RED); } if (tf.getText().equals("Green") && rect.getFill() != Color.GREEN) { rect.setFill(Color.GREEN); } if (tf.getText().equals("Yellow") && rect.getFill() != Color.YELLOW) { rect.setFill(Color.YELLOW); } }); Button btn1 = new Button(); btn1.setId("Yellow"); btn1.setText("Change To Yellow"); btn1.setOnAction(event -> { rect.setFill(Color.YELLOW); tf.setText("Yellow"); }); Button btn2 = new Button(); btn2.setId("Red"); btn2.setText("Change To Red"); btn2.setOnAction(event -> { rect.setFill(Color.RED); tf.setText("Red"); }); Button btn3 = new Button(); btn3.setId("Green"); btn3.setText("Change To Green"); btn3.setOnAction(event -> { rect.setFill(Color.GREEN); tf.setText("Green"); }); Label label = new Label(); label.setStyle("-fx-border-color:white; -fx-background-color:#c4d8de;"); label.setId("labelId"); label.setText("Can you find this label text"); hb.getChildren().add(btn1); hb.getChildren().add(btn2); hb.getChildren().add(btn3); ListView listView = new ListView(); listView.setId("listViewId"); listView.getItems().addAll("Item1","Item2","Item3","Item4","Item5","Item6","Item7"); vb.getChildren().addAll(hb, rect,label, tf,listView); Scene scene = new Scene(vb, 800, 800); primaryStage.setScene(scene); primaryStage.setTitle("Test Title"); primaryStage.show(); } public static boolean resultForJUnit(){ return true; } public static void main(String[] args) { launch(args); } }
package com.example.rishi.justjava; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.CheckBox; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; /** * This app displays an order form to order coffee. */ public class MainActivity extends AppCompatActivity { int quantity = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } /** * This method displays the given text on the screen. */ private void displayMessage(String message) { // TextView orderSummaryTextView = (TextView) findViewById(R.id.order_summary_text_view); // orderSummaryTextView.setText(message); String subject = "Just Java App"; Intent emailIntent = new Intent(Intent.ACTION_SENDTO); emailIntent.setData(Uri.parse("mailto:")); emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject); emailIntent.putExtra(Intent.EXTRA_TEXT, message); if (emailIntent.resolveActivity(getPackageManager()) != null) startActivity(emailIntent); } private String createOrderSummary(int price, boolean hasWhippedCream, boolean hasChooclate, String name) { String summarymes = ""; summarymes += "\nName: " + name; summarymes += "\nQuantity: " + quantity; summarymes += "\nAdd whipped cream?: " + hasWhippedCream; summarymes += "\nAdd Chocolate?: " + hasChooclate; summarymes += "\nTotal: $" + price; summarymes += "\nThank You"; return summarymes; } public void submitOrder(View view) { CheckBox WhippedCream = (CheckBox) findViewById(R.id.whippedcream); CheckBox chocolateCheckBox = (CheckBox) findViewById(R.id.chocolate); Boolean hasChocolate = false; Boolean hasWhippedCream = false; EditText nameTextView = (EditText) findViewById(R.id.nameTextView); String name; name = nameTextView.getText().toString(); hasWhippedCream = WhippedCream.isChecked(); hasChocolate = chocolateCheckBox.isChecked(); int price = calculatePrice(hasWhippedCream, hasChocolate); String summary = createOrderSummary(price, hasWhippedCream, hasChocolate, name); displayMessage(summary); } private void displayQuantity(int number) { TextView quantitytextview = (TextView) findViewById(R.id.quantity_text_view); quantitytextview.setText("" + number); } private int calculatePrice(boolean hasWhipped, boolean hasChocolate) { int price = 5; if (hasChocolate) { price += 2; } if (hasWhipped) { price += 1; } return price * quantity; } public void increment(View view) { if (quantity >= 50) { Toast.makeText(this, "Cannot order more than 50cups", Toast.LENGTH_SHORT).show(); return; } quantity++; displayQuantity(quantity); } public void decrement(View view) { if (quantity <= 1) { Toast.makeText(this, "Cannot order less than 1", Toast.LENGTH_SHORT).show(); return; } quantity--; displayQuantity(quantity); } }
package com.tencent.mm.plugin.wallet.balance.ui.lqt; import android.widget.CompoundButton; import android.widget.CompoundButton.OnCheckedChangeListener; class WalletLqtSaveFetchUI$4 implements OnCheckedChangeListener { final /* synthetic */ WalletLqtSaveFetchUI pcc; WalletLqtSaveFetchUI$4(WalletLqtSaveFetchUI walletLqtSaveFetchUI) { this.pcc = walletLqtSaveFetchUI; } public final void onCheckedChanged(CompoundButton compoundButton, boolean z) { if (z) { WalletLqtSaveFetchUI.a(this.pcc, true); } else { WalletLqtSaveFetchUI.a(this.pcc, false); } } }
package com.tencent.mm.plugin.radar; import android.content.Context; import android.graphics.Bitmap; import b.c.b.e; import com.tencent.mm.a.f; import com.tencent.mm.aa.q; import com.tencent.mm.pluginsdk.ui.i; import com.tencent.mm.pluginsdk.ui.i.a; import com.tencent.mm.sdk.platformtools.BackwardSupportUtil.b; import com.tencent.mm.sdk.platformtools.ad; import com.tencent.mm.sdk.platformtools.c; import com.tencent.mm.sdk.platformtools.x; import java.io.IOException; import java.lang.ref.WeakReference; public final class c$b implements a { private Bitmap byb; private final f<String, WeakReference<Bitmap>> lZt = new f(15); private Bitmap mjm; c$b() { try { Context context = ad.getContext(); e.h(context, "MMApplicationContext.getContext()"); this.byb = b.a(context.getAssets().open("avatar/default_nor_avatar.png"), com.tencent.mm.bp.a.getDensity(null)); Bitmap bitmap = this.byb; Bitmap bitmap2 = this.byb; if (bitmap2 == null) { e.cJM(); } this.mjm = c.a(bitmap, false, (float) (bitmap2.getWidth() / 2)); } catch (IOException e) { c.a aVar = c.mjl; x.printErrStackTrace(c.access$getTAG$cp(), e, "", new Object[0]); } } public final void a(i iVar) { e.i(iVar, "drawable"); if (iVar instanceof com.tencent.mm.aa.f.c) { q.Kp().a((com.tencent.mm.aa.f.c) iVar); } } public final Bitmap cJ(String str) { e.i(str, "tag"); WeakReference weakReference = (WeakReference) this.lZt.get(str); if (!(weakReference == null || weakReference.get() == null)) { Object obj = weakReference.get(); if (obj == null) { throw new b.i("null cannot be cast to non-null type android.graphics.Bitmap"); } else if (!((Bitmap) obj).isRecycled() && (e.i((Bitmap) weakReference.get(), this.byb) ^ 1) == 0) { return (Bitmap) weakReference.get(); } } Bitmap jM = com.tencent.mm.aa.c.jM(str); if (jM == null || jM.isRecycled()) { return this.mjm; } jM = c.a(jM, false, (float) (jM.getWidth() / 2)); this.lZt.m(str, new WeakReference(jM)); return jM; } public final Bitmap uM() { return this.byb; } public final Bitmap cK(String str) { e.i(str, "tag"); return null; } public final Bitmap b(String str, int i, int i2, int i3) { e.i(str, "tag"); return null; } }
package net.example.template.persons.control; import lombok.AllArgsConstructor; import net.example.template.persons.control.messaging.Queues; import org.springframework.jms.core.JmsTemplate; import org.springframework.stereotype.Component; import javax.jms.JMSException; import javax.jms.Message; import javax.jms.Session; import javax.jms.TextMessage; @Component @AllArgsConstructor public class PersonsNotifier { private final JmsTemplate jmsTemplate; private final Queues queues; public void notifyAboutPhoto() { jmsTemplate.send(queues.getProfilePhoto(), this::createMessage); } private Message createMessage(Session session) throws JMSException { TextMessage mess = session.createTextMessage("New photo has been uploaded"); mess.setStringProperty("JMSXGroupID", "session-1"); return mess; } }
package swm11.jdk.jobtreaming.back.app.lecture.model; import lombok.Getter; import lombok.Setter; import org.hibernate.annotations.DynamicInsert; import org.hibernate.annotations.DynamicUpdate; import swm11.jdk.jobtreaming.back.app.common.model.AbstractBoard; import swm11.jdk.jobtreaming.back.app.user.model.User; import javax.persistence.*; import java.io.Serializable; import java.util.ArrayList; import java.util.List; @Entity @Table(name = "lecture_question") @Getter @DynamicInsert @DynamicUpdate public class LectureQuestion extends AbstractBoard implements Serializable { @ManyToOne @JoinColumn(name = "lecture_id", nullable = false, referencedColumnName = "id") private Lecture lecture; // 강연 @Setter @ManyToOne @JoinColumn(nullable = false, referencedColumnName = "id") private User writer; // 작성자 @OneToMany(mappedBy = "question") private List<LectureAnswer> answer = new ArrayList<>(); // 답변 }
package com.smxknife.java.ex29; /** * @author smxknife * 2019/9/8 */ public class AnimalDemo { public static void main(String[] args) { Animal test = new Animal.Builder("test") .age(10) .build(); System.out.println(test); } }
/** * DNet eBusiness Suite * Copyright: 2010-2013 Nan21 Electronics SRL. All rights reserved. * Use is subject to license terms. */ package net.nan21.dnet.module.bd.presenter.impl.attr.model; import net.nan21.dnet.core.api.annotation.Ds; import net.nan21.dnet.core.api.annotation.DsField; import net.nan21.dnet.core.api.annotation.Param; import net.nan21.dnet.core.api.annotation.RefLookup; import net.nan21.dnet.core.api.annotation.RefLookups; import net.nan21.dnet.core.api.annotation.SortField; import net.nan21.dnet.core.presenter.model.AbstractTypeWithCodeDs; import net.nan21.dnet.module.bd.domain.impl.attr.AttributeSet; import net.nan21.dnet.module.bd.domain.impl.attr.AttributeSubSet; @Ds(entity = AttributeSubSet.class, sort = { @SortField(field = AttributeSubSet_Ds.f_attributeSet), @SortField(field = AttributeSubSet_Ds.f_sequenceNo)}) @RefLookups({@RefLookup(refId = AttributeSubSet_Ds.f_attributeSetId, namedQuery = AttributeSet.NQ_FIND_BY_CODE, params = {@Param(name = "code", field = AttributeSubSet_Ds.f_attributeSet)})}) public class AttributeSubSet_Ds extends AbstractTypeWithCodeDs<AttributeSubSet> { public static final String f_sequenceNo = "sequenceNo"; public static final String f_attributeSetId = "attributeSetId"; public static final String f_attributeSet = "attributeSet"; public static final String f_attributeSetName = "attributeSetName"; @DsField private Integer sequenceNo; @DsField(join = "left", path = "attributeSet.id") private String attributeSetId; @DsField(join = "left", path = "attributeSet.code") private String attributeSet; @DsField(join = "left", path = "attributeSet.name") private String attributeSetName; public AttributeSubSet_Ds() { super(); } public AttributeSubSet_Ds(AttributeSubSet e) { super(e); } public Integer getSequenceNo() { return this.sequenceNo; } public void setSequenceNo(Integer sequenceNo) { this.sequenceNo = sequenceNo; } public String getAttributeSetId() { return this.attributeSetId; } public void setAttributeSetId(String attributeSetId) { this.attributeSetId = attributeSetId; } public String getAttributeSet() { return this.attributeSet; } public void setAttributeSet(String attributeSet) { this.attributeSet = attributeSet; } public String getAttributeSetName() { return this.attributeSetName; } public void setAttributeSetName(String attributeSetName) { this.attributeSetName = attributeSetName; } }
/* * Copyright 2015 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.jbpm.test.casemgmt; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.drools.core.command.impl.GenericCommand; import org.drools.core.command.impl.KnowledgeCommandContext; import org.jbpm.workflow.core.impl.NodeImpl; import org.kie.api.runtime.KieSession; import org.kie.api.runtime.process.NodeInstance; import org.kie.api.runtime.process.WorkflowProcessInstance; import org.kie.api.task.TaskService; import org.kie.api.task.model.I18NText; import org.kie.api.task.model.Task; import org.kie.internal.command.Context; import org.kie.internal.task.api.InternalTaskService; import org.kie.internal.task.api.TaskModelProvider; import org.kie.internal.task.api.model.InternalI18NText; public class UpdateTaskNameCommand implements GenericCommand<Object> { private static final long serialVersionUID = 7323092505416116457L; private TaskService taskService; private long processInstanceId; private Task task; private String newName; public UpdateTaskNameCommand(TaskService taskService, long processInstanceId, Task task, String newName) { this.taskService = taskService; this.processInstanceId = processInstanceId; this.task = task; this.newName = newName; } @Override public Object execute(Context context) { KieSession kieSession = ((KnowledgeCommandContext) context).getKieSession(); Collection<NodeInstance> nodes = ((WorkflowProcessInstance) kieSession.getProcessInstance(processInstanceId)).getNodeInstances(); for (NodeInstance ni : nodes) { if (ni.getNodeName().equals(task.getName())) { ((NodeImpl)ni.getNode()).setName(newName); } } List<I18NText> updatedNames = new ArrayList<I18NText>(); I18NText updatedName = TaskModelProvider.getFactory().newI18NText(); ((InternalI18NText) updatedName).setLanguage(task.getNames().get(0).getLanguage()); ((InternalI18NText) updatedName).setText(newName); updatedNames.add(updatedName); ((InternalTaskService) taskService).setTaskNames(task.getId(), updatedNames); return null; } }
package com.chris.projects.fx.ftp.fix; import quickfix.Message; public interface FixSender { boolean send(Message message, String senderCompId, String targetCompId); }
package com.tencent.mm.g.a; public final class fj extends com.tencent.mm.sdk.b.b { public a bNK; public b bNL; public static final class b { public long bJC = 0; } public fj() { this((byte) 0); } private fj(byte b) { this.bNK = new a(); this.bNL = new b(); this.sFm = false; this.bJX = null; } }
package com.zero.votes.beans; import java.io.Serializable; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; import javax.faces.context.FacesContext; import javax.faces.event.ValueChangeEvent; /** * Manages the locales, which offer multilanguage support */ @ManagedBean(name = "language") @SessionScoped public class LanguageBean implements Serializable { private static final long serialVersionUID = 1L; private Locale currentLocale; private String localeCode; private static Map<String, Locale> availableLocales; static { availableLocales = new LinkedHashMap<String, Locale>(); availableLocales.put("Deutsch", Locale.GERMAN); availableLocales.put("English", Locale.ENGLISH); } public Map<String, Locale> getAvailableLocales() { return this.availableLocales; } public String getLocaleCode() { if (this.localeCode == null) { this.localeCode = this.getCurrentLocale().getLanguage(); } return this.localeCode; } public void setLocaleCode(String localeCode) { this.localeCode = localeCode; } public Locale getCurrentLocale() { if (this.currentLocale == null) { this.currentLocale = FacesContext.getCurrentInstance().getExternalContext().getRequestLocale(); } if (this.currentLocale == null) { this.currentLocale = Locale.GERMAN; } return this.currentLocale; } public void setLocale(Locale locale) { this.currentLocale = locale; } public void localeChanged(ValueChangeEvent e) { String newLocaleValue = e.getNewValue().toString(); for (Map.Entry<String, Locale> entry : this.availableLocales.entrySet()) { if (entry.getValue().toString().equals(newLocaleValue)) { FacesContext.getCurrentInstance().getViewRoot().setLocale((Locale) entry.getValue()); } } } }