text
stringlengths
10
2.72M
package com.sinodynamic.hkgta.service.crm.account; import com.sinodynamic.hkgta.service.IServiceBase; public interface DDITaskService extends IServiceBase{ /** * upload DDI transaction report *//* public void generateDDIReporter(); //TODO --pending public void parseDDIAckReporter(File file); *//** * download DDI reject reporter * @param file *//* public void parseDDIRejectReporter(File file); public void test();*/ public void generateDDIReport(); public void parseDDIRejectReporter(); }
import java.util.Scanner; import java.io.PrintWriter; import java.util.Arrays; // import java.util.HashMap; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); PrintWriter output = new PrintWriter(System.out); int n = scanner.nextInt(); Integer[] a = new Integer[n]; for (int i = 0; i < n; i++) { a[i] = scanner.nextInt(); } Arrays.sort(a); int result = 1; int l = 0; int r = 0; while (r < n) { if (a[r] - a[l] <= 5) { result = Math.max(result, r - l + 1); r++; } else { l++; } } output.println(result); output.flush(); } }
package com.unmcelearning.android.thyroidpathology; import android.app.ProgressDialog; import android.content.Intent; import android.net.Uri; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.text.SpannableString; import android.text.Spanned; import android.text.TextUtils; import android.text.style.TypefaceSpan; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.appindexing.Action; import com.google.android.gms.appindexing.AppIndex; import com.google.android.gms.appindexing.Thing; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.AuthResult; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; public class MainActivity extends AppCompatActivity implements View.OnClickListener { private Button buttonRegister; private EditText editTextEmail; private EditText editTextPassword; private EditText editTextConfirmPassword; private Button buttonSignIn; private ProgressDialog progressDialog; private FirebaseAuth firebaseAuth; private FirebaseAuth.AuthStateListener mAuthListener; private DatabaseReference mDatabase; /** * ATTENTION: This was auto-generated to implement the App Indexing API. * See https://g.co/AppIndexing/AndroidStudio for more information. */ private GoogleApiClient client; @Override protected void onCreate(final Bundle savedInstanceState) { setTheme(R.style.AppTheme); super.onCreate(savedInstanceState); //initialize buttons, edittexts, firebaseobjects, and progressbar progressDialog = new ProgressDialog(this); firebaseAuth = FirebaseAuth.getInstance(); mDatabase = FirebaseDatabase.getInstance().getReference(); mAuthListener = new FirebaseAuth.AuthStateListener() { @Override public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) { FirebaseUser user = firebaseAuth.getCurrentUser(); if (user != null) { // User is signed in finish(); Intent i = new Intent(MainActivity.this, HomeActivity.class); startActivity(i); } else { // User is signed out } // ... } }; setContentView(R.layout.activity_main); ActionBar actionBar = getSupportActionBar(); SpannableString title = new SpannableString("Thyroid Droid"); // Add a span for the sans-serif-light font title.setSpan( new TypefaceSpan("sans-serif-light"), 0, title.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE); actionBar.setTitle(title); buttonRegister = (Button) findViewById(R.id.button_register); editTextEmail = (EditText) findViewById(R.id.edit_text_email); editTextPassword = (EditText) findViewById(R.id.edit_text_password); editTextConfirmPassword = (EditText) findViewById(R.id.edit_text_confirm_password); buttonSignIn = (Button) findViewById(R.id.button_sign_in); buttonRegister.setOnClickListener(MainActivity.this); buttonSignIn.setOnClickListener(MainActivity.this); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build(); } @Override public void onStart() { super.onStart();// ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.connect(); firebaseAuth.addAuthStateListener(mAuthListener); // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. AppIndex.AppIndexApi.start(client, getIndexApiAction()); } @Override public void onStop() { super.onStop();// ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. AppIndex.AppIndexApi.end(client, getIndexApiAction()); if (mAuthListener != null) { firebaseAuth.removeAuthStateListener(mAuthListener); } // ATTENTION: This was auto-generated to implement the App Indexing API. // See https://g.co/AppIndexing/AndroidStudio for more information. client.disconnect(); } private void registerUser() { final String email = editTextEmail.getText().toString().trim(); String password = editTextPassword.getText().toString().trim(); String confirmPassword = editTextConfirmPassword.getText().toString().trim(); if (TextUtils.isEmpty(email)) { //email is empty Toast.makeText(this, "Please enter your email.", Toast.LENGTH_SHORT); return; } if (TextUtils.isEmpty(password)) { //password is empty Toast.makeText(this, "Please enter a password.", Toast.LENGTH_SHORT).show(); return; } if (TextUtils.isEmpty(confirmPassword)) { //confirm password is empty Toast.makeText(this, "Please confirm your password.", Toast.LENGTH_SHORT).show(); return; } if (!password.equals(confirmPassword)) { //password and confirm password are not the same Toast.makeText(this, "Password entries are not identical.", Toast.LENGTH_LONG).show(); return; } if (!email.substring(email.lastIndexOf("@")).equals("@unmc.edu")) { Toast.makeText(this, "Sorry, this app is not available at your institution.", Toast.LENGTH_LONG).show(); return; } //if validations are ok, we will store the information progressDialog.setMessage("Registering User..."); progressDialog.show(); firebaseAuth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() { @Override public void onComplete(@NonNull Task<AuthResult> task) { if (task.isSuccessful()) { Toast.makeText(MainActivity.this, "Registration successful.", Toast.LENGTH_SHORT).show(); writeNewUser(email); } // If sign in fails, display a message to the user. If sign in succeeds // the auth state listener will be notified and logic to handle the // signed in user can be handled in the listener. if (!task.isSuccessful()) { Toast.makeText(MainActivity.this, "Registration unsuccessful.", Toast.LENGTH_SHORT).show(); } progressDialog.dismiss(); } }); } private void writeNewUser(String email) { Users newUser = new Users(email); mDatabase.child("users").child(newUser.username).setValue(newUser); } @Override public void onClick(View view) { if (view == buttonRegister) { //register the user registerUser(); } if (view == buttonSignIn) { //sign in the user finish(); Intent openLoginAct = new Intent(this, LoginActivity.class); startActivity(openLoginAct); } } /** * ATTENTION: This was auto-generated to implement the App Indexing API. * See https://g.co/AppIndexing/AndroidStudio for more information. */ public Action getIndexApiAction() { Thing object = new Thing.Builder() .setName("Main Page") .setUrl(Uri.parse("http://[ENTER-YOUR-URL-HERE]")) .build(); return new Action.Builder(Action.TYPE_VIEW) .setObject(object) .setActionStatus(Action.STATUS_TYPE_COMPLETED) .build(); } }
package fox.test; import java.awt.AWTException; import java.awt.Robot; import java.awt.event.KeyEvent; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.openqa.selenium.By; import org.openqa.selenium.JavascriptExecutor; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class FoxTest { private static WebDriver driver; public void setUp() throws Exception { System.setProperty("webdriver.chrome.driver", "E:\\sujithwp\\qa-automation-selenium-java-someswar\\chromedriver.exe"); driver = new ChromeDriver(); driver.manage().window().maximize(); } public void tearDown() throws Exception { driver.quit(); } public void testFox() throws InterruptedException, AWTException, FileNotFoundException, IOException { driver.get("https://www.fox.com/"); driver.manage().timeouts().implicitlyWait(50, TimeUnit.SECONDS); Thread.sleep(4000); //click on show WebElement show = driver.findElement(By.xpath("//a[contains(., 'Show')]")); show.click(); Thread.sleep(4000); // scroll down and capture last 4 shows //store names to list Robot robot = new Robot(); robot.keyPress(KeyEvent.VK_PAGE_DOWN); robot.keyRelease(KeyEvent.VK_PAGE_DOWN); robot.keyPress(KeyEvent.VK_PAGE_DOWN); robot.keyRelease(KeyEvent.VK_PAGE_DOWN); robot.keyPress(KeyEvent.VK_PAGE_DOWN); robot.keyRelease(KeyEvent.VK_PAGE_DOWN); robot.keyPress(KeyEvent.VK_PAGE_DOWN); robot.keyRelease(KeyEvent.VK_PAGE_DOWN); robot.keyPress(KeyEvent.VK_PAGE_DOWN); robot.keyRelease(KeyEvent.VK_PAGE_DOWN); robot.keyPress(KeyEvent.VK_PAGE_DOWN); Thread.sleep(6000); List<WebElement> list=driver.findElements(By.xpath(" //div[@class='TileGrid_grid_vrnLT']//div/descendant::a[@class='Tile_title_2XOxg Tile_title_1kRJG']")); System.out.println("total number of suggesions"+" "+list.size()); int count= list.size(); int i; for(i=(count-4);i<count;i++) { System.out.println(list.get(i).getText()); Support.writeData(list.get(i).getText()); } } }
package api; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import javax.ws.rs.core.MediaType; import controller.Controller; @Path("qora") @Produces(MediaType.APPLICATION_JSON) public class QoraResource { @GET @Path("/stop") public String stop() { //STOP Controller.getInstance().stopAll(); System.exit(0); //RETURN return String.valueOf(true); } @GET @Path("/status") public String getStatus() { return String.valueOf(Controller.getInstance().getStatus()); } @GET @Path("/status/forging") public String getForgingStatus() { return String.valueOf(Controller.getInstance().getForgingStatus().getStatuscode()); } @GET @Path("/isuptodate") public String isUpToDate() { return String.valueOf(Controller.getInstance().isUpToDate()); } }
package com.zc.pivas.printlabel.controller; import com.google.gson.Gson; import com.zc.base.common.controller.SdDownloadController; import com.zc.base.common.exception.SdExceptionFactory; import com.zc.base.orm.mybatis.paging.JqueryStylePaging; import com.zc.base.orm.mybatis.paging.JqueryStylePagingResults; import com.zc.pivas.common.util.DictUtil; import com.zc.pivas.printlabel.entity.PrinterIPBean; import com.zc.pivas.printlabel.service.PrinterIPService; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import javax.annotation.Resource; import java.util.List; /** * 打印机配置控制类 * * @author kunkka * @version 1.0 */ @Controller() @RequestMapping(value = "/printerIP") public class PrinterIPController extends SdDownloadController { /** * 业务异常工厂 */ @Resource private SdExceptionFactory sdExceptionFactory; @Resource private PrinterIPService printerIPService; /** * 初始化页面 * * @param model * @return * @throws Exception */ @RequestMapping("/init") public String init(Model model) throws Exception { List<String> printerNames = DictUtil.getPrinterNames(); model.addAttribute("printer", printerNames); return "pivas/bottleLabel/printerIP"; } /** * 查询所有的打印机配置 * * @param bean * @param jquryStylePaging * @return * @throws Exception */ @RequestMapping(value = "/getPrinterList", produces = "application/json") @ResponseBody public String printerIPList(PrinterIPBean bean, JqueryStylePaging jquryStylePaging) throws Exception { JqueryStylePagingResults<PrinterIPBean> pagingResults = printerIPService.queryPrinterIPList(bean, jquryStylePaging); return new Gson().toJson(pagingResults); } /** * 添加打印配置项 * * @param bean 添加数据 * @return 操作结果 * @throws Exception */ @RequestMapping(value = "/addPrinter", produces = "application/json") @ResponseBody public String addPrinterIP(PrinterIPBean bean) throws Exception { // 判断名称是否存在 List<PrinterIPBean> list = printerIPService.checkPrinterIP(bean); if (list.size() > 0) { return buildFailJsonMsg("IP地址重复"); } else { int addPrinterIP = printerIPService.addPrinterIP(bean); return addPrinterIP > 0 ? buildSuccessJsonMsg("配置项添加成功") : buildFailJsonMsg("配置项添加失败"); } } /** * 修改打印机配置 * * @param bean 修改数据 * @return 操作结果 * @throws Exception */ @RequestMapping(value = "/modifyPrinter", produces = "application/json") @ResponseBody public String updatePrinterIP(PrinterIPBean bean) throws Exception { // 判断名称是否存在 PrinterIPBean printerIPBean = printerIPService.queryPrinterIPById(String.valueOf(bean.getGid())); if (printerIPBean == null) { return buildFailJsonMsg("该配置项已被删除"); } else { List<PrinterIPBean> printerIP = printerIPService.checkPrinterIP(bean); if (printerIP.size() > 0) { return buildFailJsonMsg("IP地址重复"); } int isSuccess = printerIPService.updatePrinterIP(bean); return isSuccess > 0 ? buildSuccessJsonMsg("配置项修改成功") : buildFailJsonMsg("配置项修改失败"); } } /** * 删除打印机配置 * * @return 操作结果 * @throws Exception */ @RequestMapping(value = "/delPrinter", produces = "application/json") @ResponseBody public String delPrinterIP(String ids) throws Exception { printerIPService.delPrinterIP(ids.split(",")); return buildSuccessJsonMsg(messageHolder.getMessage("common.op.success")); } /** * 查询某个打印配置项 * * @param gid 主键id * @return 操作结果 * @throws Exception */ @RequestMapping(value = "/getPrinterIPById", produces = "application/json") @ResponseBody public String queryMedicLabels(String gid) throws Exception { PrinterIPBean printerIPBean = printerIPService.queryPrinterIPById(gid); return new Gson().toJson(printerIPBean); } }
package ua.epam.course.java.block16; public class Student { public static enum specialities { MATHEMATHIC, BIOLOGIST } private static int count = 0; private Student.specialities speciality; private int number; /** * @param speciality */ public Student(Student.specialities speciality) { this.speciality = speciality; number = count++; } /* (non-Javadoc) * @see java.lang.Object#toString() */ @Override public String toString() { return "Student #" + number + " : " + speciality; } /** * @return the speciality */ public Student.specialities getSpeciality() { return speciality; } }
package process; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import org.simgrid.msg.Host; import org.simgrid.msg.HostFailureException; import org.simgrid.msg.Msg; import org.simgrid.msg.MsgException; import org.simgrid.msg.Task; import org.simgrid.msg.Process; import org.simgrid.msg.TimeoutException; import org.simgrid.msg.TransferFailureException; import taches.Message; import taches.Requete; /** * S'occupe de la connexion au sp, puis ecoute la boite aux lettres du peer. * Relou en fait parce que y a plusieurs boites aux lettres a ecouter. Celle du peer, et celles des publications de ses amis. * Eventuellement : quand on publie un truc, on met le hash dans sa boite aux lettres de publications, et on ping ses amis pour qu'ils aillent la voir. * @author otmann * */ public class Reception extends Process { private byte[] monCode; private String mbox; private HashMap<String, byte[]> amis; public Reception(Host host, String name, String[]args) throws NoSuchAlgorithmException, UnsupportedEncodingException { super(host,name,args); this.monCode = args[1].getBytes(); amis = new HashMap<String, byte[]>(); } public void main(String[] args) throws MsgException { //on se connecte connexion(args[0]+"_process0"); int i=0; while(i<6){ i++; Msg.info(Host.currentHost().getName() + " regarde si son ami publie qqch."); if(Task.listen(host.getName())){ Task msg = Task.receive(host.getName()); if(msg instanceof Message){ if(((Message) msg).getType()==0 && ((Message) msg).getMessage().equals("ping")){//on a été pingué par un poto //On vérifie si on connait le code du peer qui nous a pingé if(amis.containsKey(((Message) msg).getNomPeer()) && amis.get(((Message) msg).getNomPeer())!=null) { try { String mboxDuPeer = codeToMbox(amis.get(((Message) msg).getNomPeer())); //while(!(Task.listen(mboxDuPeer))); Msg.info("000000000000"); Task msgHashPubli= Task.receive("abc");//mboxDuPeer); Msg.info("000000000000"); if(msgHashPubli instanceof Message && ((Message) msgHashPubli).getType()==1){ //Un ami nous dit qu'il a publié un truc byte[] hash = ((Message) msgHashPubli).getHash(); Requete req = new Requete(hash); Msg.info(Host.currentHost().getName() + " voit que peer0 a mis qqch sur " + args[0] + ". Il fait une requete a " + args[0] + " en se servant du hash que peer0 a distribué à ses amis."); req.send(args[0]+"_process1"); Task.listen(Host.currentHost().getName()); Task reponse = Task.receive(Host.currentHost().getName()); if(reponse instanceof Message){ String contenu = ((Message)reponse).getMessage(); Msg.info(Host.currentHost().getName() + " a récupéré sur " + args[0] + " la donnée : \"" + contenu + "\"."); } } } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } else if(((Message) msg).getType()==2){//Un ami s'est co et le sp nous envoie son code if(this.amis.containsKey(((Message) msg).getNomPeer())){ Msg.info(host.getName()+" ajoute le code de "+((Message) msg).getNomPeer()); this.amis.put(((Message)msg).getNomPeer(),((Message)msg).getCode()); } } } } Process.sleep(500); } } /* * Le peer se connecte à son superpeer pour lui donner son code et obtenir ses amis. */ public void connexion(String sp) throws TransferFailureException, HostFailureException, TimeoutException{ Msg.info(host.getName() + " se connecte."); Message envoiCode = new Message(this.monCode, 2); envoiCode.send("superpeer0_process0"); Task.listen(Host.currentHost().getName()+"_connexion"); Task listeAmis = Task.receive(Host.currentHost().getName()+"_connexion"); if(listeAmis instanceof Message && ((Message) listeAmis).getType()==3){ for(String a : ((Message)listeAmis).getList()){ this.amis.put(a, null); } } host.setData(this.amis); Msg.info(host.getName() + " est connecté."); } public String codeToMbox(byte[] code) throws NoSuchAlgorithmException, UnsupportedEncodingException{ MessageDigest md = MessageDigest.getInstance("SHA-1"); md.reset(); md.update(code); String res = new String(md.digest(), "UTF-8"); return res; } }
package com.wozu.day14.Service; import com.wozu.day14.Model.Athlete; import java.util.Optional; public interface AthleteService { Optional<Athlete> getAthleteById(Long id); Athlete getAthleteByFirstName(String firstName); Iterable<Athlete> getAllAthletes(); void saveAthlete(Athlete athlete); Optional<Athlete> updateAthlete(Athlete newAthlete, Long id); void removeAthlete(Long id); }
package org.com.cay.service.impl; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.springframework.stereotype.Service; import org.springframework.web.multipart.commons.CommonsMultipartFile; @Service public class UploadService { public String uploadImage(CommonsMultipartFile image, String uploadPath, String realUploadPath) { InputStream is = null; OutputStream os = null; try { is = image.getInputStream(); os = new FileOutputStream(realUploadPath + File.separator + image.getOriginalFilename()); byte[] buffer = new byte[1024]; int len = 0; while ((len = is.read(buffer)) > 0) { os.write(buffer); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (is != null) { is.close(); } if (os != null) { os.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return uploadPath + "/" + image.getOriginalFilename(); } }
package com.stk123.entity; import javax.persistence.*; import java.sql.Time; import java.util.Objects; @Entity @Table(name = "STK_INTERNET_SEARCH") public class StkInternetSearchEntity { private Long searchSource; private String searchUrl; private String lastSearchText; private Time updateTime; private Long status; private String desc1; @Id @Column(name = "SEARCH_SOURCE", nullable = true, precision = 0) public Long getSearchSource() { return searchSource; } public void setSearchSource(Long searchSource) { this.searchSource = searchSource; } @Basic @Column(name = "SEARCH_URL", nullable = true, length = 1000) public String getSearchUrl() { return searchUrl; } public void setSearchUrl(String searchUrl) { this.searchUrl = searchUrl; } @Basic @Column(name = "LAST_SEARCH_TEXT", nullable = true, length = 1000) public String getLastSearchText() { return lastSearchText; } public void setLastSearchText(String lastSearchText) { this.lastSearchText = lastSearchText; } @Basic @Column(name = "UPDATE_TIME", nullable = true) public Time getUpdateTime() { return updateTime; } public void setUpdateTime(Time updateTime) { this.updateTime = updateTime; } @Basic @Column(name = "STATUS", nullable = true, precision = 0) public Long getStatus() { return status; } public void setStatus(Long status) { this.status = status; } @Basic @Column(name = "DESC_1", nullable = true, length = 500) public String getDesc1() { return desc1; } public void setDesc1(String desc1) { this.desc1 = desc1; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; StkInternetSearchEntity that = (StkInternetSearchEntity) o; return Objects.equals(searchSource, that.searchSource) && Objects.equals(searchUrl, that.searchUrl) && Objects.equals(lastSearchText, that.lastSearchText) && Objects.equals(updateTime, that.updateTime) && Objects.equals(status, that.status) && Objects.equals(desc1, that.desc1); } @Override public int hashCode() { return Objects.hash(searchSource, searchUrl, lastSearchText, updateTime, status, desc1); } }
package com.example.admin.fpbackend.TeamActivity; import android.app.Dialog; import android.content.Intent; import android.os.Bundle; import android.provider.ContactsContract; import android.support.v7.app.AppCompatActivity; import android.util.Log; import android.view.View; import android.widget.ArrayAdapter; import android.widget.EditText; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.example.admin.fpbackend.ContactsActivity.ContactsActivity; import com.example.admin.fpbackend.DataObjects.TeamBindingClass; import com.example.admin.fpbackend.R; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import java.util.List; import butterknife.BindView; import butterknife.ButterKnife; public class TeamActivity extends AppCompatActivity { String consultant_ref; String Housing_ref; @BindView(R.id.spinnerSetTeam) Spinner spinnerSetTeam; private Dialog dialog; DatabaseReference Teams_Info; DatabaseReference Teams_Consul; private ArrayAdapter<String> adapter; public static final String TAG = "TeamActivityTAG"; String TeamRefrence; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_team); Intent intent = getIntent(); consultant_ref = intent.getStringExtra(getString(R.string.consultant_Refrence)); Housing_ref = intent.getStringExtra(getString(R.string.Housing_Refrence)); ButterKnife.bind(this); FirebaseDatabase database = FirebaseDatabase.getInstance(); Teams_Info = database.getReference("Teams_Info"); Teams_Consul = database.getReference("Data_Binding").child("Teams_Consult"); adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1); setSpinnerItems(); Log.d(TAG, "onCreate: "+Housing_ref); } public void setSpinnerItems() { Teams_Info.orderByKey().limitToLast(10).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { adapter.clear(); for (DataSnapshot d : dataSnapshot.getChildren()) { adapter.add(d.getValue().toString()); } adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinnerSetTeam.setAdapter(adapter); adapter.notifyDataSetChanged(); } @Override public void onCancelled(DatabaseError databaseError) { } }); } public void SetTeam(View view) { Teams_Info.orderByValue().equalTo(spinnerSetTeam.getSelectedItem().toString()).addValueEventListener(new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { for (DataSnapshot d : dataSnapshot.getChildren()) { TeamRefrence = d.getKey(); } SetDataBinding(TeamRefrence); } @Override public void onCancelled(DatabaseError databaseError) { } }); } public void SetDataBinding(String Refrence) { TeamBindingClass team = new TeamBindingClass(TeamRefrence,consultant_ref); Teams_Consul.push().setValue(team, new DatabaseReference.CompletionListener() { @Override public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) { Toast.makeText(TeamActivity.this, "Member Added to the Team Succefully", Toast.LENGTH_SHORT).show(); Intent intent = new Intent(TeamActivity.this, ContactsActivity.class); intent.putExtra(getString(R.string.consultant_Refrence),consultant_ref); intent.putExtra(getString(R.string.Housing_Refrence),Housing_ref); intent.putExtra(getString(R.string.Team_Refrence),TeamRefrence); startActivity(intent); } }); } public void AddNewTeam(View view) { dialog = new Dialog(this); dialog.setTitle("Add new Team"); dialog.setContentView(R.layout.add_teaminfo); dialog.show(); } public void AddTeamtoDB(View view) { EditText txtTeamName = dialog.findViewById(R.id.txtAddTeam_name); Teams_Info.push().setValue(txtTeamName.getText().toString(), new DatabaseReference.CompletionListener() { @Override public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) { Toast.makeText(TeamActivity.this, "Addes Succefully", Toast.LENGTH_SHORT).show(); dialog.dismiss(); } }); } }
package Voting; import java.io.*; import java.security.*; import java.security.spec.*; import javax.crypto.*; import javax.crypto.spec.*; public class Encrypt { PublicKey publicKey; PrivateKey privateKey; byte[] data; public void createKey() { KeyPairGenerator kpg; try { kpg = KeyPairGenerator.getInstance("RSA"); kpg.initialize(1024); KeyPair kp = kpg.genKeyPair(); publicKey = kp.getPublic(); privateKey = kp.getPrivate(); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void encrypt(String in, String out){ try { FileInputStream file = new FileInputStream(in); byte[] text = new byte[file.available()]; file.read(text); file.close(); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, publicKey); byte[] ciphertext = cipher.doFinal(text); FileOutputStream cipherfile = new FileOutputStream(out); cipherfile.write(ciphertext); cipherfile.close(); } catch (Exception e) { e.printStackTrace(); } } public void decrypt(String in, String out){ try { FileInputStream cipherfile = new FileInputStream(in); byte[] ciphertext = new byte[cipherfile.available()]; cipherfile.read(ciphertext); cipherfile.close(); Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, privateKey); byte[] text = cipher.doFinal(ciphertext); FileOutputStream file = new FileOutputStream(out); file.write(text); file.close(); } catch (Exception e) { e.printStackTrace(); } } }
package com.example.wordapplication; import androidx.appcompat.app.AlertDialog; import androidx.appcompat.app.AppCompatActivity; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Configuration; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.provider.UserDictionary; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TableLayout; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; public class MainActivity extends AppCompatActivity { WordsDBHelper mDbHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //为ListView注册上下文菜单 ListView list = (ListView) findViewById(R.id.IstWords); registerForContextMenu(list); //创建SQLiteOpenHelper对象,注意第一次运行时,此时数据库并没有被创建 mDbHelper = new WordsDBHelper(this); //在列表显示全部单词 final ArrayList<Map<String, String>> items = getAll(); setWordsListView(items); // 点击事件 if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { list.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Bundle bundle=new Bundle(); bundle.putSerializable(Words.Word.COLUMN_NAME_WORD,items.get(position).get(Words.Word.COLUMN_NAME_WORD)); bundle.putSerializable(Words.Word.COLUMN_NAME_MEANING,items.get(position).get(Words.Word.COLUMN_NAME_MEANING)); bundle.putSerializable(Words.Word.COLUMN_NAME_SAMPLE,items.get(position).get(Words.Word.COLUMN_NAME_SAMPLE)); Intent intent=new Intent(MainActivity.this,FrameActivity.class); intent.putExtras(bundle); startActivity(intent); } }); } if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { list.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { TextView LandWord = findViewById(R.id.LandWord); TextView LandMeaning = findViewById(R.id.LandMeaning); TextView LandSqmple = findViewById(R.id.LandSample); LandWord.setText(items.get(position).get(Words.Word.COLUMN_NAME_WORD)); LandMeaning.setText(items.get(position).get(Words.Word.COLUMN_NAME_MEANING)); LandSqmple.setText(items.get(position).get(Words.Word.COLUMN_NAME_SAMPLE)); //Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT).show(); } }); } } private ArrayList<Map<String, String>> getAll() { SQLiteDatabase db = mDbHelper.getReadableDatabase(); String sql="select * from words"; Cursor c=db.rawQuery(sql,new String[]{}); return ConvertCursor2List(c); } private ArrayList<Map<String, String>> ConvertCursor2List(Cursor c) { ArrayList<Map<String, String>> items = new ArrayList<Map<String, String>>(); c.moveToNext(); while (true) { Map<String,String> map =new HashMap<>(); if(c.isLast()){ map.put("id", c.getString(0)); map.put(Words.Word.COLUMN_NAME_WORD, c.getString(1)); map.put(Words.Word.COLUMN_NAME_MEANING, c.getString(2)); map.put(Words.Word.COLUMN_NAME_SAMPLE, c.getString(3)); items.add(map); break; } else { map.put("id", c.getString(0)); map.put(Words.Word.COLUMN_NAME_WORD, c.getString(1)); map.put(Words.Word.COLUMN_NAME_MEANING, c.getString(2)); map.put(Words.Word.COLUMN_NAME_SAMPLE, c.getString(3)); items.add(map); c.moveToNext(); } } return items; } @Override protected void onDestroy(){ super.onDestroy(); mDbHelper.close(); } public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement switch (id) { case R.id.action_search: //查找 SearchDialog(); return true; case R.id.action_insert: //新增单词 InsertDialog(); return true; case R.id.action_help: Toast.makeText(MainActivity.this, "你点击了帮助", Toast.LENGTH_SHORT).show(); return true; } return super.onOptionsItemSelected(item); } //使用Sql语句查找 private ArrayList<Map<String, String>> SearchUseSql(String strWordSearch) { SQLiteDatabase db = mDbHelper.getReadableDatabase(); String sql="select * from words where word like ? order by word desc"; Cursor c=db.rawQuery(sql,new String[]{"%"+strWordSearch+"%"}); return ConvertCursor2List(c); } //使用query方法查找 private ArrayList<Map<String, String>> Search(String strWordSearch) { SQLiteDatabase db = mDbHelper.getReadableDatabase(); String[] projection = { Words.Word._ID, Words.Word.COLUMN_NAME_WORD, Words.Word.COLUMN_NAME_MEANING, Words.Word.COLUMN_NAME_SAMPLE }; String sortOrder = Words.Word.COLUMN_NAME_WORD + " DESC"; String selection = Words.Word.COLUMN_NAME_WORD + " LIKE ?"; String[] selectionArgs = {"%"+strWordSearch+"%"}; Cursor c = db.query( Words.Word.TABLE_NAME, // The table to query projection, // The columns to return selection, // The columns for the WHERE clause selectionArgs, // The values for the WHERE clause null, // don't group the rows null, // don't filter by row groups sortOrder // The sort order ); return ConvertCursor2List(c); } private void SearchDialog() { final TableLayout tableLayout = (TableLayout) getLayoutInflater().inflate(R.layout.searchterm, null); new AlertDialog.Builder(this) .setTitle("查找单词")//标题 .setView(tableLayout)//设置视图 // 确定按钮及其动作 .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { String txtSearchWord=((EditText)tableLayout.findViewById(R.id.txtSearchWord)).getText().toString(); ArrayList<Map<String, String>> items=null; //既可以使用Sql语句查询,也可以使用方法查询 items=SearchUseSql(txtSearchWord); //items=Search(txtSearchWord); if(items.size()>0) { Bundle bundle=new Bundle(); bundle.putSerializable("result",items); Intent intent=new Intent(MainActivity.this,SearchActivity.class); intent.putExtras(bundle); startActivity(intent); }else Toast.makeText(MainActivity.this,"没有找到", Toast.LENGTH_LONG).show(); } }) //取消按钮及其动作 .setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }) .create()//创建对话框 .show();//显示对话框 } //新增对话框 private void InsertDialog() { final TableLayout tableLayout = (TableLayout) getLayoutInflater().inflate(R.layout.insert, null); new AlertDialog.Builder(this) .setTitle("新增单词")//标题 .setView(tableLayout)//设置视图 // 确定按钮及其动作 .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { String strWord=((EditText)tableLayout.findViewById(R.id.txtWord)).getText().toString(); String strMeaning=((EditText)tableLayout.findViewById(R.id.txtMeaning)).getText().toString(); String strSample=((EditText)tableLayout.findViewById(R.id.txtSample)).getText().toString(); //既可以使用Sql语句插入,也可以使用使用insert方法插入 InsertUserSql(strWord, strMeaning, strSample); //Insert(strWord, strMeaning, strSample); ArrayList<Map<String, String>> items = getAll(); setWordsListView(items); } }) //取消按钮及其动作 .setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }) .create()//创建对话框 .show();//显示对话框 } //使用Sql语句插入单词 private void InsertUserSql(String strWord, String strMeaning, String strSample){ String sql="insert into words(word,meaning,sample) values(?,?,?)"; //Gets the data repository in write mode*/ SQLiteDatabase db = mDbHelper.getWritableDatabase(); db.execSQL(sql,new String[]{strWord,strMeaning,strSample}); } //使用insert方法增加单词 private void Insert(String strWord, String strMeaning, String strSample) { //Gets the data repository in write mode*/ SQLiteDatabase db = mDbHelper.getWritableDatabase(); // Create a new map of values, where column names are the keys ContentValues values = new ContentValues(); values.put(Words.Word.COLUMN_NAME_WORD, strWord); values.put(Words.Word.COLUMN_NAME_MEANING, strMeaning); values.put(Words.Word.COLUMN_NAME_SAMPLE, strSample); // Insert the new row, returning the primary key value of the new row long newRowId; newRowId = db.insert(Words.Word.TABLE_NAME,null,values); } //设置适配器,在列表中显示单词 private void setWordsListView(ArrayList<Map<String, String>> items){ SimpleAdapter adapter = new SimpleAdapter(this, items, R.layout.item, new String[]{"id", Words.Word.COLUMN_NAME_WORD, Words.Word.COLUMN_NAME_MEANING, Words.Word.COLUMN_NAME_SAMPLE, }, new int[]{R.id.textId,R.id.textViewWord, R.id.textViewMeaning, R.id.textViewSample}); ListView list = (ListView) findViewById(R.id.IstWords); list.setAdapter(adapter); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { getMenuInflater().inflate(R.menu.contextmenu_wordslistview, menu); } @Override public boolean onContextItemSelected(MenuItem item) { TextView textId=null; TextView textWord=null; TextView textMeaning=null; TextView textSample=null; AdapterView.AdapterContextMenuInfo info=null; View itemView=null; switch (item.getItemId()){ case R.id.action_delete: //删除单词 info=(AdapterView.AdapterContextMenuInfo)item.getMenuInfo(); itemView=info.targetView; textId =(TextView)itemView.findViewById(R.id.textId); if(textId!=null){ String strId=textId.getText().toString(); DeleteDialog(strId); } break; case R.id.action_update: //修改单词 info=(AdapterView.AdapterContextMenuInfo)item.getMenuInfo(); itemView=info.targetView; textId =(TextView)itemView.findViewById(R.id.textId); textWord =(TextView)itemView.findViewById(R.id.textViewWord); textMeaning =(TextView)itemView.findViewById(R.id.textViewMeaning); textSample =(TextView)itemView.findViewById(R.id.textViewSample); if(textId!=null && textWord!=null && textMeaning!=null && textSample!=null){ String strId=textId.getText().toString(); String strWord=textWord.getText().toString(); String strMeaning=textMeaning.getText().toString(); String strSample=textSample.getText().toString(); UpdateDialog(strId, strWord, strMeaning, strSample); } break; } return true; } //使用Sql语句更新单词 private void UpdateUseSql(String strId,String strWord, String strMeaning, String strSample) { SQLiteDatabase db = mDbHelper.getReadableDatabase(); String sql="update words set word=?,meaning=?,sample=? where _id=?"; db.execSQL(sql, new String[]{strWord, strMeaning, strSample,strId}); } //使用方法更新 private void Update(String strId,String strWord, String strMeaning, String strSample) { SQLiteDatabase db = mDbHelper.getReadableDatabase(); // New value for one column ContentValues values = new ContentValues(); values.put(Words.Word.COLUMN_NAME_WORD, strWord); values.put(Words.Word.COLUMN_NAME_MEANING, strMeaning); values.put(Words.Word.COLUMN_NAME_SAMPLE, strSample); String selection = Words.Word._ID + " = ?"; String[] selectionArgs = {strId}; int count = db.update( Words.Word.TABLE_NAME, values, selection, selectionArgs); } private void UpdateDialog(final String strId, String strWord, String strMeaning, String strSample) { final TableLayout tableLayout = (TableLayout) getLayoutInflater().inflate(R.layout.insert, null); ((EditText)tableLayout.findViewById(R.id.txtWord)).setText(strWord); ((EditText)tableLayout.findViewById(R.id.txtMeaning)).setText(strMeaning); ((EditText)tableLayout.findViewById(R.id.txtSample)).setText(strSample); new AlertDialog.Builder(this) .setTitle("修改单词") //标题 .setView(tableLayout) //设置视图 // 确定按钮及其动作 .setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { String strNewWord = ((EditText) tableLayout.findViewById(R.id.txtWord)).getText().toString(); String strNewMeaning = ((EditText) tableLayout.findViewById(R.id.txtMeaning)).getText().toString(); String strNewSample = ((EditText) tableLayout.findViewById(R.id.txtSample)).getText().toString(); //既可以使用Sql语句更新,也可以使用使用update方法更新 UpdateUseSql(strId, strNewWord, strNewMeaning, strNewSample); // Update(strId, strNewWord, strNewMeaning, strNewSample); setWordsListView(getAll()); } }) //取消按钮及其动作 .setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }) .create()//创建对话框 .show();//显示对话框 } private void DeleteDialog(final String strId) { new AlertDialog.Builder(this).setTitle("删除单词").setMessage("是否真的删除单词?").setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { //既可以使用Sql语句删除,也可以使用使用delete方法删除 DeleteUseSql(strId); //Delete(strId); setWordsListView(getAll()); } }).setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { } }).create().show(); } //删除单词 private void DeleteUseSql(String strId) { String sql="delete from words where _id='"+strId+"'"; //Gets the data repository in write mode*/ SQLiteDatabase db = mDbHelper.getReadableDatabase(); db.execSQL(sql); } private void Delete(String strId) { SQLiteDatabase db = mDbHelper.getReadableDatabase(); // 定义where子句 String selection = Words.Word._ID + " = ?"; // 指定占位符对应的实际参数 String[] selectionArgs = {strId}; // Issue SQL statement. db.delete(Words.Word.TABLE_NAME, selection, selectionArgs); } }
package sch.frog.calculator.compile.syntax; import sch.frog.calculator.exception.CompileException; import sch.frog.calculator.compile.lexical.IToken; import sch.frog.calculator.util.collection.IList; /** * 语法树构建器 */ public interface ISyntaxTreeBuilder { /** * 将表达式构建为语法树 * @param tokens token集合 * @return 语法树 */ ISyntaxNode build(IList<IToken> tokens) throws CompileException; }
package mc.kurunegala.bop.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import mc.kurunegala.bop.dao.UploadsMapper; import mc.kurunegala.bop.model.Uploads; @Service public class UploadSearvice { @Autowired UploadsMapper mapper; public void add(Uploads upload) { mapper.insertSelective(upload); } }
package ru.shikhovtsev.exception; public class AtmException extends RuntimeException { }
import org.junit.Assert; import org.junit.Test; import java.util.Stack; public class MyStackTests { StackAPI<Integer> myStack = new MyStack<Integer>(); Stack<Integer> javaStack = new Stack<Integer>(); private void clearStacks() { myStack.clear(); javaStack.clear(); } @Test public void testPushPop() { clearStacks(); for (int i = 0; i < 100; i++) { myStack.push(i); javaStack.push(i); } for (int i = 0; i < 100; i++) { int myRemove = myStack.pop(); int javaRemove = javaStack.pop(); Assert.assertEquals(myRemove, javaRemove); } Assert.assertEquals(myStack.size(), javaStack.size()); } @Test public void testContains() { clearStacks(); for (int i = 0; i < 100; i++) { myStack.push(i); javaStack.push(i); } for (int i = 0; i < 200; i++) { boolean myBool = myStack.contains(i); boolean javaBool = javaStack.contains(i); Assert.assertEquals(myBool, javaBool); } } @Test public void testRemove() { clearStacks(); for (int i = 0; i < 100; i++) { myStack.push(i); javaStack.push(i); } for (int i = 0; i < 100; i++) { int myRemoved = myStack.pop(); int javaRemoved = javaStack.pop(); Assert.assertEquals(myRemoved, javaRemoved); } } }
package me.walkerknapp.cfi; import java.io.File; import java.io.IOException; import java.util.concurrent.CompletableFuture; public interface ProcessRunner { CompletableFuture<Void> start(File workingDir, String... args) throws IOException; }
package pl.qaaacademy.todo.interfaces; public interface StatusChangable { void toggleStatus(); void complete(); }
import java.io.FileNotFoundException; import java.io.IOException; import virtualdisk.DiskThread; import virtualdisk.VirtualDisk; import common.Constants; import dblockcache.DBufferCache; import dfs.DFS; public class TestMain { public static void main(String[] args) throws FileNotFoundException, IOException { DFS deFiler = new DFS(); System.out.println("running test main"); System.out.println("Index of first data block: "+ Constants.DATA_BLOCK_FIRST); System.out.println("Number of map blocks: "+ Constants.NUM_OF_MAP_BLOCKS); System.out.println("Number of Inode blocks: "+ Constants.NUM_OF_INODE_BLOCKS); //not the number of inodes, the number of blocks used to store them DBufferCache cache = new DBufferCache(Constants.NUM_OF_CACHE_BLOCKS); deFiler.myCache = cache; VirtualDisk disk = new VirtualDisk("Seans disk", false); cache.myVD = disk; DiskThread diskThread = new DiskThread(disk); diskThread.start(); ClientThread client1 = new ClientThread(deFiler); client1.start(); } }
package com.hg.mylifetomorrow.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; public class MLTUtil { public final static String DT_FORMAT="yyyy-MM-dd HH:mm:ss a"; public final static String DT_FORMAT3="yyyy-MM-dd"; public final static String DT_FORMAT2="yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"; private final static SimpleDateFormat sdf =new SimpleDateFormat(); public static String getCurrentDateTime(final String pattern){ java.util.Date dt = new java.util.Date(); sdf.applyPattern(pattern); return sdf.format(dt); } public static String getDateInDisplayFormat(final String date) throws ParseException{ final SimpleDateFormat ft = new SimpleDateFormat(DT_FORMAT, Locale.getDefault()); final java.util.Date t=ft.parse(date); ft.applyPattern("MMM dd, yyyy hh:mm:ss a"); return ft.format(t); } public static String getDateToString(final Date date) throws ParseException{ final SimpleDateFormat sdf = new SimpleDateFormat(DT_FORMAT, Locale.getDefault()); sdf.applyPattern(DT_FORMAT3); return sdf.format(date); } public static String getDateToString2(final Date date) throws ParseException{ final SimpleDateFormat sdf = new SimpleDateFormat(DT_FORMAT2, Locale.getDefault()); sdf.applyPattern(DT_FORMAT3); return sdf.format(date); } public static Date getStringToDate(final String date) throws ParseException{ final SimpleDateFormat sdf = new SimpleDateFormat(DT_FORMAT3, Locale.getDefault()); sdf.applyPattern(DT_FORMAT3); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); return sdf.parse(date); } public static void main(String a[]) throws ParseException{ System.out.println(getStringToDate("1980-05-27")); } }
package ua.siemens.dbtool.service; import ua.siemens.dbtool.model.entities.Activity; import ua.siemens.dbtool.model.timesheet.DayEntryActivityInfo; import java.util.Collection; /** * Service interface for {@link DayEntryActivityInfo} * * @author Perevoznyk Pavlo * creation date 15 Feb 2018 * @version 1.0 */ public interface DayEntryActivityInfoService { void save(DayEntryActivityInfo info); void update(DayEntryActivityInfo info); void delete(Long id); DayEntryActivityInfo findById(Long id); Collection<DayEntryActivityInfo> findAll(); Collection<DayEntryActivityInfo> findByActivity(Activity activity); double findActivityHours(Activity activity); }
package library; public class IntegerOrdList extends OrderedList { //compare function defined below @Override protected int compare(Object obj1, Object obj2){ return ((Integer)obj1).intValue() - ((Integer)obj2).intValue(); } }
package interfaces; import java.util.List; import modelo.tableUsuarioDto; public interface CRUD { public List listar(); public tableUsuarioDto list(long cedula_usuario); }
package src.server_main; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.io.InputStream; import java.net.InetSocketAddress; import com.sun.net.httpserver.HttpExchange; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; public class HttpServ implements Public_Element, Runnable{ HttpServer server; File html_f; FileInputStream html_stream; byte[] buf = null; class MyHandler implements HttpHandler { public void handle(HttpExchange t) throws IOException { String request_path = t.getRequestURI().toString(); boolean not_page = false; boolean not_image_stream = true; OutputStream os; Logd.Log_w(L_INFO, "html Request: "+request_path); //Logd.Log_w(L_INFO, "" + "image.jpg?test".split("test")[0]); try{ html_f = new File("./html/exception.html"); }catch(Exception e){ //html_f = new File("./html/exception.html"); Logd.Log_w(L_ERROR, "/exception"+" page does not exist"); } /*Open file*/ if(request_path.equals("/")){ try{ html_f = new File("./html/index.html"); }catch(Exception e){ //html_f = new File("./html/exception.html"); Logd.Log_w(L_ERROR, "/index"+" page does not exist"); } } if(request_path.equals("/jquery-1.9.1.min.js")){ try{ html_f = new File("./html/jquery-1.9.1.min.js"); }catch(Exception e){ //html_f = new File("./html/exception.html"); Logd.Log_w(L_ERROR, "/jquery"+" page does not exist"); } } if(request_path.equals("/dirty.png")){ try{ html_f = new File("./html/dirty.png"); }catch(Exception e){ //html_f = new File("./html/exception.html"); Logd.Log_w(L_ERROR, "/dirty.png"+" page does not exist"); } } if(request_path.split("nocache")[0].equals("/image.jpg?")){ if(buf_handler.rw_st_sig(S_READ) == 0){//it`s not available yet Logd.Log_w(L_INFO, "image stream not yet ready"); try{ html_f = new File("./html/funny_coffee.jpg"); }catch(Exception e){ Logd.Log_w(L_ERROR, "/funny_coffee.jpg"+" page does not exist"); } not_image_stream = true; }else{ if(buf_handler._buf_handler(S_READ) == E_READ){ try{ html_f = new File("./html/funny_coffee.jpg"); }catch(Exception e){ Logd.Log_w(L_ERROR, "/funny_coffee.jpg"+" page does not exist"); } not_image_stream = true; }else{ buf = new byte[pStream.to_server_in.available()]; pStream.to_server_in.read(buf); not_image_stream = false; } } } if(request_path.equals("/handler.html") && t.getRequestMethod().toUpperCase().equals("POST")){ String direction = null; InputStream req_body = t.getRequestBody(); byte body_buf[] = new byte[req_body.available()]; int num = req_body.read(body_buf); String body = new String(body_buf,0,num,"UTF-8"); //force it to utf-8 if(body.equals("FWD")){//forward direction = "f"; }else if(body.equals("BCK")){//backward direction = "b"; }else if(body.equals("STP")){//stop direction = "sp"; }else if(body.equals("RHT")){//right direction = "r"; }else if(body.equals("LFT")){//left direction = "l"; }else if(body.equals("R_R")){//right rotate direction = "rr"; }else if(body.equals("R_L")){//left rotate direction = "rl"; }else{ direction = "unknown"; } if(!direction.equals("unknown")){ client_connector.control(direction); } Logd.Log_w(L_DEBUG, "control: "+direction); not_page = true; } if(!not_page){ /*it's a page*/ if(not_image_stream){ /*Create file stream*/ try{ html_stream = new FileInputStream(html_f); }catch(Exception ioe){ Logd.Log_w(L_ERROR, ""+ioe); } /*Send*/ t.sendResponseHeaders(200, html_f.length()); buf = new byte[html_stream.available()]; html_stream.read(buf); } os = t.getResponseBody(); os.write(buf); os.flush(); os.close(); html_stream.close(); buf = null; } } } public HttpServ(){ try{ server = HttpServer.create(new InetSocketAddress(8000), 0); }catch(Exception e){ Logd.Log_w(L_ERROR, "Create HttpServer Failed"); } } public void HttpCreate(){ server.createContext("/", new MyHandler()); server.createContext("/dirty.png", new MyHandler()); server.createContext("/handler.html", new MyHandler()); server.createContext("/jquery-1.9.1.min.js", new MyHandler()); server.createContext("/image.jpg", new MyHandler()); server.setExecutor(null); // creates a default executor } public void HttpStart(){ try{ server.start(); System.out.println("Http server start..."); Logd.Log_w(L_DEBUG, "http server start"); }catch(Exception e){ Logd.Log_w(L_ERROR, ""+e); } } @Override public void run() { HttpCreate(); HttpStart(); } }
package five; import javax.swing.*; /** * <li>1. Prost ili primitivni -> 8</li> * <li>2. Niz a zatim String</li> */ public class ContinueDemo { public static void main(String[] args) { String text = "petar pan je pojeo pancakes"; char[] nizKaraktera = text.toCharArray();//ime varijable određenog tipa int brojac = 0; for(int i = 0; i<nizKaraktera.length; i++){ char karakter = nizKaraktera[i]; if(karakter != 'p'){ continue; } brojac++; } //ime tipa String poruka = String.format("Broj ponavljanja slova p je '%s'", brojac); JOptionPane.showMessageDialog(null, poruka); } }
/** * Created by will.schick on 4/7/16. */ public class DatabaseConfiguration { /** * The configuration here can later be pulled out to a file or program argument. * @param args * @throws Exception */ public static void main(String[] args) throws Exception{ //create an H2 database for development //this is in-memeory //if you want this to persist across multiple runs of //the application, use: // // "jdbc:h2:./dev_db;DB_CLOSE_DELAY=-1" // // this will put the database in a file called dev_db // DatabaseService databaseService = new DatabaseService( "org.h2.Driver", "jdbc:h2:mem:test_database;DB_CLOSE_DELAY=-1", //"jdbc:h2:./dev_db;DB_CLOSE_DELAY=-1", "fake", "fake"); /* for MYSQL, all you need to do is change the driver and url DatabaseService databaseService = new DatabaseService( "com.mysql.jdbc.Driver", "jdbc:mysql://localhost/test, "fake", "fake"); */ //create the tables if they do not exist databaseService.createDatabaseIfItDoesNotExist(); //write things to stuff databaseService.writeAThing("ruff"); databaseService.writeAThing("meow"); databaseService.writeAThing("oink"); databaseService.writeAThing("baaah"); //display all of the things System.out.println("all of the things:"); for (String s:databaseService.getAllThings()){ System.out.println("\t" + s); } } }
package cn.itcast.bookstore.category.web.servlet.admin; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import cn.itcast.bookstore.category.domain.Category; import cn.itcast.bookstore.category.service.CategoryService; import cn.itcast.commons.CommonUtils; import cn.itcast.servlet.BaseServlet; public class AdminCategoryServlet extends BaseServlet { private CategoryService categoryService = new CategoryService(); /** * 查看所有分类 * @param request * @param response * @return * @throws ServletException * @throws IOException */ public String findAll(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { List<Category> categoryList = categoryService.findAll(); request.setAttribute("categoryList", categoryList); return "f:/adminjsps/admin/category/list.jsp"; } /** * 添加分类 * @param request * @param response * @return * @throws ServletException * @throws IOException */ public String add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Category category = CommonUtils.toBean(request.getParameterMap(), Category.class); category.setCid(CommonUtils.uuid()); categoryService.add(category); return findAll(request,response); } /** * 删除分类 * @param request * @param response * @return * @throws ServletException * @throws IOException */ public String delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String cid = request.getParameter("cid"); try{ categoryService.delete(cid); return findAll(request,response); }catch(CategoryException e){ request.setAttribute("msg", e.getMessage()); return "f:/adminjsps/msg.jsp"; } } /** * 修改之前的加载工作 * @param request * @param response * @return * @throws ServletException * @throws IOException */ public String editPre(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String cid = request.getParameter("cid"); request.setAttribute("category", categoryService.load(cid)); return "f:/adminjsps/admin/category/mod.jsp"; } public String edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Category category = CommonUtils.toBean(request.getParameterMap(), Category.class); categoryService.edit(category); return findAll(request,response); } }
/* * Created on Mar 2, 2007 * */ package com.citibank.ods.modules.client.customerprvtcmpl.functionality; import com.citibank.ods.common.dataset.DataSet; import com.citibank.ods.common.entity.BaseODSEntity; import com.citibank.ods.common.functionality.ODSListFnc; import com.citibank.ods.common.functionality.valueobject.BaseFncVO; import com.citibank.ods.common.functionality.valueobject.BaseODSFncVO; import com.citibank.ods.modules.client.customerprvtcmpl.functionality.valueobject.BaseCustomerPrvtCmplListFncVO; import com.citibank.ods.modules.client.customerprvtcmpl.functionality.valueobject.CustomerPrvtCmplListFncVO; import com.citibank.ods.persistence.pl.dao.BaseTplCustomerPrvtCmplDAO; import com.citibank.ods.persistence.pl.dao.TplCustomerPrvtCmplDAO; import com.citibank.ods.persistence.pl.dao.factory.ODSDAOFactory; /** * @author gerson.a.rodrigues * */ public class CustomerPrvtCmplListFnc extends BaseCustomerPrvtCmplListFnc implements ODSListFnc { /* * (non-Javadoc) * @see com.citibank.ods.modules.client.customer.functionality.CustomerListFnc#getDAO() */ protected BaseTplCustomerPrvtCmplDAO getDAO() { return ODSDAOFactory.getInstance().getTplCustomerPrvtCmplDAO(); } /* * Cria uma Instancia do FncVO * @see com.citibank.ods.common.functionality.BaseFnc#createFncVO() */ public BaseFncVO createFncVO() { return new CustomerPrvtCmplListFncVO(); } /* * O metodo list List conforme os paramentros de busca * @see com.citibank.ods.common.functionality.ODSListFnc#list(com.citibank.ods.common.functionality.valueobject.BaseFncVO) */ public void list( BaseFncVO fncVO_ ) { // Instanciação do CustomerDAO, obtendo a instância da Factory //Execução do método listCustomer com os parâmetros de busca //Atualiza o DataSet do FncVO com o retornado pelo método, caso o // retorno não seja null // Obtém a instância do DAO necessário TplCustomerPrvtCmplDAO tplCustomerPrvtCmplDAO = ( TplCustomerPrvtCmplDAO ) this.getDAO(); CustomerPrvtCmplListFncVO customerCmplListFncVO = ( CustomerPrvtCmplListFncVO ) fncVO_; DataSet results = tplCustomerPrvtCmplDAO.list( customerCmplListFncVO.getEmNbrSrc(), // customerCmplListFncVO.getGlbRevenSysOffcrNbrSrc(), customerCmplListFncVO.getPrvtCustNbrSrc(), // customerCmplListFncVO.getPrvtKeyNbrSrc(), // customerCmplListFncVO.getCustNbrSrc(), // customerCmplListFncVO.getWealthPotnlCodeSrc(), // customerCmplListFncVO.getOffcrNbrSrc(), // customerCmplListFncVO.getClassCmplcCodeSrc(),// BaseODSEntity.C_REC_STAT_CODE_ACTIVE,// customerCmplListFncVO.getCustFullNameSrc());// customerCmplListFncVO.setResults( results ); if ( results.size() > 0 ) { super.load( ( BaseCustomerPrvtCmplListFncVO ) fncVO_ ); customerCmplListFncVO.addMessage( BaseODSFncVO.C_MESSAGE_SUCESS ); } else { customerCmplListFncVO.addMessage( BaseODSFncVO.C_NO_REGISTER_FOUND ); } } /* * (non-Javadoc) * @see com.citibank.ods.common.functionality.ODSListFnc#load(com.citibank.ods.common.functionality.valueobject.BaseFncVO) */ public void load( BaseFncVO fncVO_ ) { CustomerPrvtCmplListFncVO customerPrvtCmplListFncVO = ( CustomerPrvtCmplListFncVO ) fncVO_; getDomainLists( customerPrvtCmplListFncVO ); if ( customerPrvtCmplListFncVO.isFromSearch() ) { loadCustomerText( customerPrvtCmplListFncVO ); loadOfficerText( customerPrvtCmplListFncVO ); customerPrvtCmplListFncVO.setFromSearch( false ); } else { customerPrvtCmplListFncVO.setCustNbrSrc( null ); customerPrvtCmplListFncVO.setCustTextSrc( null ); customerPrvtCmplListFncVO.setOffcrNbrSrc( null ); customerPrvtCmplListFncVO.setOffcrTextSrc( null ); customerPrvtCmplListFncVO.setGlbRevenSysOffcrNbrSrc( null ); customerPrvtCmplListFncVO.setResults( null ); } } /* * (non-Javadoc) * @see com.citibank.ods.common.functionality.ODSListFnc#validateList(com.citibank.ods.common.functionality.valueobject.BaseFncVO) */ public void validateList( BaseFncVO fncVO_ ) { /** * "[Method description]" * * @param * @return * @exception * @see */ } }
package com.gxtc.huchuan.data; import com.gxtc.huchuan.bean.LiveListBean; import com.gxtc.huchuan.http.ApiCallBack; import com.gxtc.huchuan.ui.live.list.LiveListContract; import java.util.ArrayList; import java.util.List; /** * Created by Gubr on 2017/2/27. */ public class LiveListRepository implements LiveListContract.Source { @Override public void getLiveListDatas(ApiCallBack<List<LiveListBean>> callBack, int count, int id) { ArrayList<LiveListBean> objects = new ArrayList<>(); for (int i = 0; i < 20; i++) { objects.add(new LiveListBean()); } callBack.onSuccess(objects); } @Override public List<LiveListBean> getHistory(String currentType) { return null; } @Override public void saveHistory(int id, List<LiveListBean> data) { } @Override public void destroy() { } }
package egovframework.com.tag; import java.text.MessageFormat; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.jsp.JspException; import javax.servlet.jsp.JspTagException; import javax.servlet.jsp.JspWriter; import javax.servlet.jsp.tagext.TagSupport; import org.springframework.stereotype.Controller; import org.springframework.web.context.ContextLoader; import org.springframework.web.context.WebApplicationContext; import egovframework.rte.fdl.property.EgovPropertyService; import enc.C; /** * <pre> * system : * menu : * source : ReportTag.java * description : * </pre> * * @version * * <pre> * * 1.0 2010-10-21 * 1.1 * </pre> */ public class ReportTag extends TagSupport { /** EgovPropertyService */ /* @Resource(name = "propertiesService") private static EgovPropertyService propertiesService; */ //실서버 private static String REPORT_SERVER_IP = "203.236.236.24"; private static String REPORT_SERVER_URL = "http://" + REPORT_SERVER_IP + "/rdServer/"; private static String REPORT_SERVER_CAB = "http://" + REPORT_SERVER_IP + "/rdServer/"; private static String REPORT_SERVER_SERVICE_NAME = "newknise"; private static String REPORT_SERVER_SITE_NAME= "국립특수교육원 원격연수 시스템"; private static String REPORT_VIEWER_OBJECT_ID= "Rdviewer"; private static String REPORT_VIEWER_CLSID= "clsid:ADB6D20D-80A1-4aa4-88AE-B2DC820DA076"; private static String REPORT_VIEWER_VERSION= "rdviewer50.cab#version=5,0,0,258"; private static String REPORT_VIEWER_WIDTH= "100%"; private static String REPORT_VIEWER_HEIGHT= "100%"; //private static String REPORT_MADOWNLOAD_SERVER_URL= "http://125.60.59.34/ngsrd/rdServer/markany/"; private static String REPORT_MADOWNLOAD_SERVER_CAB= "http://" + REPORT_SERVER_IP + "/rdServer/"; private static String REPORT_MADOWNLOAD_OBJECT_ID = "MaDownloadRD"; private static String REPORT_MADOWNLOAD_CLSID = "clsid:3B780B78-73B9-49B8-9630-3E60EDE61C73"; private static String REPORT_MADOWNLOAD_VERSION = "MaDownloadRD.cab#version=2,5,1,10"; private static String REPORT_MADOWNLOAD_WIDTH = ""; private static String REPORT_MADOWNLOAD_HEIGHT = ""; /** * * private static String REPORT_SERVER_SERVICE_NAME = propertiesService.getString("report.server.serviceName"); private static String REPORT_SERVER_SITE_NAME = propertiesService.getString("report.server.siteName"); private static String REPORT_VIEWER_OBJECT_ID = propertiesService.getString("report.viewer.object.id"); private static String REPORT_VIEWER_CLSID = propertiesService.getString("report.viewer.clsid"); private static String REPORT_VIEWER_VERSION = propertiesService.getString("report.viewer.version"); private static String REPORT_VIEWER_WIDTH = propertiesService.getString("report.viewer.width"); private static String REPORT_VIEWER_HEIGHT = propertiesService.getString("report.viewer.height"); **/ private static String HIDE_CONTROL_TAG = "<TEXTAREA ID=\"{0}_\" NAME=\"{0}_\" STYLE=\"display:none;\" ROWS=\"0\" COLS=\"0\">\n{1}</TEXTAREA>\n" + "<SCRIPT language=\"javascript\">\n" + "document.write( $(\"#{0}_\").val());\n" + "$(\"#{0}_\").val(\"\");" + "</SCRIPT>\n"; private static String REPORT_OBJECT_TAG = "<OBJECT ID=\"{0}\" NAME=\"{0}\" CLASSID=\"{1}\" CODEBASE=\"{2}\" WIDTH=\"{3}\" HEIGHT=\"{4}\" >\n</OBJECT>\n"; private static String REPORT_MADOWNLODERD_OBJECT_TAG = "<OBJECT ID=\"{0}\" NAME=\"{0}\" CLASSID=\"{1}\" CODEBASE=\"{2}\" WIDTH=\"{3}\" HEIGHT=\"{4}\" >\n</OBJECT>\n"; /** * */ private static final long serialVersionUID = -1146134413067129167L; private String title; private String file; private String rv; private String rp; private String rprnn; private String toolbar; private String printoff; private String mark; private String rpageorder; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getFile() { return file; } public void setFile(String file) { this.file = file; } public String getRv() { return rv; } public String getRpageorder(){ return rpageorder; } public void setRpageorder(String rpageorder){ this.rpageorder = rpageorder; } public void setRv(String rv) { this.rv = rv; } public String getRp() { return rp; } public void setRp(String rp) { this.rp = rp; } public String getRprnn() { return rprnn; } public void setRprnn(String rprnn) { this.rprnn = rprnn; } public String getPrintoff() { return printoff; } public void setPrintoff(String printoff) { this.printoff = printoff; } public String getMark() { return mark; } public void setMark(String mark) { this.mark = mark; } public int doStartTag() throws JspException { if (file == null) file = ""; if (title == null) title = ""; if (rv == null) rv = ""; if (rp == null) rp = ""; if (rprnn == null) rprnn = ""; if (toolbar == null) toolbar = "Y"; if (printoff == null) printoff = "N"; if (mark == null) mark = "N"; if (rpageorder == null) rpageorder = ""; return SKIP_BODY; } public int doEndTag() throws JspException { try { JspWriter out = pageContext.getOut(); HttpServletRequest request = (HttpServletRequest)pageContext.getRequest(); String html = ""; html += reportControl(); html += reportParameter( request); out.print( html); //System.out.println( html); } catch (Exception e) { throw new JspTagException("I/O Exception : " + e.getMessage()); } return EVAL_PAGE; } private String reportControl() { String reportControl = ""; if(mark.equals("Y")){ reportControl = reportControl + MessageFormat.format( REPORT_MADOWNLODERD_OBJECT_TAG, new Object[] { REPORT_MADOWNLOAD_OBJECT_ID, REPORT_MADOWNLOAD_CLSID, REPORT_MADOWNLOAD_SERVER_CAB+REPORT_MADOWNLOAD_VERSION, REPORT_MADOWNLOAD_WIDTH, REPORT_MADOWNLOAD_HEIGHT}); } reportControl = reportControl + MessageFormat.format( REPORT_OBJECT_TAG, new Object[] { REPORT_VIEWER_OBJECT_ID, REPORT_VIEWER_CLSID, REPORT_SERVER_CAB+REPORT_VIEWER_VERSION, REPORT_VIEWER_WIDTH, REPORT_VIEWER_HEIGHT}); return MessageFormat.format( HIDE_CONTROL_TAG, new Object[]{ "reportControl", reportControl}); } private String reportParameter( HttpServletRequest request) throws Exception { String path = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() ; //mrd 파일 패스 String fileURL = "http://"+REPORT_SERVER_IP+"/mrd/" + getFile(); if("127.0.0.1".equals(request.getRemoteAddr())){ fileURL = path + "/mrd/" + getFile(); } //System.out.println("MRD PATH IS : " + path); //System.out.println("MRD fileURL IS : " + fileURL); String parameter = "/rfn ["+REPORT_SERVER_URL+"rdagent.jsp] /rsn ["+REPORT_SERVER_SERVICE_NAME+"] /rpxpos [25] " + " /rmessageboxshow [2] "; parameter += "/rv site[" + REPORT_SERVER_SITE_NAME + "] title["+title+"] " + getRv(); parameter += "/rp " + getRp(); if(mark.equals("Y")){ parameter += " /rmultipage /rwatchprn "; } if(!getRprnn().equals("")){ parameter += "/rprnn " + getRprnn(); } if(!getRpageorder().equals("")){ parameter += "/rpageorder " + getRpageorder(); } //System.out.println("MRD parameter IS : " + parameter); //System.out.println("TEST1234 : "+REPORT_VIEWER_OBJECT_ID+".MAFileOpen('"+fileURL+"','"+parameter+"','"+REPORT_SERVER_URL+"rdagent.jsp');"); String encryptFileURL = ""; String encryptParameter = ""; if(!mark.equals("Y")){ encryptFileURL = new String( C.process( fileURL, 1)); encryptParameter = new String( C.process( parameter, 1)); }else{ encryptFileURL = fileURL; encryptParameter = parameter; } //String encryptFileURL = fileURL; //String encryptParameter = parameter; StringBuffer sb = new StringBuffer(); sb.append("<script language=\"javascript\">").append("\n"); /* sb.append(" $('#"+REPORT_VIEWER_OBJECT_ID+"').SetBackgroundColor(255,255,255);").append("\n"); sb.append(" $('#"+REPORT_VIEWER_OBJECT_ID+"').AutoAdjust=0;").append("\n"); sb.append(" $('#"+REPORT_VIEWER_OBJECT_ID+"').SetParameterEncrypt(1);").append("\n"); sb.append(" $('#"+REPORT_VIEWER_OBJECT_ID+"').SetKindOfParam(1);").append("\n"); sb.append(" $('#"+REPORT_VIEWER_OBJECT_ID+"').SetReportDialogInfo(1,'','',1,'','');").append("\n"); */ sb.append(" "+REPORT_VIEWER_OBJECT_ID+".SetBackgroundColor(255,255,255);").append("\n"); sb.append(" "+REPORT_VIEWER_OBJECT_ID+".AutoAdjust=0;").append("\n"); if(!mark.equals("Y")){ sb.append(" "+REPORT_VIEWER_OBJECT_ID+".SetParameterEncrypt(1);").append("\n"); sb.append(" "+REPORT_VIEWER_OBJECT_ID+".SetKindOfParam(1);").append("\n"); } sb.append(" "+REPORT_VIEWER_OBJECT_ID+".SetReportDialogInfo(1,'','',1,'','');").append("\n"); if(toolbar.equals("N")){ sb.append(" "+REPORT_VIEWER_OBJECT_ID+".DisableToolbar (0);").append("\n"); sb.append(" "+REPORT_VIEWER_OBJECT_ID+".DisableToolbar (2);").append("\n"); sb.append(" "+REPORT_VIEWER_OBJECT_ID+".DisableToolbar (3);").append("\n"); sb.append(" "+REPORT_VIEWER_OBJECT_ID+".DisableToolbar (4);").append("\n"); sb.append(" "+REPORT_VIEWER_OBJECT_ID+".DisableToolbar (5);").append("\n"); sb.append(" "+REPORT_VIEWER_OBJECT_ID+".DisableToolbar (6);").append("\n"); sb.append(" "+REPORT_VIEWER_OBJECT_ID+".DisableToolbar (7);").append("\n"); sb.append(" "+REPORT_VIEWER_OBJECT_ID+".DisableToolbar (8);").append("\n"); sb.append(" "+REPORT_VIEWER_OBJECT_ID+".DisableToolbar (9);").append("\n"); sb.append(" "+REPORT_VIEWER_OBJECT_ID+".DisableToolbar (10);").append("\n"); sb.append(" "+REPORT_VIEWER_OBJECT_ID+".DisableToolbar (11);").append("\n"); sb.append(" "+REPORT_VIEWER_OBJECT_ID+".DisableToolbar (12);").append("\n"); sb.append(" "+REPORT_VIEWER_OBJECT_ID+".DisableToolbar (13);").append("\n"); sb.append(" "+REPORT_VIEWER_OBJECT_ID+".DisableToolbar (14);").append("\n"); sb.append(" "+REPORT_VIEWER_OBJECT_ID+".DisableToolbar (15);").append("\n"); sb.append(" "+REPORT_VIEWER_OBJECT_ID+".DisableToolbar (16);").append("\n"); sb.append(" "+REPORT_VIEWER_OBJECT_ID+".DisableToolbar (17);").append("\n"); if(printoff.equals("Y")){ sb.append(" "+REPORT_VIEWER_OBJECT_ID+".PrintFinished();").append("\n"); } } if(mark.equals("Y")){ /* 마 크*/ sb.append(" "+REPORT_VIEWER_OBJECT_ID+".MAFileOpen2('"+encryptFileURL+"','"+encryptParameter+"','"+REPORT_SERVER_URL+"rdagent.jsp');").append("\n"); }else{ sb.append(" "+REPORT_VIEWER_OBJECT_ID+".FileOpen('"+encryptFileURL+"','"+encryptParameter+"');").append("\n"); } sb.append("</script>").append("\n"); /* if(printoff.equals("Y")){ sb.append("<SCRIPT LANGUAGE=JavaScript FOR=Rdviewer event=\"PrintFinished()\"> ").append("\n"); sb.append("</script>").append("\n"); } */ return sb.toString(); } public void release() { title = null; file = null; rv = null; rp = null; rprnn = null; mark = null; rpageorder = null; super.release(); } public String getToolbar() { return toolbar; } public void setToolbar(String toolbar) { this.toolbar = toolbar; } /* public EgovPropertyService getPropertyService() { if( propertiesService == null){ propertiesService = (EgovPropertyService)this.getWebApplicationBean("propertiesService"); } return propertiesService; } */ public WebApplicationContext getContext() { return ContextLoader.getCurrentWebApplicationContext(); } public Object getWebApplicationBean(String beanName) { return getContext().getBean(beanName); } }
package com.company; import javax.swing.JOptionPane; public class RandomSongPicker { public static void main(String[] args) { String userOption = JOptionPane.showInputDialog("Choose a random number from 0 to 4"); int x = Integer.parseInt(userOption); String song = randomSong(x); JOptionPane.showMessageDialog(null, "Your song is: " + song); } public static String randomSong (int option) { String[] songs = { "Breezeblocks - Alt-J", "New Rules - Dua Lipa", "Rather be - Clean Bandit", "Havana - Camila Cabello", "Vai malandra - Anitta" }; return songs[option]; } }
//applection based on literal class l1 { public static void main(String d[]) { int a=0117,b=0xccf; System.out.println("Var a in Decimal no="+a); System.out.printf("Var b in Decimal no="+b); }//close of main }//close of class
package acueducto.domain; import java.util.Map; import java.util.HashMap; import java.util.Collection; /** * * @author Karla Salas M. | Leonardo Sanchez J. */ public interface BombaRepository { /** * Insercion de un objeto Bomba. * @param bom * @return */ public boolean insertBomba(Bomba bom); /** * Eliminacion de un objeto Bomba. * @param bom * @return */ public boolean deleteBomba(Bomba bom); /** * Busqueda de un objeto Bomba. * @param id * @return */ public Bomba findBomba(int id); /** * Actualizacion de un objeto Bomba. * @param bom * @return */ public boolean updateBomba(Bomba bom); /** * Listado de objetos Bomba. * @return */ public Collection findAllBomba(); /** * Listado de objetos Bomba. * @param idPozo * @return */ public Collection findAllBombaXIdPozo(int idPozo); }
package example; import com.agenarisk.api.model.DataSet; import com.agenarisk.api.model.Model; import com.agenarisk.api.model.Network; import com.agenarisk.api.model.Node; import java.io.File; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.stream.Collectors; /** * * @author Eugene */ public class BatchCalculate { public static void main(String[] args) throws Exception { String separatorIn = ","; String separatorOut = ","; List<String> rawData = Files.lines(new File(Demo.class.getClassLoader().getResource("example/Asia.csv").getFile()).toPath()).collect(Collectors.toList()); String[] headers = rawData.get(0).split(separatorIn); List<String[]> data = rawData.subList(1, rawData.size()-1).stream().map(line -> line.split(",")).collect(Collectors.toList()); String modelFilePath = new File(Demo.class.getClassLoader().getResource("example/Asia.xml").getFile()).getAbsolutePath(); Model model = Model.loadModel(modelFilePath); Network net = model.getNetworkList().get(0); // Delete pre-exising DataSets if (!model.getDataSets().isEmpty()){ model.removeDataSet(model.getDataSetList().get(0)); } // If you want to use a single DataSet then for each new case (row) use dataSet.clearAllData(); for(String[] dsData: data){ String dsId = dsData[0]; DataSet dataSet = model.createDataSet(dsId); for (int i = 1; i < dsData.length; i++) { String nodeId = headers[i]; String observation = dsData[i]; if (observation.trim().isEmpty()){ // No observation continue; } dataSet.setObservation(net.getNode(nodeId), observation); } } // Calulate all networks and all data sets model.calculate(); Node hasBronchitis = net.getNode("B"); Node hasLungCancer = net.getNode("L"); Node hasTuberculosis = net.getNode("T"); String out = String.join(separatorOut, new String[]{"Case", "Has Bronchitis", "Has Lung Cancer", "Has Tuberculosis"}) + "\n"; for(DataSet ds: model.getDataSets().values()){ String outLine = String.join(separatorOut, Arrays.asList( ds.getId(), ds.getCalculationResult(hasBronchitis).getResultValue("yes").getValue()+"", ds.getCalculationResult(hasLungCancer).getResultValue("yes").getValue()+"", ds.getCalculationResult(hasTuberculosis).getResultValue("yes").getValue()+"" )); out += outLine + "\n"; } Files.write(Paths.get("BatchCalculate.csv"), out.getBytes(), StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE); } }
package model; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.Dictionary; import java.util.Hashtable; public class User { private static DB database; public User() { database = new DB(); try { database.connect("jdbc:mysql://localhost:3306/fintech512project?serverTimezone=UTC"); } catch (SQLException e) { int a = 0; } } public int register(String username, String password) { int result = 1; try { ResultSet resultset = database.executeQuery("select * from users where username = '" + username + "';"); if (resultset.next()) { result = 2; }else { database.executeUpdate("DELETE FROM users WHERE username = '" + username + "';"); database.executeUpdate("INSERT INTO users (username, password) VALUES ('" + username + "', '" + password + "');"); result = 0; } } catch (SQLException throwables) { result = 1; throwables.printStackTrace(); } finally { //database.close(); } return result; } public boolean login(String username, String password) { boolean result = false; try { ResultSet resultset = database.executeQuery("select * from users where username = '" + username + "';"); if (!resultset.next()) { System.out.println("no result"); } else { String passw = resultset.getString("password"); if (passw.equals(password)) { result = true; } } } catch (SQLException var10) { result = false; } finally { //database.close(); } return result; } public int GetUserid(String username) { int userid = -1; try { ResultSet resultset = database.executeQuery("select * from users where username = '" + username + "';"); if (!resultset.next()) { System.out.println("no result"); } else { userid = resultset.getInt("userid"); } } catch (SQLException var10) { } finally { //database.close(); } return userid; } public Dictionary<String, Integer> GetStocks(int userid) { Dictionary<String, Integer> stocks = new Hashtable<String, Integer>(); try { ResultSet resultset = database.executeQuery("select * from Assets where UserID = " + userid + ";"); while (resultset.next()) { String stock = resultset.getString("Asset"); int sharesize = resultset.getInt("Sharesize"); stocks.put(stock, sharesize); } } catch (SQLException var10) { } finally { //database.close(); } return stocks; } public ArrayList<Dictionary<String, String>> GetAllStocks() { ArrayList<Dictionary<String, String>> allStocks = new ArrayList<Dictionary<String, String>>(); try { ResultSet resultset = database.executeQuery("SELECT users.username, Assets.Asset, Assets.Sharesize FROM Assets join users on users.userid = Assets.UserID;"); while (resultset.next()) { Dictionary<String, String> oneUser = new Hashtable<String, String>(); String username = resultset.getString("username"); String stock = resultset.getString("Asset"); String sharesize = Integer.toString(resultset.getInt("Sharesize")); oneUser.put("username", username); oneUser.put("stock", stock); oneUser.put("sharesize", sharesize); allStocks.add(oneUser); } } catch (SQLException var10) { } finally { //database.close(); } return allStocks; } }
package com.skyhorse.scs.Service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.skyhorse.scs.Bean.AdminBean; import com.skyhorse.scs.DAO.DaoService; @Service public class MainServiceImpl implements MainService{ //Tells the application context to inject an instance of DaoService here @Autowired DaoService daoS; @Override public List<AdminBean> loginVerify(String uname) { System.out.println("MainService Entering..."); return daoS.loginVerify(uname); } }
package homework1.tasks; import java.util.Scanner; /** * Пусть a, b, c - переменные, которым присваиваются введенные числа, * а переменная m в конечном итоге должна будет содержать значение наибольшей переменной. * *Вариант без переменной m */ public class MaxNumber2 { public static void main(String[] args) { int a, b, c; Scanner in = new Scanner(System.in); System.out.println("ВВедите три разных числа : "); a = in.nextInt(); b = in.nextInt(); c = in.nextInt(); if (a == b || b == c || a == c){ System.out.println(" Ввод некорректен - нужны три РАЗНЫХ числа"); }else { if (a > b){ if(a > c){ System.out.println("Найбольшее число : " + a); }else System.out.println("Найбольшее число : " + c); }else if(b > c){ System.out.println("Найбольшее число : " + b); }else System.out.println("Найбольшее число : " + c); } in.close(); } }
package be.mxs.common.util.pdf.general.oc.examinations; import java.sql.SQLException; import java.text.DecimalFormat; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Iterator; import java.util.Vector; import com.itextpdf.text.Chunk; import com.itextpdf.text.Font; import com.itextpdf.text.FontFactory; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.PdfPTable; import com.itextpdf.text.pdf.PdfPCell; import be.mxs.common.model.vo.healthrecord.ItemVO; import be.mxs.common.util.db.MedwanQuery; import be.mxs.common.util.pdf.general.PDFGeneralBasic; import be.mxs.common.util.system.ScreenHelper; import be.openclinic.medical.Prescription; import be.openclinic.medical.Problem; import be.openclinic.pharmacy.Product; public class PDFFollowUpChildren extends PDFGeneralBasic { //--- ADD CONTENT ------------------------------------------------------------------------------ protected void addContent(){ try{ if(transactionVO.getItems().size() >= minNumberOfItems){ table = new PdfPTable(5); // TEST VIH (duration) itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_CS_SUIVI_ENFANTS_TEMPS"); if(itemValue.length() > 0){ if(itemValue.equals("6.weeks")) itemValue = itemValue.substring(0,itemValue.lastIndexOf("."))+" "+getTran("web","weeks").toLowerCase(); else if(itemValue.equals("7.5.months")) itemValue = itemValue.substring(0,itemValue.lastIndexOf("."))+" "+getTran("web","months").toLowerCase(); else if(itemValue.equals("9.months")) itemValue = itemValue.substring(0,itemValue.lastIndexOf("."))+" "+getTran("web","months").toLowerCase(); else if(itemValue.equals("15.months")) itemValue = itemValue.substring(0,itemValue.lastIndexOf("."))+" "+getTran("web","months").toLowerCase(); addItemRow(table,getTran("cs.suivi.enfants","test.vih"),itemValue); } // RESULT itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_CS_SUIVI_ENFANTS_RESULTAT"); if(itemValue.length() > 0){ if(itemValue.equals("+")) itemValue = getTran("web","positive"); else if(itemValue.equals("-")) itemValue = getTran("web","negative"); addItemRow(table,getTran("web.occup","intradermo.result"),itemValue); } // DEATH itemValue = getItemValue(IConstants_PREFIX+"ITEM_TYPE_CS_SUIVI_ENFANTS_DECES"); if(itemValue.length() > 0){ addItemRow(table,getTran("cs.suivi.enfants","deces"),getTran("web",itemValue)); } // COMMENT //itemValue = getItemSeriesValue(IConstants_PREFIX+"ITEM_TYPE_CS_SUIVI_ENFANTS_COMMENTAIRE_0"); itemValue = checkString(getItemValue(transactionVO,IConstants_PREFIX+"ITEM_TYPE_CS_SUIVI_ENFANTS_COMMENTAIRE_0"))+ checkString(getItemValue(transactionVO,IConstants_PREFIX+"ITEM_TYPE_CS_SUIVI_ENFANTS_COMMENTAIRE_1"))+ checkString(getItemValue(transactionVO,IConstants_PREFIX+"ITEM_TYPE_CS_SUIVI_ENFANTS_COMMENTAIRE_2"))+ checkString(getItemValue(transactionVO,IConstants_PREFIX+"ITEM_TYPE_CS_SUIVI_ENFANTS_COMMENTAIRE_3"))+ checkString(getItemValue(transactionVO,IConstants_PREFIX+"ITEM_TYPE_CS_SUIVI_ENFANTS_COMMENTAIRE_4")); if(itemValue.length() > 0){ addItemRow(table,getTran("web","comment"),itemValue); } if(table.size() > 0){ tranTable.addCell(new PdfPCell(table)); } // add transaction to doc addTransactionToDoc(); } } catch(Exception e){ e.printStackTrace(); } } }
package com.badawy.carservice.activity; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.annotation.SuppressLint; import android.content.Intent; import android.content.SharedPreferences; import android.net.Uri; import android.os.Bundle; import android.os.Handler; import android.view.View; import android.widget.Toast; import com.alphamovie.lib.AlphaMovieView; import com.badawy.carservice.R; import com.badawy.carservice.models.AboutUsDataModel; import com.badawy.carservice.utils.Constants; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.database.ValueEventListener; import com.google.gson.Gson; public class SplashScreenActivity extends AppCompatActivity { /** * * Created by Ahmed Tarek 15/11/2019 * Modified by Mahmoud Badawy 16/11/2019 * ... **/ // Splash Variables private Handler handler = new Handler(); private Runnable runnable = new Runnable() { @Override public void run() { Intent i = new Intent(SplashScreenActivity.this, LoginActivity.class); startActivity(i); finish(); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash_screen); hideSystemUI(); setSplashScreen(); //video view............... splash animation AHMED TAREK AlphaMovieView alphaMovieView = findViewById(R.id.splash_video); //build the video uri Uri uri=Uri.parse("android.resource://" +getPackageName() + "/" +R.raw.background_splash); alphaMovieView.setVideoFromUri(this,uri); } private void setSplashScreen() { // Time in MilliSeconds 1000 = 1 second int SPLASH_TIME_OUT = 3500; handler.postDelayed(runnable,SPLASH_TIME_OUT); } @Override protected void onDestroy() { super.onDestroy(); if (handler!=null){ handler.removeCallbacks(runnable); } } private void hideSystemUI() { View decorView = getWindow().getDecorView(); decorView.setSystemUiVisibility( View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY // Set the content to appear under the system bars so that the // content doesn't resize when the system bars hide and show. | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN // Hide the nav bar and status bar | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN); } }
package dao; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class MySql { private String ip = "127.0.0.1"; private String port = "3306"; private String user = "root"; private String pwd = ""; private String db = "bdd_bank"; private Connection connexion = null; public MySql() throws ClassNotFoundException, SQLException { try { Class.forName("com.mysql.jdbc.Driver"); } catch(ClassNotFoundException e) { System.out.println("Driver JDBC introuvable"); } try { connexion=DriverManager.getConnection("jdbc:mysql://" + ip + ":" + port + "/" + db, user, pwd); System.out.println("Connexion établie"); } catch(SQLException e) { System.out.println("Connexion ŕ la BDD impossible"); e.printStackTrace(); } } public Connection get_connexion() { return connexion; } public void close_connexion() throws SQLException { this.connexion.close(); } }
package com.zjf.myself.codebase.fragment; import android.text.Html; import android.view.View; import android.widget.CheckBox; import android.widget.EditText; import android.widget.TextView; import com.zjf.myself.codebase.R; import com.zjf.myself.codebase.activity.BaseAct; import com.zjf.myself.codebase.activity.LoginAct; import com.zjf.myself.codebase.application.AppConstants; import com.zjf.myself.codebase.application.UserDataManager; import com.zjf.myself.codebase.model.UserData; import com.zjf.myself.codebase.util.StringUtil; import com.zjf.myself.codebase.util.ViewUtils; /** * <pre> * author : ZouJianFeng * e-mail : 1434690833@qq.com * time : 2017/08/10 * desc : * version: 1.0 * </pre> */ public class HRNormalFragment extends BaseFragment{ public static HRNormalFragment newInstance() { HRNormalFragment f = new HRNormalFragment(); return f; } @Override protected void initView() { } @Override public void onResume() { super.onResume(); } @Override protected int layoutId() { return R.layout.fragment_hr_normal; } }
package ru.yandex.yamblz.ui.recyclerstuff; import android.content.Context; import android.support.v7.widget.GridLayoutManager; /** * Created by dalexiv on 8/5/16. */ public class OptimizedGridLayoutManager extends GridLayoutManager { public OptimizedGridLayoutManager(Context context, int spanCount) { super(context, spanCount); } @Override public boolean supportsPredictiveItemAnimations() { return true; } }
package com.example31._CRUD.config; import org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer; public class SpringSecurityInitializer extends AbstractSecurityWebApplicationInitializer { }
package com.codecool.stampcollection.DTO; import com.fasterxml.jackson.annotation.JsonIdentityInfo; import com.fasterxml.jackson.annotation.ObjectIdGenerators; import java.util.Set; @JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "name") public class StampDTO { private Long id; private String name; private String country; private Integer yearOfIssue; private Set<DenominationDTO> denominations; public StampDTO() { } public StampDTO(Long id, String name, String country, Integer yearOfIssue, Set<DenominationDTO> denominations) { this.id = id; this.name = name; this.country = country; this.yearOfIssue = yearOfIssue; this.denominations = denominations; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public Integer getYearOfIssue() { return yearOfIssue; } public void setYearOfIssue(Integer yearOfIssue) { this.yearOfIssue = yearOfIssue; } public Set<DenominationDTO> getDenominations() { return denominations; } public void setDenominations(Set<DenominationDTO> denominations) { this.denominations = denominations; } }
package baek5622; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main {//모르겠다 난 어려움 공략보면서 쉽게 생각하자아! public static void main(String[] args) throws IOException { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String str = br.readLine(); int count =0; int N = str.length(); for(int i =0;i < N;i++){ switch (str.charAt(i)){ case'A','B','C': count +=3; break; case'D','E','F': count += 4; break; case'G','H','I': count += 5; break; case 'J' : case 'K': case 'L' : count += 6; break; case 'M' : case 'N': case 'O' : count += 7; break; case 'P' : case 'Q': case 'R' : case 'S' : count += 8; break; case 'T' : case 'U': case 'V' : count += 9; break; case 'W' : case 'X': case 'Y' : case 'Z' : count += 10; break; } } System.out.println(count); } }
package com.nps.hellow; import android.app.AlertDialog; import android.content.DialogInterface; import android.os.Bundle; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.TextView; import com.nps.rangeseekbar.RangeSeekBar; import org.json.JSONException; import org.json.JSONObject; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; /** * Created by Ralf on 12/12/2014. */ public class FragmentRecherche extends Fragment { public final static String TAG = FragmentRecherche.class.getSimpleName(); private RangeSeekBar<Integer> age_seekBar = null; private RangeSeekBar<Integer> taille_seekBar = null; private RangeSeekBar<Integer> poids_seekBar = null; private Button rechercher = null; private CheckBox homme = null; private CheckBox femme = null; private CheckBox bleu = null; private CheckBox vert = null; private CheckBox marron = null; private CheckBox noisette = null; private CheckBox chauve = null; private CheckBox court = null; private CheckBox milong = null; private CheckBox longs = null; private CheckBox noir = null; private CheckBox blond = null; private CheckBox chatain = null; private CheckBox autre = null; private String FILENAME = "preferences_file"; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setRetainInstance(true); age_seekBar = new RangeSeekBar<Integer>(18, 99, getActivity()); taille_seekBar = new RangeSeekBar<Integer>(100, 200, getActivity()); poids_seekBar = new RangeSeekBar<Integer>(30, 120, getActivity()); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.activity_recherche, container, false); rechercher = (Button) view.findViewById(R.id.button_recherche); homme = (CheckBox) view.findViewById(R.id.homme); femme = (CheckBox) view.findViewById(R.id.femme); bleu = (CheckBox) view.findViewById(R.id.bleu); vert = (CheckBox) view.findViewById(R.id.vert); marron = (CheckBox) view.findViewById(R.id.marron); noisette = (CheckBox) view.findViewById(R.id.noisette); chauve = (CheckBox) view.findViewById(R.id.chauve); court = (CheckBox) view.findViewById(R.id.court); milong = (CheckBox) view.findViewById(R.id.milong); longs = (CheckBox) view.findViewById(R.id.longs); noir = (CheckBox) view.findViewById(R.id.noir); blond = (CheckBox) view.findViewById(R.id.blond); chatain = (CheckBox) view.findViewById(R.id.chatain); autre = (CheckBox) view.findViewById(R.id.autre); return view; } @Override public void onViewCreated(View view, Bundle savedInstanceState) { //AGE seekbar------------------------------------------------------------------------------------------------ age_seekBar.setOnRangeSeekBarChangeListener(new RangeSeekBar.OnRangeSeekBarChangeListener<Integer>() { @Override public void onRangeSeekBarValuesChanged(RangeSeekBar<?> bar, Integer minValue, Integer maxValue) { // handle changed range values TextView age = (TextView) getActivity().findViewById(R.id.age); age.setText("Age : " + age_seekBar.getSelectedMinValue() + " - " + age_seekBar.getSelectedMaxValue()); } }); age_seekBar.setSelectedMaxValue(99); age_seekBar.setSelectedMinValue(18); LinearLayout age_layout = (LinearLayout) getActivity().findViewById(R.id.age_seekbar); age_layout.addView(age_seekBar); //TAILLE seekbar------------------------------------------------------------------------------------------------ taille_seekBar.setOnRangeSeekBarChangeListener(new RangeSeekBar.OnRangeSeekBarChangeListener<Integer>() { @Override public void onRangeSeekBarValuesChanged(RangeSeekBar<?> bar, Integer minValue, Integer maxValue) { // handle changed range values TextView age = (TextView) getActivity().findViewById(R.id.taille); age.setText("Taille : " + taille_seekBar.getSelectedMinValue() + " - " + taille_seekBar.getSelectedMaxValue() + "cm"); } }); taille_seekBar.setSelectedMaxValue(200); taille_seekBar.setSelectedMinValue(100); LinearLayout taille_layout = (LinearLayout) getActivity().findViewById(R.id.taille_seekbar); taille_layout.addView(taille_seekBar); //POIDS seekbar------------------------------------------------------------------------------------------------ poids_seekBar.setOnRangeSeekBarChangeListener(new RangeSeekBar.OnRangeSeekBarChangeListener<Integer>() { @Override public void onRangeSeekBarValuesChanged(RangeSeekBar<?> bar, Integer minValue, Integer maxValue) { // handle changed range values TextView age = (TextView) getActivity().findViewById(R.id.poids); age.setText("Poids : " + poids_seekBar.getSelectedMinValue() + " - " + poids_seekBar.getSelectedMaxValue() + "Kg"); } }); poids_seekBar.setSelectedMaxValue(120); poids_seekBar.setSelectedMinValue(30); LinearLayout poids_layout = (LinearLayout) getActivity().findViewById(R.id.poids_seekbar); poids_layout.addView(poids_seekBar); //RECHERCHER button-------------------------------------------------------------------------------------------- rechercher.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //Dans le cas ou on a pas sélectionné assez de critères boolean test = false; if (!homme.isChecked() && !femme.isChecked()) { test = true; } if (!bleu.isChecked() && !vert.isChecked() && !marron.isChecked() && !noisette.isChecked()) { test = true; } if (!chauve.isChecked() && !court.isChecked() && !milong.isChecked() && !longs.isChecked()) { test = true; } if (!noir.isChecked() && !blond.isChecked() && !chatain.isChecked() && !autre.isChecked()) { test = true; } //Si on a donc un soucis au niveau des paramètres test devient true if (test) { final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getActivity()); alertDialogBuilder.setTitle(R.string.alert_dialog); alertDialogBuilder .setMessage(R.string.msg_dialog) .setPositiveButton("Ok",new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int id) { dialog.cancel(); } }); //On crée notre alertdialog AlertDialog alertDialog = alertDialogBuilder.create(); //On l'affiche alertDialog.show(); } //Tout est bon, on envoie la requête et on sauvegarde les préférences else { //Constitution du String a sauvegarder String CONTENT = age_seekBar.getSelectedMinValue() + "-" + age_seekBar.getSelectedMaxValue() + ","; CONTENT += taille_seekBar.getSelectedMinValue() + "-" + taille_seekBar.getSelectedMaxValue() + ","; CONTENT += poids_seekBar.getSelectedMinValue() + "-" + poids_seekBar.getSelectedMaxValue() + ","; CONTENT += homme.isChecked() + "," + femme.isChecked() + ","; CONTENT += bleu.isChecked() + "," + vert.isChecked() + "," + marron.isChecked() + "," + noisette.isChecked() + ","; CONTENT += chauve.isChecked() + "," + court.isChecked() + "," + milong.isChecked() + "," + longs.isChecked() + ","; CONTENT += noir.isChecked() + "," + blond.isChecked() + "," + chatain.isChecked() + "," + autre.isChecked(); FileOutputStream fos = null; try { fos = getActivity().openFileOutput(FILENAME, getActivity().MODE_PRIVATE); } catch (FileNotFoundException e) { e.printStackTrace(); } if (fos != null) { System.out.println(getActivity().getFilesDir()); try { fos.write(CONTENT.getBytes()); } catch (IOException e) { e.printStackTrace(); } try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } //On put les données dans un json String age_min = age_seekBar.getSelectedMinValue().toString(); String age_max = age_seekBar.getSelectedMaxValue().toString(); String taille_min = taille_seekBar.getSelectedMinValue().toString(); String taille_max = taille_seekBar.getSelectedMaxValue().toString(); String poids_min = poids_seekBar.getSelectedMinValue().toString(); String poids_max = poids_seekBar.getSelectedMaxValue().toString(); String s_homme = Boolean.toString(homme.isChecked()); String s_femme = Boolean.toString(femme.isChecked()); String s_bleu = Boolean.toString(bleu.isChecked()); String s_vert = Boolean.toString(vert.isChecked()); String s_marron = Boolean.toString(marron.isChecked()); String s_noisette = Boolean.toString(noisette.isChecked()); String s_chauve = Boolean.toString(chauve.isChecked()); String s_court = Boolean.toString(court.isChecked()); String s_milong = Boolean.toString(milong.isChecked()); String s_longs = Boolean.toString(longs.isChecked()); String s_noir = Boolean.toString(noir.isChecked()); String s_blond = Boolean.toString(blond.isChecked()); String s_chatain = Boolean.toString(chatain.isChecked()); String s_autre = Boolean.toString(autre.isChecked()); //On le passe a notre intent ((MainActivity)getActivity()).startRecherche(age_min, age_max, taille_min, taille_max, poids_min, poids_max, s_homme, s_femme ,s_bleu, s_vert, s_marron, s_noisette, s_chauve, s_court, s_milong, s_longs ,s_noir, s_blond, s_chatain, s_autre); } } }); //Si on a un fichier de préférence sauvegardé String contenu = ""; try { FileInputStream fis = getActivity().openFileInput(FILENAME); int content; while ((content = fis.read()) != -1) { // convert to char and display it contenu += Character.toString((char) content); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } //Si on a bien récupérer le contenu if (contenu != "") { //On set nos données String contenu_tab[] = contenu.split(","); //item 0 = age String contenu_age[] = contenu_tab[0].split("-"); age_seekBar.setSelectedMinValue(Integer.parseInt(contenu_age[0])); age_seekBar.setSelectedMaxValue(Integer.parseInt(contenu_age[1])); //item 1 = taille String contenu_taille[] = contenu_tab[1].split("-"); taille_seekBar.setSelectedMinValue(Integer.parseInt(contenu_taille[0])); taille_seekBar.setSelectedMaxValue(Integer.parseInt(contenu_taille[1])); //item 2 = poids String contenu_poids[] = contenu_tab[2].split("-"); poids_seekBar.setSelectedMinValue(Integer.parseInt(contenu_poids[0])); poids_seekBar.setSelectedMaxValue(Integer.parseInt(contenu_poids[1])); //item 3 = sexe homme homme.setChecked(Boolean.parseBoolean(contenu_tab[3])); //item 4 = sexe femme femme.setChecked(Boolean.parseBoolean(contenu_tab[4])); //item 5 = yeux bleus bleu.setChecked(Boolean.parseBoolean(contenu_tab[5])); //item 6 = yeux verts vert.setChecked(Boolean.parseBoolean(contenu_tab[6])); //item 7 = yeux marrons marron.setChecked(Boolean.parseBoolean(contenu_tab[7])); //item 8 = yeux noisettes noisette.setChecked(Boolean.parseBoolean(contenu_tab[8])); //item 9 = cheveux chauve chauve.setChecked(Boolean.parseBoolean(contenu_tab[9])); //item 10 = cheveux courts court.setChecked(Boolean.parseBoolean(contenu_tab[10])); //item 11 = cheveux mi-long milong.setChecked(Boolean.parseBoolean(contenu_tab[11])); //item 12 = cheveux longs longs.setChecked(Boolean.parseBoolean(contenu_tab[12])); //item 13 = couleur noir noir.setChecked(Boolean.parseBoolean(contenu_tab[13])); //item 14 = couleur blond blond.setChecked(Boolean.parseBoolean(contenu_tab[14])); //item 15 = couleur chatain chatain.setChecked(Boolean.parseBoolean(contenu_tab[15])); //item 16 = couleur autre autre.setChecked(Boolean.parseBoolean(contenu_tab[16])); } super.onViewCreated(view, savedInstanceState); } public static Fragment newInstance() { return new FragmentRecherche(); } }
package com.croquis.crary.restclient; import android.annotation.TargetApi; import android.content.Context; import android.os.Handler; import android.os.Looper; import com.croquis.crary.restclient.gson.GsonMimeCraftMultipartConverter; import com.google.gson.Gson; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; import com.squareup.mimecraft.Multipart; import com.squareup.mimecraft.Part; import org.apache.http.HttpStatus; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Reader; import java.lang.reflect.Type; import java.net.CookieHandler; import java.net.CookieManager; import java.net.CookiePolicy; import java.net.HttpURLConnection; import java.net.ProtocolException; import java.net.URL; import java.util.Collection; import java.util.Map; @TargetApi(14) public class CraryRestClientImplJavaNet { Context mContext; Gson mGson; String mUserAgent; Handler mHandler = new Handler(Looper.getMainLooper()); public CraryRestClientImplJavaNet(Context context, Gson gson) { mContext = context; mGson = gson; CookieHandler.setDefault(new CookieManager(null, CookiePolicy.ACCEPT_ALL)); } public void setUserAgent(String userAgent) { mUserAgent = userAgent; } public <T> void get(String url, CraryRestClient.OnRequestComplete<T> complete, Type type) { request(url, "GET", null, null, false, complete, type); } public <T> void post(String url, Object parameters, CraryRestClient.OnRequestComplete<T> complete, Type type) { request(url, "POST", parameters, null, false, complete, type); } public <T> void post(String url, Object parameters, Collection<CraryRestClientAttachment> attachments, CraryRestClient.OnRequestComplete<T> complete, Type type) { request(url, "POST", parameters, attachments, false, complete, type); } public <T> void postGzip(String url, Object parameters, CraryRestClient.OnRequestComplete<T> complete, Type type) { request(url, "POST", parameters, null, true, complete, type); } public <T> void put(String url, Object parameters, CraryRestClient.OnRequestComplete<T> complete, Type type) { request(url, "PUT", parameters, null, false, complete, type); } public <T> void put(String url, Object parameters, Collection<CraryRestClientAttachment> attachments, CraryRestClient.OnRequestComplete<T> complete, Type type) { request(url, "PUT", parameters, attachments, false, complete, type); } public <T> void delete(String url, CraryRestClient.OnRequestComplete<T> complete, Type type) { request(url, "DELETE", null, null, false, complete, type); } public void post(final String url, final byte[] data, final CraryRestClient.OnRequestComplete<byte[]> complete) { request(url, "POST", data, complete); } private <T> void request(final String url, final String method, final Object parameters, final Collection<CraryRestClientAttachment> attachments, final boolean gzip, final CraryRestClient.OnRequestComplete<T> complete, final Type type) { new Thread(new Runnable() { @Override public void run() { HttpURLConnection urlConnection; try { urlConnection = (HttpURLConnection) new URL(url).openConnection(); } catch (IOException e) { if (complete != null) { complete.onComplete(CraryRestClient.RestError.UNKNOWN_ERROR, null); } return; } catch (ClassCastException e) { if (complete != null) { complete.onComplete(CraryRestClient.RestError.UNKNOWN_ERROR, null); } return; } try { if (mUserAgent != null) { urlConnection.setRequestProperty("User-Agent", mUserAgent); } urlConnection.setRequestMethod(method); if (attachments != null) { urlConnection.setDoOutput(true); Multipart multipart = convertMultipart(parameters, attachments); Map<String, String> headers = multipart.getHeaders(); for (String field : headers.keySet()) { urlConnection.setRequestProperty(field, headers.get(field)); } multipart.writeBodyTo(urlConnection.getOutputStream()); } else if (parameters != null) { urlConnection.setDoOutput(true); urlConnection.setRequestProperty("Content-Type", "application/json"); if (gzip) { urlConnection.setRequestProperty("Content-Encoding", "gzip"); OutputStream out = urlConnection.getOutputStream(); out.write(CraryRestClient.gzipDeflate(mGson.toJson(parameters).getBytes())); out.close(); } else { OutputStreamWriter out = new OutputStreamWriter(urlConnection.getOutputStream()); out.write(mGson.toJson(parameters)); out.close(); } } } catch (ProtocolException e) { if (complete != null) { complete.onComplete(CraryRestClient.RestError.UNKNOWN_ERROR, null); } urlConnection.disconnect(); return; } catch (IOException e) { if (complete != null) { complete.onComplete(CraryRestClient.RestError.UNKNOWN_ERROR, null); } urlConnection.disconnect(); return; } processResponse(urlConnection, complete, type); } }).start(); } private Multipart convertMultipart(Object parameters, Collection<CraryRestClientAttachment> attachments) { Multipart.Builder builder = GsonMimeCraftMultipartConverter.convert(parameters, mGson); for (CraryRestClientAttachment attachment : attachments) { builder.addPart(new Part.Builder() .body(attachment.mData) .contentType(attachment.mMimeType) .contentDisposition("form-data; name=\"" + attachment.mName + "\"; filename=\"" + attachment.mFileName + "\"") .build()); } return builder.build(); } private <T> void processResponse(HttpURLConnection urlConnection, CraryRestClient.OnRequestComplete<T> complete, Type type) { CraryRestClient.RestError error; T json; try { int responseCode = urlConnection.getResponseCode(); Reader reader; if (responseCode >= HttpStatus.SC_BAD_REQUEST) { reader = new InputStreamReader(urlConnection.getErrorStream()); } else { reader = new InputStreamReader(urlConnection.getInputStream()); } error = getResponseError(responseCode, reader); //noinspection unchecked json = mGson.fromJson(reader, type); } catch (IOException ignored) { if (complete != null) { complete.onComplete(CraryRestClient.RestError.UNKNOWN_ERROR, null); } urlConnection.disconnect(); return; } catch (JsonParseException ignored) { if (complete != null) { complete.onComplete(CraryRestClient.RestError.UNRECOGNIZABLE_RESULT, null); } urlConnection.disconnect(); return; } urlConnection.disconnect(); if (error != null) { callOnComplete(complete, error, null); } else { callOnComplete(complete, null, json); } } private CraryRestClient.RestError getResponseError(int statusCode, Reader reader) { if (statusCode >= 200 && statusCode < 300) { return null; } JsonObject json; try { json = mGson.fromJson(reader, JsonObject.class); } catch (JsonParseException ignored) { return CraryRestClient.RestError.UNRECOGNIZABLE_RESULT; } if (json == null) { return CraryRestClient.RestError.NETWORK_ERROR; } JsonElement errorObj = json.get("error"); String error = errorObj != null && errorObj.isJsonPrimitive() ? errorObj.getAsString() : null; JsonElement descriptionObj = json.get("description"); String description = descriptionObj != null && descriptionObj.isJsonPrimitive() ? descriptionObj.getAsString() : null; return new CraryRestClient.RestError(statusCode, error, description); } private void request(final String url, final String method, final byte[] data, final CraryRestClient.OnRequestComplete<byte[]> complete) { new Thread(new Runnable() { @Override public void run() { HttpURLConnection urlConnection; try { urlConnection = (HttpURLConnection) new URL(url).openConnection(); } catch (IOException e) { if (complete != null) { complete.onComplete(CraryRestClient.RestError.UNKNOWN_ERROR, null); } return; } catch (ClassCastException e) { if (complete != null) { complete.onComplete(CraryRestClient.RestError.UNKNOWN_ERROR, null); } return; } try { if (mUserAgent != null) { urlConnection.setRequestProperty("User-Agent", mUserAgent); } urlConnection.setRequestMethod(method); if (data != null) { urlConnection.setDoOutput(true); urlConnection.setRequestProperty("Content-Type", "application/octet-stream"); OutputStream out = urlConnection.getOutputStream(); out.write(data); out.close(); } } catch (ProtocolException e) { if (complete != null) { complete.onComplete(CraryRestClient.RestError.UNKNOWN_ERROR, null); } urlConnection.disconnect(); return; } catch (IOException e) { if (complete != null) { complete.onComplete(CraryRestClient.RestError.UNKNOWN_ERROR, null); } urlConnection.disconnect(); return; } byte[] output; try { InputStream inputStream = urlConnection.getInputStream(); output = toByteArray(inputStream); inputStream.close(); } catch (IOException ignored) { if (complete != null) { complete.onComplete(CraryRestClient.RestError.UNKNOWN_ERROR, null); } urlConnection.disconnect(); return; } callOnComplete(complete, null, output); } }).start(); } private static byte[] toByteArray(InputStream input) throws IOException { ByteArrayOutputStream output = new ByteArrayOutputStream(); byte[] buffer = new byte[4096]; int n; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); } return output.toByteArray(); } private <T> void callOnComplete(final CraryRestClient.OnRequestComplete<T> complete, final CraryRestClient.RestError error, final T result) { mHandler.post(new Runnable() { @Override public void run() { if (complete != null) { complete.onComplete(error, result); } } }); } }
package com.imooc.spring.ioc.class08; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; @Configuration @ComponentScan(value ="com.imooc.spring.ioc.class08") public class MyConfiguration { /* @Bean(value=" ") 指定别名,也可指定多个 public Bean1 bean1(){ return new Bean1(); }*/ }
package com.mditservices.scheduler; /*package com.webinfoways.blackbelt; import java.util.ArrayList; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class DatabaseHelper extends SQLiteOpenHelper { public static String DATABASENAME = "namericknew.db"; public static String PRODUCTTABLE = "producttable"; public static String colProductId = "productId"; public static String colProductName = "productname"; public static String colProductDesc = "productdesc"; public static String colProductState = "productstate"; public static String colProductDirection = "productdirection"; public static String colProductURL = "producturl"; private ArrayList<Item> cartList = new ArrayList<Item>(); Context c; public DatabaseHelper(Context context) { super(context, DATABASENAME, null, 33); c = context; } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + PRODUCTTABLE + "(" + colProductId + " TEXT ," + colProductName + " TEXT ," + colProductDesc + " TEXT ," + colProductState + " TEXT ," + colProductDirection + " BLOB ," + colProductURL + " BLOB )"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS" + PRODUCTTABLE); onCreate(db); } public void addProductToCart(Contact productitem) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues contentValues = new ContentValues(); contentValues.put(colProductId, productitem._id); contentValues.put(colProductName, productitem._name); // contentValues.put(colProductState, productitem.facial); //contentValues.put(colProductURL, productitem.plan); db.insert(PRODUCTTABLE, colProductName, contentValues); // db.insert(PRODUCTTABLE, colProductDesc, contentValues); // db.insert(PRODUCTTABLE, colProductDirection, contentValues); // db.insert(PRODUCTTABLE, colProductURL, contentValues); * colProductId, , , colProductDesc,, db.close(); } // update public void removeProductFromCart(int productid) { try { SQLiteDatabase db = this.getWritableDatabase(); db.execSQL("delete from producttable where productId=" + productid); db.close(); } catch (Exception e) { e.printStackTrace(); } } public ArrayList<Item> getCartItems() { cartList.clear(); SQLiteDatabase db = this.getWritableDatabase(); Cursor cursor = db.rawQuery("select * from " + PRODUCTTABLE, null); if (cursor.getCount() != 0) { if (cursor.moveToFirst()) { do { Item item = new Item(); item.id = cursor.getString(cursor .getColumnIndex(colProductId)); item.name = cursor.getString(cursor .getColumnIndex(colProductName)); item.notes = cursor.getString(cursor .getColumnIndex(colProductDesc)); item.facial = cursor.getString(cursor .getColumnIndex(colProductState)); item.group = cursor.getString(cursor .getColumnIndex(colProductDirection)); item.plan = cursor.getString(cursor .getColumnIndex(colProductURL)); cartList.add(item); } while (cursor.moveToNext()); } } cursor.close(); db.close(); return cartList; } } */
package com.planificateurvoyage.ui.personne; import javax.swing.JPanel; import javax.swing.JButton; import javax.swing.JLabel; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.Font; import javax.swing.JTable; import javax.swing.JScrollPane; import javax.swing.JTextField; public class PersonneConsultationPanel extends JPanel { //////////// private String data[][]={ {"1","Dubois","Bertrand"}, {"2","Martin","Henri"}, {"3","Sachin","Simon"}, {"5","villebois","Paul"}, {"6","Legenec","Jacques"}, {"7","Dupuis","Yvette"} }; private String column[]={"ID","NOM","PRENOM"}; private JTable table = new JTable(data,column); private JScrollPane sp=new JScrollPane(table); private JTextField textField; private JTextField textField_1; //////////// public PersonneConsultationPanel() { setLayout(null); JLabel lblTitre = new JLabel("Consultation des personnes"); lblTitre.setBounds(102, 5, 245, 25); lblTitre.setFont(new Font("Tahoma", Font.PLAIN, 20)); add(lblTitre); //Critere de recherche JLabel lblNewLabel_1 = new JLabel("nom"); lblNewLabel_1.setBounds(50, 44, 46, 14); add(lblNewLabel_1); textField = new JTextField(); textField.setBounds(102, 41, 86, 20); add(textField); textField.setColumns(10); JLabel lblNewLabel_2 = new JLabel("pr\u00E9nom"); lblNewLabel_2.setBounds(198, 41, 46, 14); add(lblNewLabel_2); textField_1 = new JTextField(); textField_1.setBounds(246, 41, 86, 20); add(textField_1); textField_1.setColumns(10); JButton btnNewButton_1 = new JButton("Recherche"); btnNewButton_1.setBounds(342, 41, 108, 23); add(btnNewButton_1); // Table sp.setBounds(50, 72, 400, 100); add(sp); JButton btnNewButton = new JButton("Ajouter"); btnNewButton.setBounds(361, 193, 89, 23); add(btnNewButton); } }
public class M4_11static { public static void main(String[] args) { Counter c1 = new Counter(); Counter c2 = new Counter(); System.out.println(Counter.COUNT); System.out.println(c1); System.out.println(c2); //System.out.println(c1.COUNT); //System.out.println(c2.COUNT); Vehicle.horn(); } } class Counter { public static int COUNT=0; Counter() { COUNT++; } } // you can call this method without creating object class Vehicle { public static void horn() { System.out.println("Beep"); } }
package com.wessolowski.app.android.util.media; import com.wessolowski.app.util.checks.Checks; import android.media.MediaPlayer; import android.media.audiofx.BassBoost; import android.util.Log; import android.media.audiofx.*; public class MediaPlayerEqualizer { private static final short BASS_BOOST_RANGE = 50; private static final short BASS_BOOST_MIN_STRENGTH = 0; private static final short BASS_BOOST_MAX_STRENGTH = 1000; private static final short DEFAULT_BASS_BOOST_STRENGTH = 500; private short currentBoost = 0; private static final short EQUALIZER_BAND_ONE = 0; private static final short EQUALIZER_BAND_TWO = 1; private static final short EQUALIZER_BAND_THREE = 2; private static final short EQUALIZER_BAND_FOUR = 3; private static final short EQUALIZER_BAND_FIVE = 4; private static final short DEFAULT_EQUALIZER_BAND_ONE_LEVEL = 0; private static final short DEFAULT_EQUALIZER_BAND_TWO_LEVEL = 0; private static final short DEFAULT_EQUALIZER_BAND_THREE_LEVEL = 0; private static final short DEFAULT_EQUALIZER_BAND_FOUR_LEVEL = 0; private static final short DEFAULT_EQUALIZER_BAND_FIVE_LEVEL = 0; private static final short EQUALIZER_BAND_LEVEL_RANGE = 100; private static final short DEFAULT_VIRTUALIZER_LEVEL = 0; private static MediaPlayerEqualizer mediaPlayerEqualizer = null; private static final String TAG = MediaPlayerEqualizer.class.getSimpleName(); private BassBoost bassBoost = null; private Equalizer androidEqualizer = null; private Virtualizer virtualizer = null; // private LoudnessEnhancer loudness = null; private MediaPlayerEqualizer() { } public static MediaPlayerEqualizer getInstance() { if (!Checks.checkNull(mediaPlayerEqualizer)) { mediaPlayerEqualizer = new MediaPlayerEqualizer(); return mediaPlayerEqualizer; } return mediaPlayerEqualizer; } public void configEqualizer(int sessoinId) { Log.i(TAG, "config equalizer"); bassBoost = new BassBoost(0, sessoinId); bassBoost.setEnabled(true); androidEqualizer = new Equalizer(0, sessoinId); androidEqualizer.setEnabled(true); virtualizer = new Virtualizer(0, sessoinId); virtualizer.setEnabled(true); loadDefaultEqualizerSettings(); } public void loadDefaultEqualizerSettings() { Log.i(TAG, "load default settings"); loadDefaultBandLevel(); loadDefaultVirtualizerlevel(); loadDefaultBassBoostLevel(); } public void loadDefaultBandLevel() { if (Checks.checkNull(androidEqualizer)) { androidEqualizer.setBandLevel(EQUALIZER_BAND_ONE , DEFAULT_EQUALIZER_BAND_ONE_LEVEL); androidEqualizer.setBandLevel(EQUALIZER_BAND_TWO , DEFAULT_EQUALIZER_BAND_TWO_LEVEL); androidEqualizer.setBandLevel(EQUALIZER_BAND_THREE , DEFAULT_EQUALIZER_BAND_THREE_LEVEL); androidEqualizer.setBandLevel(EQUALIZER_BAND_FOUR , DEFAULT_EQUALIZER_BAND_FOUR_LEVEL); androidEqualizer.setBandLevel(EQUALIZER_BAND_FIVE , DEFAULT_EQUALIZER_BAND_FIVE_LEVEL); } } private void setBandLevel(short band, short level) { androidEqualizer.setBandLevel(band, (short) (level + 100)); } public void setBandLevelUp(short band) { short[] range = androidEqualizer.getBandLevelRange(); if (androidEqualizer.getBandLevel(band) < range[1]) { short level = androidEqualizer.getBandLevel(band); setBandLevel(band, level); Log.i(TAG, "Set Band: " + band + " Level UP to: " + androidEqualizer.getBandLevel(band)); } else { Log.i(TAG, "Band: " + band + " is MAX Level: " + androidEqualizer.getBandLevel(band)); } } public void setBandLevelDown(short band) { short[] range = androidEqualizer.getBandLevelRange(); if (androidEqualizer.getBandLevel(band) > range[0]) { short level = androidEqualizer.getBandLevel(band); androidEqualizer.setBandLevel(band, (short) (level - 100)); Log.i(TAG, "Set Band: " + band + " Level DOWN to: " + androidEqualizer.getBandLevel(band)); } else { Log.i(TAG, "Band: " + band + " is MIN Level: " + androidEqualizer.getBandLevel(band)); } } public void loadDefaultBassBoostLevel() { setBassBoostLevel(DEFAULT_BASS_BOOST_STRENGTH); } private void setBassBoostLevel(short level) { bassBoost.setStrength(level); } public short setBassBoostLevelUp() { if (currentBoost < BASS_BOOST_MAX_STRENGTH) { short strength = (short) ((short) bassBoost.getRoundedStrength() + BASS_BOOST_RANGE); setBassBoostLevel(strength); currentBoost = bassBoost.getRoundedStrength(); } return bassBoost.getRoundedStrength(); } public short setbassBoostLevelDown() { if (currentBoost > BASS_BOOST_MIN_STRENGTH) { short strength = (short) ((short) bassBoost.getRoundedStrength() - BASS_BOOST_RANGE); setBassBoostLevel(strength); currentBoost = bassBoost.getRoundedStrength(); } return bassBoost.getRoundedStrength(); } public void loadDefaultVirtualizerlevel() { setVirtualizerLevel(DEFAULT_VIRTUALIZER_LEVEL); } private void setVirtualizerLevel(short level) { virtualizer.setStrength(level); } public void setVirtualizerLevelMAX() { short maxLevel = 1000; setVirtualizerLevel(maxLevel); } public void setVirtualizerLevelMIN() { short minLevel = 0; setVirtualizerLevel(minLevel); } public void setVirtualizerLevelUp() { if (virtualizer.getRoundedStrength() < 1000) { short level = (short) (virtualizer.getRoundedStrength() + 200); setVirtualizerLevel(level); Log.i(TAG, "Set Virtualizer Level UP to: " + virtualizer.getRoundedStrength()); } else { Log.i(TAG, "Virtualizer Level is MAX: " + virtualizer.getRoundedStrength()); } } public void setVirtualizerLevelDown() { if (virtualizer.getRoundedStrength() > 0) { short level = (short) (virtualizer.getRoundedStrength() - 200); setVirtualizerLevel(level); Log.i(TAG, "Set Virtualizer Level Down to: " + virtualizer.getRoundedStrength()); } else { Log.i(TAG, "Virtualizer Level is MIN: " + virtualizer.getRoundedStrength()); } } public void destroyMediaEqualizer() { if (Checks.checkNull(bassBoost)) { bassBoost.release(); } if (Checks.checkNull(virtualizer)) { virtualizer.release(); } if (Checks.checkNull(androidEqualizer)) { androidEqualizer.release(); } } }
package com.pengo.storage.service; import com.baomidou.mybatisplus.extension.service.IService; import com.pengo.common.entity.Storage; public interface StorageService extends IService<Storage> { }
package com.training; public class TestGreeting{ public static void main(String[] args){ Greeting obj=new Greeting(); System.out.println(obj.getMessage()); } }
/** * */ package com.zh.common.utils; import java.io.Serializable; /** * @author ZH * 所有properties陪着的key * 都需要配置在该文件里面。 * */ public class GlobalConstants implements Serializable { private static final long serialVersionUID = 3186971530746202421L; }
package com.qst.dms.service; import java.util.List; import com.qst.dms.dao.impl.ImplLogRecDao; import com.qst.dms.dao.impl.ImplMatchedLogRecDao; import com.qst.dms.entity.LogRec; import com.qst.dms.entity.MatchedLogRec; import com.qst.dms.factory.DaoFactory; /** * @author 陌意随影 TODO :日志业务类 *2019年11月7日 下午7:26:58 */ public class LogRecService extends Service<MatchedLogRec> { /** 数据库链接 */ private ImplMatchedLogRecDao matchedLogRecDao = null; private ImplLogRecDao logRecDao = null; @SuppressWarnings("javadoc") public LogRecService() { //通过工厂模式获取对象实例 this.matchedLogRecDao = (ImplMatchedLogRecDao) DaoFactory.getDaoImpl("ImplMatchedLogRecDao"); //通过工厂模式获取对象实例 this.logRecDao = (ImplLogRecDao) DaoFactory.getDaoImpl("ImplLogRecDao");; } /** * 将匹配的登录日志匹配到文件中去 */ public void saveToDataBase(List<MatchedLogRec> matchLogs ){ if (matchLogs == null) { return; } //将所有的MatchedLogRec逐个保存到数据库中去 for (int i = 0; i < matchLogs.size(); i++) { MatchedLogRec matchLog = matchLogs.get(i); //获取登入ID int loginid = matchLog.getLogin().getId(); //获取登出ID int logoutid = matchLog.getLogout().getId(); boolean fla = this.matchedLogRecDao.isExits(loginid, logoutid); if (!fla) { System.out.println(matchLog); //开始保存 boolean fla1 = this.logRecDao.save(matchLog.getLogin()); boolean fla2 = this.logRecDao.save(matchLog.getLogout()); if (!fla1 || !fla2) { System.out.println("存储到数据库时失败"); } } } //获取所有的LogRec List<LogRec> list = this.logRecDao.getAll(); //每次保留两个 for (int i = 0; i < list.size(); i = i + 2) { //获取登入的LogRec LogRec login = list.get(i); //获取登出的LogRec LogRec logout = list.get(i + 1); //首先判断是否在数据库中存在 boolean fla = this.matchedLogRecDao.isExits(login.getId(), logout.getId()); if (!fla) { //不存在则保存 this.matchedLogRecDao.save(login.getId(), logout.getId()); } } } /** * 通过loginid 或 logoutid中的一个id来删除对应的两条记录 * @param id * @return 返回是否移除成功 */ public boolean remove(int id){ //通过ID获取登入登出的两个对象的ID数组 Integer[] ids = this.matchedLogRecDao.getMatchedLogId(id); if(ids == null || ids.length != 2){ return false; } //登入ID int loginid = ids[0]; //登出ID int logoutid = ids[1]; //在 gather_logrec表中删除登入ID boolean fla1 =this.logRecDao.remove(loginid); //在 gather_logrec表中删除登出ID boolean fla2 =this.logRecDao.remove(logoutid); //在 matched_logrec中删除这条记录 boolean fla3 = this.matchedLogRecDao.remove(loginid, logoutid); if(fla1&&fla2&&fla3){ return true; }else{ return false; } } /** * 将匹配的登录日志匹配到文件中去 */ public void saveToDataBase(MatchedLogRec... matchLogs ){ if(matchLogs == null){ return ; } for(int i = 0;i < matchLogs.length;i++){ MatchedLogRec matchLog = matchLogs[i]; int loginid = matchLog.getLogin().getId(); int logoutid = matchLog.getLogout().getId(); boolean fla = this.matchedLogRecDao.isExits(loginid, logoutid); if(!fla) { System.out.println(matchLog); boolean fla1 = this.logRecDao.save(matchLog.getLogin()); boolean fla2 = this.logRecDao.save(matchLog.getLogout()); if(!fla1||!fla2) { System.out.println("存储到数据库时失败"); } } } List<LogRec> list = this.logRecDao.getAll(); for(int i = 0; i < list.size();i= i+2){ LogRec login = list.get(i); LogRec logout = list.get(i+1); System.out.println(login); System.out.println(logout); boolean fla = this.matchedLogRecDao.isExits(login.getId(), logout.getId()); if(!fla){ this.matchedLogRecDao.save(login.getId(),logout.getId()); } } } /** * 读匹配日志信息保存,参数是集合 */ public List<LogRec> readLogfromDataBase() { //获取全部的匹配登录日志 List<LogRec> list = this.logRecDao.getAll(); return list; } @Override public void saveToLocal(String pathName, MatchedLogRec... params) { super.saveToLocal(pathName, params); } @Override public void saveToLocal(String pathName, List<MatchedLogRec> list) { super.saveToLocal(pathName, list); } @Override public List<MatchedLogRec> readFromLocal(String pathName) { return super.readFromLocal(pathName); } }
/* * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.orm.jpa.persistenceunit; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Properties; import javax.sql.DataSource; import jakarta.persistence.SharedCacheMode; import jakarta.persistence.ValidationMode; import jakarta.persistence.spi.ClassTransformer; import jakarta.persistence.spi.PersistenceUnitTransactionType; import org.springframework.lang.Nullable; import org.springframework.util.Assert; import org.springframework.util.ClassUtils; /** * Spring's base implementation of the JPA * {@link jakarta.persistence.spi.PersistenceUnitInfo} interface, * used to bootstrap an {@code EntityManagerFactory} in a container. * * <p>This implementation is largely a JavaBean, offering mutators * for all standard {@code PersistenceUnitInfo} properties. * * @author Rod Johnson * @author Juergen Hoeller * @author Costin Leau * @since 2.0 */ public class MutablePersistenceUnitInfo implements SmartPersistenceUnitInfo { @Nullable private String persistenceUnitName; @Nullable private String persistenceProviderClassName; @Nullable private PersistenceUnitTransactionType transactionType; @Nullable private DataSource nonJtaDataSource; @Nullable private DataSource jtaDataSource; private final List<String> mappingFileNames = new ArrayList<>(); private final List<URL> jarFileUrls = new ArrayList<>(); @Nullable private URL persistenceUnitRootUrl; private final List<String> managedClassNames = new ArrayList<>(); private final List<String> managedPackages = new ArrayList<>(); private boolean excludeUnlistedClasses = false; private SharedCacheMode sharedCacheMode = SharedCacheMode.UNSPECIFIED; private ValidationMode validationMode = ValidationMode.AUTO; private Properties properties = new Properties(); private String persistenceXMLSchemaVersion = "2.0"; @Nullable private String persistenceProviderPackageName; public void setPersistenceUnitName(@Nullable String persistenceUnitName) { this.persistenceUnitName = persistenceUnitName; } @Override @Nullable public String getPersistenceUnitName() { return this.persistenceUnitName; } public void setPersistenceProviderClassName(@Nullable String persistenceProviderClassName) { this.persistenceProviderClassName = persistenceProviderClassName; } @Override @Nullable public String getPersistenceProviderClassName() { return this.persistenceProviderClassName; } public void setTransactionType(PersistenceUnitTransactionType transactionType) { this.transactionType = transactionType; } @Override public PersistenceUnitTransactionType getTransactionType() { if (this.transactionType != null) { return this.transactionType; } else { return (this.jtaDataSource != null ? PersistenceUnitTransactionType.JTA : PersistenceUnitTransactionType.RESOURCE_LOCAL); } } public void setJtaDataSource(@Nullable DataSource jtaDataSource) { this.jtaDataSource = jtaDataSource; } @Override @Nullable public DataSource getJtaDataSource() { return this.jtaDataSource; } public void setNonJtaDataSource(@Nullable DataSource nonJtaDataSource) { this.nonJtaDataSource = nonJtaDataSource; } @Override @Nullable public DataSource getNonJtaDataSource() { return this.nonJtaDataSource; } public void addMappingFileName(String mappingFileName) { this.mappingFileNames.add(mappingFileName); } @Override public List<String> getMappingFileNames() { return this.mappingFileNames; } public void addJarFileUrl(URL jarFileUrl) { this.jarFileUrls.add(jarFileUrl); } @Override public List<URL> getJarFileUrls() { return this.jarFileUrls; } public void setPersistenceUnitRootUrl(@Nullable URL persistenceUnitRootUrl) { this.persistenceUnitRootUrl = persistenceUnitRootUrl; } @Override @Nullable public URL getPersistenceUnitRootUrl() { return this.persistenceUnitRootUrl; } /** * Add a managed class name to the persistence provider's metadata. * @see jakarta.persistence.spi.PersistenceUnitInfo#getManagedClassNames() * @see #addManagedPackage */ public void addManagedClassName(String managedClassName) { this.managedClassNames.add(managedClassName); } @Override public List<String> getManagedClassNames() { return this.managedClassNames; } /** * Add a managed package to the persistence provider's metadata. * <p>Note: This refers to annotated {@code package-info.java} files. It does * <i>not</i> trigger entity scanning in the specified package; this is * rather the job of {@link DefaultPersistenceUnitManager#setPackagesToScan}. * @since 4.1 * @see SmartPersistenceUnitInfo#getManagedPackages() * @see #addManagedClassName */ public void addManagedPackage(String packageName) { this.managedPackages.add(packageName); } @Override public List<String> getManagedPackages() { return this.managedPackages; } public void setExcludeUnlistedClasses(boolean excludeUnlistedClasses) { this.excludeUnlistedClasses = excludeUnlistedClasses; } @Override public boolean excludeUnlistedClasses() { return this.excludeUnlistedClasses; } public void setSharedCacheMode(SharedCacheMode sharedCacheMode) { this.sharedCacheMode = sharedCacheMode; } @Override public SharedCacheMode getSharedCacheMode() { return this.sharedCacheMode; } public void setValidationMode(ValidationMode validationMode) { this.validationMode = validationMode; } @Override public ValidationMode getValidationMode() { return this.validationMode; } public void addProperty(String name, String value) { this.properties.setProperty(name, value); } public void setProperties(Properties properties) { Assert.notNull(properties, "Properties must not be null"); this.properties = properties; } @Override public Properties getProperties() { return this.properties; } public void setPersistenceXMLSchemaVersion(String persistenceXMLSchemaVersion) { this.persistenceXMLSchemaVersion = persistenceXMLSchemaVersion; } @Override public String getPersistenceXMLSchemaVersion() { return this.persistenceXMLSchemaVersion; } @Override public void setPersistenceProviderPackageName(@Nullable String persistenceProviderPackageName) { this.persistenceProviderPackageName = persistenceProviderPackageName; } @Nullable public String getPersistenceProviderPackageName() { return this.persistenceProviderPackageName; } /** * This implementation returns the default ClassLoader. * @see org.springframework.util.ClassUtils#getDefaultClassLoader() */ @Override @Nullable public ClassLoader getClassLoader() { return ClassUtils.getDefaultClassLoader(); } /** * This implementation throws an UnsupportedOperationException. */ @Override public void addTransformer(ClassTransformer classTransformer) { throw new UnsupportedOperationException("addTransformer not supported"); } /** * This implementation throws an UnsupportedOperationException. */ @Override public ClassLoader getNewTempClassLoader() { throw new UnsupportedOperationException("getNewTempClassLoader not supported"); } @Override public String toString() { return "PersistenceUnitInfo: name '" + this.persistenceUnitName + "', root URL [" + this.persistenceUnitRootUrl + "]"; } }
package actions.partie; import modele.Joueur; /** * Created by alucard on 24/11/2016. */ public class QuitterPartieAction extends EnvironementCommunPartie { public String execute() { Joueur unJoueur = this.getMaFacade().getJoueur((String) this.getSessionMap().get("pseudo")); //partie unePartie = facade.getPartie(unJoueur); facade.quitterPartie(unJoueur); return SUCCESS; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package interfaz; import datos.ClienteBD; import datos.FacturaDB; import datos.ProductoDB; import datos.VentasBD; import java.awt.Color; import java.awt.event.KeyEvent; import java.sql.SQLException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JList; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import javax.swing.table.DefaultTableModel; import negocio.Cliente; import negocio.Factura; import negocio.Producto; import negocio.Productos; import negocio.Venta; /** * * @author pablo */ public class MostrarFactura extends javax.swing.JInternalFrame { Producto producto = new Producto(); ProductoDB productoBase = new ProductoDB(); Factura factura = new Factura(); Validacion validacion = new Validacion(); Cliente cliente = new Cliente(); boolean entra; ArrayList datos; menu menu; FacturasLista fl; /** * Creates new form VentanaFactura */ public MostrarFactura(ArrayList clave, menu menu, FacturasLista fl) throws SQLException { datos = clave; this.menu = menu; this.fl = fl; initComponents(); entra = false; String[] columnas = {"N°", "Producto", "Codigo", "Precio", "Cantidad", "SubTotal"}; DefaultTableModel temp = new DefaultTableModel(new String[][]{}, columnas); productosT.setModel(temp); productosT.updateUI(); lbfecha.setText(clave.get(1).toString()); numFactura.setText(clave.get(0).toString()); VentasBD ventasBD = new VentasBD(); ArrayList<Venta> ventas = ventasBD.listarFactura(datos.get(0).toString()); String[][] prod = new String[ventas.size()][6]; ArrayList<Producto> productos = new ArrayList(); ArrayList<Producto> produc = new ArrayList(); produc = productoBase.listar(); for (Venta v : ventas) { for (Producto pr : produc) { if (Integer.parseInt(v.getIdProcduto()) == pr.getIdproducto()) { productos.add(pr); } } } for (int i = 0; i < ventas.size(); i++) { prod[i][0] = Integer.toString(i + 1); prod[i][1] = productos.get(i).getNombre(); prod[i][2] = ventas.get(i).getIdProcduto(); prod[i][3] = Double.toString(productos.get(i).getPrecio()); prod[i][4] = ventas.get(i).getCantidad(); prod[i][5] = Double.toString(Integer.parseInt(ventas.get(i).getCantidad()) * productos.get(i).getPrecio()); } DefaultTableModel aux = new DefaultTableModel(prod,columnas); productosT.setModel(aux); productosT.updateUI(); ClienteBD clienteBD=new ClienteBD(); Cliente c=clienteBD.buscar(datos.get(2).toString()); txtnombre.setText(c.getNombre()); txtapellido.setText(c.getApellido()); txtcedula.setText(c.getCedula()); txttelefono.setText(c.getTelefono()); actualizar(); } /** * 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() { jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jPanel2 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); numFactura = new javax.swing.JLabel(); jPanel3 = new javax.swing.JPanel(); lbfecha = new javax.swing.JTextField(); jLabel4 = new javax.swing.JLabel(); jPanel4 = new javax.swing.JPanel(); jLabel5 = new javax.swing.JLabel(); txtdireccion = new javax.swing.JTextField(); jLabel6 = new javax.swing.JLabel(); txtnombre = new javax.swing.JTextField(); jLabel7 = new javax.swing.JLabel(); txtcedula = new javax.swing.JTextField(); jLabel8 = new javax.swing.JLabel(); txtapellido = new javax.swing.JTextField(); jLabel9 = new javax.swing.JLabel(); txttelefono = new javax.swing.JTextField(); jPanel6 = new javax.swing.JPanel(); jPanel5 = new javax.swing.JPanel(); jLabel10 = new javax.swing.JLabel(); lbTotal = new javax.swing.JLabel(); jButton2 = new javax.swing.JButton(); jButton3 = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); productosT = new javax.swing.JTable(); setPreferredSize(new java.awt.Dimension(1000, 576)); jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.RAISED)); jLabel1.setBackground(new java.awt.Color(51, 0, 204)); jLabel1.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N jLabel1.setForeground(new java.awt.Color(0, 51, 204)); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel1.setText("Factura"); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 590, Short.MAX_VALUE) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 2, Short.MAX_VALUE)) ); jPanel2.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jLabel2.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N jLabel2.setForeground(new java.awt.Color(255, 0, 0)); jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); jLabel2.setText("Nro. Factura"); numFactura.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N numFactura.setForeground(new java.awt.Color(0, 0, 153)); numFactura.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); numFactura.setText("0001"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 151, Short.MAX_VALUE) .addComponent(numFactura, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(numFactura, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(19, 19, 19)) ); jPanel3.setBorder(javax.swing.BorderFactory.createEtchedBorder()); lbfecha.setEnabled(false); jLabel4.setText("Fecha de Emicion:"); javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3); jPanel3.setLayout(jPanel3Layout); jPanel3Layout.setHorizontalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup() .addContainerGap() .addComponent(jLabel4) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(lbfecha, javax.swing.GroupLayout.PREFERRED_SIZE, 297, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap(416, Short.MAX_VALUE)) ); jPanel3Layout.setVerticalGroup( jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(lbfecha) .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addContainerGap()) ); jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Informacion:")); jLabel5.setText("Cedula:"); txtdireccion.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N txtdireccion.setEnabled(false); jLabel6.setText("Nombre:"); txtnombre.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N txtnombre.setEnabled(false); jLabel7.setText("Direccion:"); txtcedula.setEditable(false); txtcedula.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N txtcedula.addCaretListener(new javax.swing.event.CaretListener() { public void caretUpdate(javax.swing.event.CaretEvent evt) { txtcedulaCaretUpdate(evt); } }); jLabel8.setText("Apellido:"); txtapellido.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N txtapellido.setEnabled(false); jLabel9.setText("Telefono:"); txttelefono.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N txttelefono.setEnabled(false); javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4); jPanel4.setLayout(jPanel4Layout); jPanel4Layout.setHorizontalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel5, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel6, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(jLabel8, javax.swing.GroupLayout.Alignment.TRAILING)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtcedula, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtnombre, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(txtapellido, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(32, 32, 32) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel7) .addComponent(jLabel9)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(txtdireccion) .addGroup(jPanel4Layout.createSequentialGroup() .addComponent(txttelefono, javax.swing.GroupLayout.PREFERRED_SIZE, 148, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 504, Short.MAX_VALUE))) .addContainerGap()) ); jPanel4Layout.setVerticalGroup( jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel4Layout.createSequentialGroup() .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel5) .addComponent(txtcedula, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel7) .addComponent(txtdireccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel6) .addComponent(txtnombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jLabel9) .addComponent(txttelefono, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel8) .addComponent(txtapellido, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))) ); jPanel6.setBorder(javax.swing.BorderFactory.createEtchedBorder()); javax.swing.GroupLayout jPanel6Layout = new javax.swing.GroupLayout(jPanel6); jPanel6.setLayout(jPanel6Layout); jPanel6Layout.setHorizontalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 980, Short.MAX_VALUE) ); jPanel6Layout.setVerticalGroup( jPanel6Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 127, Short.MAX_VALUE) ); jPanel5.setBorder(javax.swing.BorderFactory.createEtchedBorder()); jLabel10.setText("Total a Pagar:"); lbTotal.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N lbTotal.setForeground(new java.awt.Color(204, 0, 0)); lbTotal.setText("$ 0,00"); jButton2.setText("Salir"); jButton2.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jButton2ActionPerformed(evt); } }); jButton3.setText("Cancelar"); javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5); jPanel5.setLayout(jPanel5Layout); jPanel5Layout.setHorizontalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup() .addContainerGap() .addComponent(jButton2, javax.swing.GroupLayout.PREFERRED_SIZE, 179, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(30, 30, 30) .addComponent(jButton3, javax.swing.GroupLayout.PREFERRED_SIZE, 196, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jLabel10) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(lbTotal) .addGap(18, 18, 18)) ); jPanel5Layout.setVerticalGroup( jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel5Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel10) .addComponent(jButton3) .addComponent(jButton2)) .addGap(21, 21, 21)) .addGroup(jPanel5Layout.createSequentialGroup() .addComponent(lbTotal, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGap(18, 18, 18)) ); productosT.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); productosT.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { productosTMouseClicked(evt); } public void mouseExited(java.awt.event.MouseEvent evt) { productosTMouseExited(evt); } }); jScrollPane1.setViewportView(productosT); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jPanel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(jScrollPane1) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(18, 18, 18) .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 128, Short.MAX_VALUE) .addGap(26, 26, 26) .addComponent(jPanel6, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, 42, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents public boolean valida(String num) { try { Integer.parseInt(num); return true; } catch (Exception e) { return false; } } private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed menu.estado = 4; //boton de productos activa this.show(false); menu.escritorio.add(this.fl); fl.show(); // TODO add your handling code here: }//GEN-LAST:event_jButton2ActionPerformed private void productosTMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_productosTMouseClicked float suma = 0; if (productosT.getSelectedColumn() == 4) { DefaultTableModel aux = new DefaultTableModel(); aux = (DefaultTableModel) productosT.getModel(); for (int i = 0; i < productosT.getRowCount(); i++) { aux.setValueAt(Double.toString( Float.parseFloat(aux.getValueAt(i, 3).toString()) * Float.parseFloat(aux.getValueAt(i, 4).toString())), i, 5); suma = suma + Float.parseFloat(productosT.getValueAt(i, 5).toString()); } lbTotal.setText("$ " + suma); productosT.setModel(aux); productosT.updateUI(); } // TODO add your handling code here: }//GEN-LAST:event_productosTMouseClicked private void productosTMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_productosTMouseExited // actualizar(); }//GEN-LAST:event_productosTMouseExited private void txtcedulaCaretUpdate(javax.swing.event.CaretEvent evt) {//GEN-FIRST:event_txtcedulaCaretUpdate txtnombre.setText(null); txtapellido.setText(null); txttelefono.setText(null); try { ClienteBD clienteBD = new ClienteBD(); validacion = new Validacion(); /*this.validacion.validadorDeCedula(txtcedula.getText())*/ if (txtcedula.getText().length() == 10) { if (clienteBD.buscar(txtcedula.getText()) != null) { txtcedula.setBackground(Color.green); cliente = clienteBD.buscar(txtcedula.getText()); txtnombre.setText(cliente.getNombre()); txtapellido.setText(cliente.getApellido()); txttelefono.setText(cliente.getTelefono()); txtcedula.setBackground(Color.green); } else { txtcedula.setBackground(Color.red); } } else { txtcedula.setBackground(Color.red); } // TODO add your handling code here: } catch (SQLException ex) { Logger.getLogger(MostrarFactura.class.getName()).log(Level.SEVERE, null, ex); } }//GEN-LAST:event_txtcedulaCaretUpdate public void actualizar() { float suma = 0; DefaultTableModel aux = new DefaultTableModel(); aux = (DefaultTableModel) productosT.getModel(); for (int i = 0; i < productosT.getRowCount(); i++) { aux.setValueAt(Double.toString( Float.parseFloat(aux.getValueAt(i, 3).toString()) * Float.parseFloat(aux.getValueAt(i, 4).toString())), i, 5); suma = suma + Float.parseFloat(productosT.getValueAt(i, 5).toString()); } lbTotal.setText("$ " + suma); productosT.setModel(aux); productosT.updateUI(); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton jButton2; private javax.swing.JButton jButton3; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel10; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel4; private javax.swing.JLabel jLabel5; private javax.swing.JLabel jLabel6; private javax.swing.JLabel jLabel7; private javax.swing.JLabel jLabel8; private javax.swing.JLabel jLabel9; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JLabel lbTotal; private javax.swing.JTextField lbfecha; private javax.swing.JLabel numFactura; public javax.swing.JTable productosT; private javax.swing.JTextField txtapellido; private javax.swing.JTextField txtcedula; private javax.swing.JTextField txtdireccion; private javax.swing.JTextField txtnombre; private javax.swing.JTextField txttelefono; // End of variables declaration//GEN-END:variables }
package xtrus.ex.cms.test.message; import org.junit.Test; import xtrus.ex.cms.message.CmsMessage; import xtrus.ex.cms.message.CmsMessageUtils; public class Cms0630_40Test { @Test public void unmarshal() throws Exception { String v = "0096 000 0630RBCOROPShis_corporation.sam 000COROPShis_corporation.sam 0000001990003980"; CmsMessage m = CmsMessageUtils.toMessage(v.getBytes()); System.out.println(m.toString()); v = "0096FTE100009900640RCCOROPShis_corporation.sam 000COROPShis_corporation.sam 0000000000004041"; m = CmsMessageUtils.toMessage(v.getBytes()); System.out.println(m.toString()); } }
package com.ms.module.wechat.clear.activity.image; import android.content.Intent; import android.graphics.drawable.Drawable; import android.view.View; import android.widget.CheckBox; import android.widget.ImageView; import androidx.annotation.Nullable; import com.bumptech.glide.Glide; import com.bumptech.glide.load.DataSource; import com.bumptech.glide.load.engine.GlideException; import com.bumptech.glide.request.RequestListener; import com.bumptech.glide.request.target.Target; import com.chad.library.adapter.base.entity.node.BaseNode; import com.chad.library.adapter.base.provider.BaseNodeProvider; import com.chad.library.adapter.base.viewholder.BaseViewHolder; import com.ms.module.wechat.clear.R; import com.ms.module.wechat.clear.activity.emoji.EmojiDetailsActivity; import com.ms.module.wechat.clear.activity.file.FileChildNode; import org.jetbrains.annotations.NotNull; public class ImageChildProvider extends BaseNodeProvider { private static final String TAG = "ImageChildProvider"; @Override public int getItemViewType() { return 2; } @Override public int getLayoutId() { return R.layout.provider_details_image_child; } @Override public void convert(@NotNull BaseViewHolder baseViewHolder, BaseNode baseNode) { ImageView imageView = baseViewHolder.findView(R.id.imageView); ImageView imageViewCheck = baseViewHolder.findView(R.id.imageViewCheck); if (baseNode instanceof FileChildNode) { FileChildNode childNode = (FileChildNode) baseNode; Glide.with(context).load(childNode.getPath()) .addListener(new RequestListener<Drawable>() { @Override public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) { e.printStackTrace(); return false; } @Override public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) { return false; } }) .into(imageView); imageViewCheck.setSelected(childNode.isCheck()); imageViewCheck.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (childNode.isCheck()) { imageViewCheck.setSelected(false); childNode.setCheck(false); } else { imageViewCheck.setSelected(true); childNode.setCheck(true); } getAdapter().notifyDataSetChanged(); if (ImageDetailsActivity.getInstance() != null) { ImageDetailsActivity.getInstance().updateSelectAll(); } if (EmojiDetailsActivity.getInstance() != null) { EmojiDetailsActivity.getInstance().updateSelectAll(); } } }); baseViewHolder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, ImageActivity.class); intent.putExtra("path", childNode.getPath()); context.startActivity(intent); } }); imageView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(context, ImageActivity.class); intent.putExtra("path", childNode.getPath()); context.startActivity(intent); } }); } } }
package org.vquiz.domain; import java.io.Serializable; /** * * @author Matti Tahvonen <matti@vaadin.com> */ public class Password implements Serializable { private String pw; public Password(String pw) { this.pw = pw; } public String getPw() { return pw; } public void setPw(String pw) { this.pw = pw; } }
package com.animals; import com.animals.Animals; public class Cat extends Animals { @Override public void play() { rootLogger.info("Cat's playing"); } @Override public void voice() { rootLogger.info("Meow"); } }
package com.mss.ejb.resource; import com.mss.ejb.repo.UserRepo; import com.mss.entity.User; import javax.annotation.PostConstruct; import javax.enterprise.context.RequestScoped; import javax.enterprise.event.Observes; import javax.enterprise.event.Reception; import javax.enterprise.inject.Produces; import javax.inject.Inject; import javax.inject.Named; import java.util.List; @RequestScoped public class UsersProducer { @Inject private UserRepo repo; private List<User> users; @Produces @Named public List<User> getUsers() { return users; } public void onChanged(@Observes(notifyObserver = Reception.IF_EXISTS) final User user) { retrieveAllOrderedName(); } @PostConstruct private void retrieveAllOrderedName(){ users = repo.findAll(); } }
package com.raymon.api.bean.success; import java.math.BigDecimal; import java.util.Map; public class StatusBean { private String code; private String message; private String toUrl; private BigDecimal amount; private Map<String,Object> signResult; public String getCode() { return code; } public void setCode(String code) { this.code = code; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public StatusBean() { this.code = 1+""; this.message = "success"; } public StatusBean(String code,String message) { this.code = code; this.message = message; } public String getToUrl() { return toUrl; } public void setToUrl(String toUrl) { this.toUrl = toUrl; } public BigDecimal getAmount() { return amount; } public void setAmount(BigDecimal amount) { this.amount = amount; } public Map<String, Object> getSignResult() { return signResult; } public void setSignResult(Map<String, Object> signResult) { this.signResult = signResult; } }
package ntou.cs.java2021.hw4; import com.fasterxml.jackson.core.JsonFactory; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; import com.google.gson.Gson; import com.google.gson.reflect.TypeToken; import org.simpleflatmapper.csv.CsvParser; import java.io.*; import java.lang.reflect.Type; import java.net.URISyntaxException; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.stream.Collectors; // References: https://gist.github.com/arnaudroger/7cbb9ca1acda66341fc10bf54ab01439 /** * MaskHandler: 提供口罩庫存資訊 * 可從網路上擷取資料 * 可利用提供的資料 回傳藥局的口罩庫存 * 00857005 周固廷 */ public class MaskHandler { private static final String dataURL = "https://data.nhi.gov.tw/Datasets/Download.ashx?rid=A21030000I-D50001-001&l=https://data.nhi.gov.tw/resource/mask/maskdata.csv"; private static final String fileName = "maskdata.csv"; // if the link is unavailable private List<Pharmacy> pharmacyList; private String maskData; private Map<String, String> constructFieldNameTranslationMap() { Map<String, String> fieldNameTranslationMap = new HashMap<String, String>(); fieldNameTranslationMap.put("醫事機構代碼", "id"); fieldNameTranslationMap.put("醫事機構名稱", "name"); fieldNameTranslationMap.put("醫事機構地址", "address"); fieldNameTranslationMap.put("醫事機構電話", "phone"); fieldNameTranslationMap.put("成人口罩剩餘數", "numberOfAdultMasks"); fieldNameTranslationMap.put("兒童口罩剩餘數", "numberOfChildrenMasks"); fieldNameTranslationMap.put("來源資料時間", "updatedTime"); return fieldNameTranslationMap; } public String produceStringFromURL(String requestURL) throws IOException { try (Scanner scanner = new Scanner(new URL(requestURL).openStream(), StandardCharsets.UTF_8.toString())) { scanner.useDelimiter("\\A"); return scanner.hasNext() ? scanner.next() : ""; } } public String produceStringFromFile(String fileName) throws IOException { InputStream is = new FileInputStream(fileName); BufferedReader buf = new BufferedReader(new InputStreamReader(is)); String line = buf.readLine(); StringBuilder sb = new StringBuilder(); while (line != null) { sb.append(line).append("\n"); line = buf.readLine(); } buf.close(); return sb.toString(); } public String produceDataJson(String csvContent) throws IOException, URISyntaxException { Map<String, String> fieldNameTranslationMap = constructFieldNameTranslationMap(); org.simpleflatmapper.lightningcsv.CsvReader reader = CsvParser.reader(csvContent); JsonFactory jsonFactory = new JsonFactory(); ByteArrayOutputStream output = new ByteArrayOutputStream(); Iterator<String[]> iterator = reader.iterator(); String[] headers = iterator.next(); try (JsonGenerator jsonGenerator = jsonFactory.createGenerator(new PrintStream(output))) { jsonGenerator.setPrettyPrinter(new DefaultPrettyPrinter()); jsonGenerator.writeStartArray(); while (iterator.hasNext()) { jsonGenerator.writeStartObject(); String[] values = iterator.next(); int nbCells = Math.min(values.length, headers.length); for (int i = 0; i < nbCells; i++) { jsonGenerator.writeFieldName(fieldNameTranslationMap.get(headers[i])); jsonGenerator.writeString(values[i]); } jsonGenerator.writeEndObject(); } jsonGenerator.writeEndArray(); } return output.toString(); } public List<Pharmacy> convertToObjects(String jsonData) { Gson gson = new Gson(); ArrayList<Pharmacy> clinicList = new ArrayList<Pharmacy>(); try { Type listType = new TypeToken<List<Pharmacy>>() { }.getType(); clinicList = gson.fromJson(jsonData, listType); } catch (Exception e) { System.err.println("Exception: " + e); } return clinicList; } public List<Pharmacy> findPharmacies(String queryName, String queryAddress) { List<Pharmacy> matchingElements = pharmacyList.stream().filter( str -> str.getName().trim().contains(queryName) && str.getAddress().trim().contains(queryAddress)) .collect(Collectors.toList()); return matchingElements; } public void initialize() throws IOException, URISyntaxException { maskData = produceStringFromURL(dataURL); // String maskData = produceStringFromFile(fileName); String maskDataJson = produceDataJson(maskData); pharmacyList = convertToObjects(maskDataJson); } public String getMaskData() { String str = ""; for (Pharmacy pharmacy : pharmacyList) { str += pharmacy + "\n"; } return str; } }
/** * Noark所有功能注解定义 */ package xyz.noark.core.annotation;
/* * Copyright 2002-2022 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.aot.hint.support; import java.util.List; import java.util.Map; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.springframework.aot.hint.MemberCategory; import org.springframework.aot.hint.RuntimeHints; import org.springframework.aot.hint.RuntimeHintsRegistrar; import org.springframework.core.io.support.SpringFactoriesLoader; import org.springframework.core.log.LogMessage; import org.springframework.lang.Nullable; import org.springframework.util.ClassUtils; /** * {@link RuntimeHintsRegistrar} to register hints for {@code spring.factories}. * * @author Brian Clozel * @author Phillip Webb * @since 6.0 * @see SpringFactoriesLoader */ class SpringFactoriesLoaderRuntimeHints implements RuntimeHintsRegistrar { private static final List<String> RESOURCE_LOCATIONS = List.of(SpringFactoriesLoader.FACTORIES_RESOURCE_LOCATION); private static final Log logger = LogFactory.getLog(SpringFactoriesLoaderRuntimeHints.class); @Override public void registerHints(RuntimeHints hints, ClassLoader classLoader) { for (String resourceLocation : RESOURCE_LOCATIONS) { registerHints(hints, classLoader, resourceLocation); } } private void registerHints(RuntimeHints hints, ClassLoader classLoader, String resourceLocation) { hints.resources().registerPattern(resourceLocation); Map<String, List<String>> factories = ExtendedSpringFactoriesLoader.accessLoadFactoriesResource(classLoader, resourceLocation); factories.forEach((factoryClassName, implementationClassNames) -> registerHints(hints, classLoader, factoryClassName, implementationClassNames)); } private void registerHints(RuntimeHints hints, ClassLoader classLoader, String factoryClassName, List<String> implementationClassNames) { Class<?> factoryClass = resolveClassName(classLoader, factoryClassName); if (factoryClass == null) { if (logger.isTraceEnabled()) { logger.trace(LogMessage.format("Skipping factories for [%s]", factoryClassName)); } return; } if (logger.isTraceEnabled()) { logger.trace(LogMessage.format("Processing factories for [%s]", factoryClassName)); } hints.reflection().registerType(factoryClass, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS); for (String implementationClassName : implementationClassNames) { Class<?> implementationType = resolveClassName(classLoader, implementationClassName); if (logger.isTraceEnabled()) { logger.trace(LogMessage.format("%s factory type [%s] and implementation [%s]", (implementationType != null ? "Processing" : "Skipping"), factoryClassName, implementationClassName)); } if (implementationType != null) { hints.reflection().registerType(implementationType, MemberCategory.INVOKE_DECLARED_CONSTRUCTORS); } } } @Nullable private Class<?> resolveClassName(ClassLoader classLoader, String factoryClassName) { try { Class<?> clazz = ClassUtils.resolveClassName(factoryClassName, classLoader); // Force resolution of all constructors to cache clazz.getDeclaredConstructors(); return clazz; } catch (Throwable ex) { return null; } } private static class ExtendedSpringFactoriesLoader extends SpringFactoriesLoader { ExtendedSpringFactoriesLoader(@Nullable ClassLoader classLoader, Map<String, List<String>> factories) { super(classLoader, factories); } static Map<String, List<String>> accessLoadFactoriesResource(ClassLoader classLoader, String resourceLocation) { return SpringFactoriesLoader.loadFactoriesResource(classLoader, resourceLocation); } } }
/* * Copyright 2002-2023 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.messaging.rsocket.service; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.time.Duration; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.function.Function; import java.util.stream.Collectors; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; import org.springframework.aop.framework.ProxyFactory; import org.springframework.aop.framework.ReflectiveMethodInvocation; import org.springframework.core.MethodIntrospector; import org.springframework.core.ReactiveAdapterRegistry; import org.springframework.core.annotation.AnnotatedElementUtils; import org.springframework.lang.Nullable; import org.springframework.messaging.rsocket.RSocketRequester; import org.springframework.util.Assert; import org.springframework.util.StringValueResolver; /** * Factory to create a client proxy from an RSocket service interface with * {@link RSocketExchange @RSocketExchange} methods. * * <p>To create an instance, use static methods to obtain a * {@link Builder Builder}. * * @author Rossen Stoyanchev * @since 6.0 */ public final class RSocketServiceProxyFactory { private final RSocketRequester rsocketRequester; private final List<RSocketServiceArgumentResolver> argumentResolvers; @Nullable private final StringValueResolver embeddedValueResolver; private final ReactiveAdapterRegistry reactiveAdapterRegistry; @Nullable private final Duration blockTimeout; private RSocketServiceProxyFactory( RSocketRequester rsocketRequester, List<RSocketServiceArgumentResolver> argumentResolvers, @Nullable StringValueResolver embeddedValueResolver, ReactiveAdapterRegistry reactiveAdapterRegistry, @Nullable Duration blockTimeout) { this.rsocketRequester = rsocketRequester; this.argumentResolvers = argumentResolvers; this.embeddedValueResolver = embeddedValueResolver; this.reactiveAdapterRegistry = reactiveAdapterRegistry; this.blockTimeout = blockTimeout; } /** * Return a proxy that implements the given RSocket service interface to * perform RSocket requests and retrieve responses through the configured * {@link RSocketRequester}. * @param serviceType the RSocket service to create a proxy for * @param <S> the RSocket service type * @return the created proxy */ public <S> S createClient(Class<S> serviceType) { List<RSocketServiceMethod> serviceMethods = MethodIntrospector.selectMethods(serviceType, this::isExchangeMethod).stream() .map(method -> createRSocketServiceMethod(serviceType, method)) .toList(); return ProxyFactory.getProxy(serviceType, new ServiceMethodInterceptor(serviceMethods)); } private boolean isExchangeMethod(Method method) { return AnnotatedElementUtils.hasAnnotation(method, RSocketExchange.class); } private <S> RSocketServiceMethod createRSocketServiceMethod(Class<S> serviceType, Method method) { Assert.notNull(this.argumentResolvers, "No argument resolvers: afterPropertiesSet was not called"); return new RSocketServiceMethod( method, serviceType, this.argumentResolvers, this.rsocketRequester, this.embeddedValueResolver, this.reactiveAdapterRegistry, this.blockTimeout); } /** * Return an {@link RSocketServiceProxyFactory} builder, initialized with the * given client. */ public static Builder builder(RSocketRequester requester) { return new Builder().rsocketRequester(requester); } /** * Return an {@link RSocketServiceProxyFactory} builder. */ public static Builder builder() { return new Builder(); } /** * Builder to create an {@link RSocketServiceProxyFactory}. */ public static final class Builder { @Nullable private RSocketRequester rsocketRequester; private final List<RSocketServiceArgumentResolver> customArgumentResolvers = new ArrayList<>(); @Nullable private StringValueResolver embeddedValueResolver; private ReactiveAdapterRegistry reactiveAdapterRegistry = ReactiveAdapterRegistry.getSharedInstance(); @Nullable private Duration blockTimeout; private Builder() { } /** * Provide the requester to perform requests through. * @param requester the requester to use * @return the same builder instance */ public Builder rsocketRequester(RSocketRequester requester) { this.rsocketRequester = requester; return this; } /** * Register a custom argument resolver, invoked ahead of default resolvers. * @param resolver the resolver to add * @return the same builder instance */ public Builder customArgumentResolver(RSocketServiceArgumentResolver resolver) { this.customArgumentResolvers.add(resolver); return this; } /** * Set the {@link StringValueResolver} to use for resolving placeholders * and expressions embedded in {@link RSocketExchange#value()}. * @param resolver the resolver to use * @return this same builder instance */ public Builder embeddedValueResolver(StringValueResolver resolver) { this.embeddedValueResolver = resolver; return this; } /** * Set the {@link ReactiveAdapterRegistry} to use to support different * asynchronous types for HTTP service method return values. * <p>By default this is {@link ReactiveAdapterRegistry#getSharedInstance()}. * @return this same builder instance */ public Builder reactiveAdapterRegistry(ReactiveAdapterRegistry registry) { this.reactiveAdapterRegistry = registry; return this; } /** * Configure how long to block for the response of an RSocket service method * with a synchronous (blocking) method signature. * <p>By default this is not set, in which case the behavior depends on * connection and response timeout settings of the underlying RSocket * {@code ClientTransport} as well as RSocket keep-alive settings. * We recommend configuring timeout values at the RSocket level which * provides more control. * @param blockTimeout the timeout value * @return this same builder instance */ public Builder blockTimeout(@Nullable Duration blockTimeout) { this.blockTimeout = blockTimeout; return this; } /** * Build the {@link RSocketServiceProxyFactory} instance. */ public RSocketServiceProxyFactory build() { Assert.notNull(this.rsocketRequester, "RSocketRequester is required"); return new RSocketServiceProxyFactory( this.rsocketRequester, initArgumentResolvers(), this.embeddedValueResolver, this.reactiveAdapterRegistry, this.blockTimeout); } private List<RSocketServiceArgumentResolver> initArgumentResolvers() { // Custom List<RSocketServiceArgumentResolver> resolvers = new ArrayList<>(this.customArgumentResolvers); // Annotation-based resolvers.add(new PayloadArgumentResolver(this.reactiveAdapterRegistry, false)); resolvers.add(new DestinationVariableArgumentResolver()); // Type-based resolvers.add(new MetadataArgumentResolver()); // Fallback resolvers.add(new PayloadArgumentResolver(this.reactiveAdapterRegistry, true)); return resolvers; } } /** * {@link MethodInterceptor} that invokes an {@link RSocketServiceMethod}. */ private static final class ServiceMethodInterceptor implements MethodInterceptor { private final Map<Method, RSocketServiceMethod> serviceMethods; private ServiceMethodInterceptor(List<RSocketServiceMethod> methods) { this.serviceMethods = methods.stream() .collect(Collectors.toMap(RSocketServiceMethod::getMethod, Function.identity())); } @Override public Object invoke(MethodInvocation invocation) throws Throwable { Method method = invocation.getMethod(); RSocketServiceMethod serviceMethod = this.serviceMethods.get(method); if (serviceMethod != null) { return serviceMethod.invoke(invocation.getArguments()); } if (method.isDefault()) { if (invocation instanceof ReflectiveMethodInvocation reflectiveMethodInvocation) { Object proxy = reflectiveMethodInvocation.getProxy(); return InvocationHandler.invokeDefault(proxy, method, invocation.getArguments()); } } throw new IllegalStateException("Unexpected method invocation: " + method); } } }
/* * Copyright 2011 The Kuali Foundation. * * Licensed under the Educational Community License, Version 1.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.opensource.org/licenses/ecl1.php * * 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.kuali.ole.select.service.impl; import org.kuali.ole.select.service.OleForiegnVendorPhoneNumberService; import java.util.regex.Matcher; import java.util.regex.Pattern; public class OleForiegnVendorPhoneNumberServiceImpl implements OleForiegnVendorPhoneNumberService { @Override public boolean isValidForiegnVendorPhoneNumber(String phoneNumber) { // TODO Auto-generated method stub boolean valid = true; Pattern p = Pattern.compile("^[0-9]{1}(([0-9]*-[0-9]*)*|([0-9]* [0-9]*)*|[0-9]*)[0-9]{1}$"); Matcher m = p.matcher(phoneNumber); StringBuffer sb = new StringBuffer(); boolean result = m.matches(); if (!result) { valid = false; } return valid; } }
package edu.seminolestate.albumflippertwo; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.ImageView; import android.widget.Spinner; import android.widget.TextView; import org.jetbrains.annotations.NotNull; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.net.URL; import java.nio.charset.Charset; public class MainActivity extends AppCompatActivity { // album ids came from musizmatch.com, which hosts the api used in fetching track lists. int albumIds[] = new int[] {10266158,10282885,10285026,10276947,19659084,15496436,10266044,10287445,10265979, 10277138,10820946,10280365,10294206,21359448,10266226,12659742,10279957,10285332}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } // Onclick instatiates views, gets spinner, formulates url, gets objects and sets track text view public void onClickFindCover(View view) throws Exception { ImageView image = findViewById(R.id.covers); Spinner cover = findViewById(R.id.spinner); TextView tracks = findViewById(R.id.track_list); int coverNumber = cover.getSelectedItemPosition() +1; String coverName = "cover" + coverNumber; String albumId = String.valueOf(albumIds[cover.getSelectedItemPosition()]); int resID = getResources().getIdentifier(coverName, "drawable", "edu.seminolestate.albumflippertwo"); image.setImageResource(resID); String url = "https://api.musixmatch.com/ws/1.1/album.tracks.get?format=jsonp&callback=callback&album_id=" + albumId + "&apikey=3d698869e3c288022483027587b42d1f"; JSONArray trackArray = readJsonFromUrl(url); try { String tracksLists = getTrackObjects(trackArray).toString(); tracks.setText(tracksLists); } catch (Exception e) { e.printStackTrace(); } } //This method takes the url and sends it to the internal class for retrieval from the api. The class // extends AsyncTask which allows internet connections outside the main thread which is not permitted. // this method then drills down into the JSON objects until it comes to the JSON array containing the // track list public static JSONArray readJsonFromUrl(String url) throws Exception, JSONException { try { String jsonTextA = new GetTheTracks().execute(url).get(); //calls the doInBackground method //in the internal class sending the url as a parameter. the .get() gets the returned string String jsonText = jsonTextA.substring(9); //trim unnecessary "callback(" from front of api string JSONObject json = new JSONObject(jsonText);//make JsonObject from text JSONObject message = json.getJSONObject("message");//drill into first layer JSONObject body = message.getJSONObject("body");//drill into second layer JSONArray trackList = body.getJSONArray("track_list");//drillinto tracklist and get array return trackList; } catch (Exception e) {} return null; } // This method takes the JSONArray with the track list. It then loops the array getting the track object, // for each track, then from that, gets the track_name object and appends it to the Stringbuilder that // is then set as text for the "Track Listing" TextView. public static StringBuilder getTrackObjects(JSONArray trackArray) throws IOException, JSONException { try { StringBuilder tracksList = new StringBuilder();//instantiate a sb for TrackList TV for (int i = 0; i < trackArray.length(); ++i) {//loop through number of tracks is JSONArray JSONObject tracks = trackArray.getJSONObject(i);//get JSONObject[i] JSONObject trackItem = tracks.getJSONObject("track");//fetch the track there String trackName = trackItem.get("track_name").toString();//from that track, fetch the track name tracksList.append(trackName);//add it to the sb tracksList.append("\n");//add new line to sb } return tracksList; } catch (Exception e) { } return null; } // readAll takes string of characters from url reader input stream and adds to stringbuilder @NotNull public static String readAll(Reader rd) throws IOException { StringBuilder sb = new StringBuilder(); int cp; while ((cp = rd.read()) != -1) { sb.append((char) cp); } return sb.toString(); } } // internal class to take internet access out of main thread this reads the data from the url, open an inputstream // and reads it in. Sends back a JSON string with the album data // Using external internet connection required adding <uses-permission android:name="android.permission.INTERNET"/> // To AndroidManifest.xml. class GetTheTracks extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... url) { String trackList = url[0]; //takes first url on list (only one parameter in this case) String jsonTextA; try { InputStream is = new URL(trackList).openStream(); //create input stream BufferedReader rd = new BufferedReader(new InputStreamReader(is, Charset.forName("UTF-8")));//make br jsonTextA = MainActivity.readAll(rd);//calls readAll method in main class to read it into the string } catch (Exception e) { jsonTextA = e.toString(); } return jsonTextA; //returns JSON string to main class } @Override protected void onPostExecute(String result) { super.onPostExecute(result); } }
package cern.molr.inspector.remote; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.BufferedReader; import java.time.Duration; import java.util.Optional; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; /** * Reads commands from a {@link BufferedReader} and proxies them to a given function in a regular interval. Unless * specified, the interval defaults to 100 milliseconds. The reader runs a separate thread to continuously read input * from the stream without blocking. */ public abstract class RemoteReader implements AutoCloseable { private static final Logger LOGGER = LoggerFactory.getLogger(RemoteReader.class); private static final Duration DEFAULT_READING_INTERVAL = Duration.ofMillis(100); private final ScheduledExecutorService service; private final BufferedReader reader; private Optional<Runnable> onClose = Optional.empty(); private Optional<Runnable> onReadingAttempt = Optional.empty(); /** * Creates a reader which reads commands from the given reader and forwards them to the controller. * * @param reader The reader to read incoming commands from. */ public RemoteReader(BufferedReader reader) { this(reader, DEFAULT_READING_INTERVAL); } /** * Creates a reader which reads commands from the given reader and forwards them to the controller. * * @param reader The reader to read incoming commands from. * @param readingInterval The interval with which to read commands. May not be negative. */ public RemoteReader(BufferedReader reader, Duration readingInterval) { if (readingInterval.isNegative()) { throw new IllegalArgumentException("Reading interval cannot be less than 0"); } this.reader = reader; service = Executors.newSingleThreadScheduledExecutor(); Runnable read = () -> { try { onReadingAttempt.ifPresent(Runnable::run); if(reader.ready()) { readCommand(reader); } } catch(Exception exception) { LOGGER.warn("Exception trying to read command", exception); } }; service.scheduleAtFixedRate(read, readingInterval.toMillis(), readingInterval.toMillis(), TimeUnit.MILLISECONDS); } /** * Reads a command from the given {@link BufferedReader}. * * @param reader The reader to read the next command from. */ protected abstract void readCommand(BufferedReader reader); @Override public void close() { closeResource(reader, e -> LOGGER.warn("Failed to close reader", e)); service.shutdown(); onClose.ifPresent(Runnable::run); } static void closeResource(AutoCloseable closeable, Consumer<Exception> onError) { try { closeable.close(); } catch (Exception e) { onError.accept(e); } } public void setOnReadingAttempt(Runnable onReadingAttempt) { this.onReadingAttempt = Optional.ofNullable(onReadingAttempt); } public void setOnClose(Runnable onClose) { this.onClose = Optional.of(onClose); } }
package com.github.dongchan.scheduler.stats; /** * @author DongChan * @date 2020/10/22 * @time 11:40 PM */ public interface StatsRegistry { enum SchedulerStatsEvent{ UNEXPECTED_ERROR, UNRESOLVED_TASK, RAN_EXECUTE_DUE } void register(SchedulerStatsEvent e); StatsRegistry NOOP = new DefaultStatsRegistry(); class DefaultStatsRegistry implements StatsRegistry{ @Override public void register(SchedulerStatsEvent e) { } } }
package com.project.board.web.Board.dto; import lombok.Getter; import lombok.RequiredArgsConstructor; import lombok.Setter; @Getter @Setter @RequiredArgsConstructor public class DeleteBoardDto { // 게시물 UID private Long BOARD_UID; // 원글 UID private Long ORIGIN_NO; // 계층 깊이 private Long LAYER_DEPTH; }
package entity; // Generated Jan 22, 2019 1:40:07 AM by Hibernate Tools 3.5.0.Final import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.springframework.format.annotation.DateTimeFormat; /** * Staffs generated by hbm2java */ @Entity @Table(name = "Staffs", schema = "dbo", catalog = "Personnel") public class Staffs implements java.io.Serializable { private int id; private String name; private boolean gender; private Date birthday; private String photo; private String email; private String phone; private double salary; private String notes; private Departs departId; public Staffs() { } public Staffs(int id) { this.id = id; } public Staffs( String name, boolean gender, Date birthday, String photo, String email, String phone, double salary, String notes, Departs departId) { this.name = name; this.gender = gender; this.birthday = birthday; this.photo = photo; this.email = email; this.phone = phone; this.salary = salary; this.notes = notes; this.departId = departId; } public Staffs(int id, String name, boolean gender, Date birthday, String photo, String email, String phone, double salary, String notes, Departs departId) { this.id = id; this.name = name; this.gender = gender; this.birthday = birthday; this.photo = photo; this.email = email; this.phone = phone; this.salary = salary; this.notes = notes; this.departId = departId; } @Id @GeneratedValue(strategy=GenerationType.IDENTITY) @Column(name = "Id", unique = true, nullable = false) public int getId() { return this.id; } public void setId(int id) { this.id = id; } @Column(name = "Name", nullable = false) public String getName() { return this.name; } public void setName(String name) { this.name = name; } @Column(name = "Gender", nullable = false) public boolean isGender() { return this.gender; } public void setGender(boolean gender) { this.gender = gender; } @Column(name = "Birthday", nullable = false) @Temporal(TemporalType.DATE) @DateTimeFormat(pattern="MM/dd/yyyy") public Date getBirthday() { return this.birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } @Column(name = "Photo", nullable = false) public String getPhoto() { return this.photo; } public void setPhoto(String photo) { this.photo = photo; } @Column(name = "Email", nullable = false) public String getEmail() { return this.email; } public void setEmail(String email) { this.email = email; } @Column(name = "Phone", nullable = false) public String getPhone() { return this.phone; } public void setPhone(String phone) { this.phone = phone; } @Column(name = "Salary", nullable = false, precision = 53, scale = 0) public double getSalary() { return this.salary; } public void setSalary(double salary) { this.salary = salary; } @Column(name = "Notes") public String getNotes() { return this.notes; } public void setNotes(String notes) { this.notes = notes; } @ManyToOne @JoinColumn(name = "DepartId", nullable = false) public Departs getDepartId() { return this.departId; } public void setDepartId(Departs departId) { this.departId = departId; } @Override public String toString() { return "Staffs [id=" + id + ", name=" + name + ", gender=" + gender + ", birthday=" + birthday + ", photo=" + photo + ", email=" + email + ", phone=" + phone + ", salary=" + salary + ", notes=" + notes + ", departId=" + departId + "]"; } }
package com.machao.base.controller; import java.io.File; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.io.FileUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestControllerAdvice; import com.machao.base.model.exception.RequestParamsErrorException; import com.machao.base.model.exception.ResourceNotFoundException; import com.machao.base.model.exception.ResourceNotReadyException; import com.machao.base.model.persit.StaticResource; import com.machao.base.model.persit.StaticResource.Type; import com.machao.base.service.ImageService; import com.machao.base.service.StaticResourceService; @RestController @RestControllerAdvice public class StaticResourceImageController extends BaseController{ private static final Logger logger = LoggerFactory.getLogger(StaticResourceImageController.class); @Autowired private StaticResourceService staticResourceService; @GetMapping("/image/{uuid}") public void image(@PathVariable String uuid, @RequestParam(name="w", defaultValue="0") int width, @RequestParam(name="h", defaultValue="0") int height, HttpServletRequest request, HttpServletResponse response) { super.checkBurglarChain(request); StaticResource staticResource = staticResourceService.findById(uuid).orElseThrow(ResourceNotFoundException::new); if(!staticResource.isHandled()) throw new ResourceNotReadyException(); if(!Type.image.equals(staticResource.getType())) throw new RequestParamsErrorException(); File file = (width == 0 || height == 0) ? new File(staticResource.getPath()) : ImageService.obtainFile(new File(staticResource.getPath()), width, height); if(!file.exists()) throw new ResourceNotFoundException(); try { response.setContentType(staticResource.getContentType()); response.getOutputStream().write(FileUtils.readFileToByteArray(file)); } catch (IOException e) { logger.error("file: {} send error", file); } } }
/* * Copyright 2002-2020 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.beans.factory; import java.text.SimpleDateFormat; import java.util.Date; import org.openjdk.jmh.annotations.Benchmark; import org.openjdk.jmh.annotations.BenchmarkMode; import org.openjdk.jmh.annotations.Mode; import org.openjdk.jmh.annotations.Scope; import org.openjdk.jmh.annotations.Setup; import org.openjdk.jmh.annotations.State; import org.openjdk.jmh.infra.Blackhole; import org.springframework.beans.factory.support.DefaultListableBeanFactory; import org.springframework.beans.factory.xml.XmlBeanDefinitionReader; import org.springframework.beans.propertyeditors.CustomDateEditor; import static org.springframework.core.testfixture.io.ResourceTestUtils.qualifiedResource; /** * Benchmark for creating prototype beans in a concurrent fashion. * This benchmark requires to customize the number of worker threads {@code -t <int>} on the * CLI when running this particular benchmark to leverage concurrency. * * @author Brian Clozel */ @BenchmarkMode(Mode.Throughput) public class ConcurrentBeanFactoryBenchmark { @State(Scope.Benchmark) public static class BenchmarkState { public DefaultListableBeanFactory factory; @Setup public void setup() { this.factory = new DefaultListableBeanFactory(); new XmlBeanDefinitionReader(this.factory).loadBeanDefinitions( qualifiedResource(ConcurrentBeanFactoryBenchmark.class, "context.xml")); this.factory.addPropertyEditorRegistrar( registry -> registry.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy/MM/dd"), false))); } } @Benchmark public void concurrentBeanCreation(BenchmarkState state, Blackhole bh) { bh.consume(state.factory.getBean("bean1")); bh.consume(state.factory.getBean("bean2")); } public static class ConcurrentBean { private Date date; public Date getDate() { return this.date; } public void setDate(Date date) { this.date = date; } } }
package com.arthur.bishi.pdd0822; import java.math.BigInteger; import java.util.Scanner; /** * @description: * @author: arthurji * @date: 2021/8/22 19:01 * @modifiedBy: * @version: 1.0 */ public class No3 { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int T = scanner.nextInt(); for (int i = 0; i < T; i++) { int N = scanner.nextInt(); int M = scanner.nextInt(); BigInteger ten = new BigInteger("10"); BigInteger two = new BigInteger("2"); BigInteger BN = new BigInteger("1"); BigInteger BM = new BigInteger(M + ""); BigInteger BMT = new BigInteger(M + ""); while (N > 1) { BN = BN.multiply(ten); N--; } while (BN.compareTo(BM) > 0) { BM = BM.multiply(two); } while (BN.compareTo(BM) <= 0) { BM = BM.subtract(BMT); } BM = BM.add(BMT); System.out.println(BM.toString()); } } }
public class FillProduct implements Command { @Override public void execute(String[] cmdParts) { try { if (cmdParts.length != 3) { throw new InsufficientParameterException(); } ShopSystem shopSystem = ShopSystem.getInstance(); int productID = Integer.parseInt(cmdParts[1]); int quantity = Integer.parseInt(cmdParts[2]); if (quantity < 0) { throw new AmountIsNegativeException(); } shopSystem.fillProductForCompany(productID, quantity); System.out.printf("Successfully fill the product %s with quantity of %s. \n", productID, quantity); } catch (Exception e) { System.out.println(e.getMessage()); } } }
/** * This class is generated by jOOQ */ package schema.tables.records; import java.sql.Timestamp; import javax.annotation.Generated; import org.jooq.Field; import org.jooq.Record1; import org.jooq.Record6; import org.jooq.Row6; import org.jooq.impl.UpdatableRecordImpl; import schema.tables.CourseOverviewsCourseoverviewimageset; /** * This class is generated by jOOQ. */ @Generated( value = { "http://www.jooq.org", "jOOQ version:3.8.4" }, comments = "This class is generated by jOOQ" ) @SuppressWarnings({ "all", "unchecked", "rawtypes" }) public class CourseOverviewsCourseoverviewimagesetRecord extends UpdatableRecordImpl<CourseOverviewsCourseoverviewimagesetRecord> implements Record6<Integer, Timestamp, Timestamp, String, String, String> { private static final long serialVersionUID = -2136505815; /** * Setter for <code>bitnami_edx.course_overviews_courseoverviewimageset.id</code>. */ public void setId(Integer value) { set(0, value); } /** * Getter for <code>bitnami_edx.course_overviews_courseoverviewimageset.id</code>. */ public Integer getId() { return (Integer) get(0); } /** * Setter for <code>bitnami_edx.course_overviews_courseoverviewimageset.created</code>. */ public void setCreated(Timestamp value) { set(1, value); } /** * Getter for <code>bitnami_edx.course_overviews_courseoverviewimageset.created</code>. */ public Timestamp getCreated() { return (Timestamp) get(1); } /** * Setter for <code>bitnami_edx.course_overviews_courseoverviewimageset.modified</code>. */ public void setModified(Timestamp value) { set(2, value); } /** * Getter for <code>bitnami_edx.course_overviews_courseoverviewimageset.modified</code>. */ public Timestamp getModified() { return (Timestamp) get(2); } /** * Setter for <code>bitnami_edx.course_overviews_courseoverviewimageset.small_url</code>. */ public void setSmallUrl(String value) { set(3, value); } /** * Getter for <code>bitnami_edx.course_overviews_courseoverviewimageset.small_url</code>. */ public String getSmallUrl() { return (String) get(3); } /** * Setter for <code>bitnami_edx.course_overviews_courseoverviewimageset.large_url</code>. */ public void setLargeUrl(String value) { set(4, value); } /** * Getter for <code>bitnami_edx.course_overviews_courseoverviewimageset.large_url</code>. */ public String getLargeUrl() { return (String) get(4); } /** * Setter for <code>bitnami_edx.course_overviews_courseoverviewimageset.course_overview_id</code>. */ public void setCourseOverviewId(String value) { set(5, value); } /** * Getter for <code>bitnami_edx.course_overviews_courseoverviewimageset.course_overview_id</code>. */ public String getCourseOverviewId() { return (String) get(5); } // ------------------------------------------------------------------------- // Primary key information // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public Record1<Integer> key() { return (Record1) super.key(); } // ------------------------------------------------------------------------- // Record6 type implementation // ------------------------------------------------------------------------- /** * {@inheritDoc} */ @Override public Row6<Integer, Timestamp, Timestamp, String, String, String> fieldsRow() { return (Row6) super.fieldsRow(); } /** * {@inheritDoc} */ @Override public Row6<Integer, Timestamp, Timestamp, String, String, String> valuesRow() { return (Row6) super.valuesRow(); } /** * {@inheritDoc} */ @Override public Field<Integer> field1() { return CourseOverviewsCourseoverviewimageset.COURSE_OVERVIEWS_COURSEOVERVIEWIMAGESET.ID; } /** * {@inheritDoc} */ @Override public Field<Timestamp> field2() { return CourseOverviewsCourseoverviewimageset.COURSE_OVERVIEWS_COURSEOVERVIEWIMAGESET.CREATED; } /** * {@inheritDoc} */ @Override public Field<Timestamp> field3() { return CourseOverviewsCourseoverviewimageset.COURSE_OVERVIEWS_COURSEOVERVIEWIMAGESET.MODIFIED; } /** * {@inheritDoc} */ @Override public Field<String> field4() { return CourseOverviewsCourseoverviewimageset.COURSE_OVERVIEWS_COURSEOVERVIEWIMAGESET.SMALL_URL; } /** * {@inheritDoc} */ @Override public Field<String> field5() { return CourseOverviewsCourseoverviewimageset.COURSE_OVERVIEWS_COURSEOVERVIEWIMAGESET.LARGE_URL; } /** * {@inheritDoc} */ @Override public Field<String> field6() { return CourseOverviewsCourseoverviewimageset.COURSE_OVERVIEWS_COURSEOVERVIEWIMAGESET.COURSE_OVERVIEW_ID; } /** * {@inheritDoc} */ @Override public Integer value1() { return getId(); } /** * {@inheritDoc} */ @Override public Timestamp value2() { return getCreated(); } /** * {@inheritDoc} */ @Override public Timestamp value3() { return getModified(); } /** * {@inheritDoc} */ @Override public String value4() { return getSmallUrl(); } /** * {@inheritDoc} */ @Override public String value5() { return getLargeUrl(); } /** * {@inheritDoc} */ @Override public String value6() { return getCourseOverviewId(); } /** * {@inheritDoc} */ @Override public CourseOverviewsCourseoverviewimagesetRecord value1(Integer value) { setId(value); return this; } /** * {@inheritDoc} */ @Override public CourseOverviewsCourseoverviewimagesetRecord value2(Timestamp value) { setCreated(value); return this; } /** * {@inheritDoc} */ @Override public CourseOverviewsCourseoverviewimagesetRecord value3(Timestamp value) { setModified(value); return this; } /** * {@inheritDoc} */ @Override public CourseOverviewsCourseoverviewimagesetRecord value4(String value) { setSmallUrl(value); return this; } /** * {@inheritDoc} */ @Override public CourseOverviewsCourseoverviewimagesetRecord value5(String value) { setLargeUrl(value); return this; } /** * {@inheritDoc} */ @Override public CourseOverviewsCourseoverviewimagesetRecord value6(String value) { setCourseOverviewId(value); return this; } /** * {@inheritDoc} */ @Override public CourseOverviewsCourseoverviewimagesetRecord values(Integer value1, Timestamp value2, Timestamp value3, String value4, String value5, String value6) { value1(value1); value2(value2); value3(value3); value4(value4); value5(value5); value6(value6); return this; } // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- /** * Create a detached CourseOverviewsCourseoverviewimagesetRecord */ public CourseOverviewsCourseoverviewimagesetRecord() { super(CourseOverviewsCourseoverviewimageset.COURSE_OVERVIEWS_COURSEOVERVIEWIMAGESET); } /** * Create a detached, initialised CourseOverviewsCourseoverviewimagesetRecord */ public CourseOverviewsCourseoverviewimagesetRecord(Integer id, Timestamp created, Timestamp modified, String smallUrl, String largeUrl, String courseOverviewId) { super(CourseOverviewsCourseoverviewimageset.COURSE_OVERVIEWS_COURSEOVERVIEWIMAGESET); set(0, id); set(1, created); set(2, modified); set(3, smallUrl); set(4, largeUrl); set(5, courseOverviewId); } }
package com.edasaki.rpg.commands.owner; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import com.edasaki.rpg.PlayerDataRPG; import com.edasaki.rpg.commands.RPGAbstractCommand; import com.edasaki.rpg.quests.QuestManager; public class CompleteQuestCommand extends RPGAbstractCommand { public CompleteQuestCommand(String... commandNames) { super(commandNames); } @Override public void execute(CommandSender sender, String[] args) { } @Override public void executePlayer(final Player p, PlayerDataRPG pd, String[] args) { if (!QuestManager.quests.containsKey(args[0])) { pd.sendMessage("quest with id " + args[0] + " does not exist"); return; } pd.questProgress.put(args[0], 1000); p.sendMessage("Added completed quest: " + args[0]); } @Override public void executeConsole(CommandSender sender, String[] args) { } }
package com.niksoftware.snapseed.util; import android.graphics.Point; import android.graphics.Rect; import android.view.View; import com.niksoftware.snapseed.MainActivity; import com.niksoftware.snapseed.core.DeviceDefs; import com.niksoftware.snapseed.util.ItemRenderer.Size; import com.niksoftware.snapseed.views.EditingToolBar; import com.niksoftware.snapseed.views.GlobalToolBar; import com.niksoftware.snapseed.views.RootView; import java.util.HashMap; import java.util.Map; public class ItemBoundsCalculator { private static final String ANCHOR_APPLYBUTTON = "APPLYBUTTON"; private static final String ANCHOR_BACKBUTTON = "BACKBUTTON"; private static final String ANCHOR_CAMERABUTTON = "CAMERABUTTON"; private static final String ANCHOR_FILTERBUTTON_LEFT = "FILTERBUTTONLEFT"; private static final String ANCHOR_FILTERBUTTON_RIGHT = "FILTERBUTTONRIGHT"; private static final String ANCHOR_FILTERLIST = "FILTERLIST"; private static final String ANCHOR_LIBRARYBUTTON = "LIBRARYBUTTON"; private static final String ANCHOR_MENUBUTTON = "MENUBUTTON"; private static final String ANCHOR_REVERTBUTTON = "REVERTBUTTON"; private static final String ANCHOR_SAVEBUTTON = "SAVEBUTTON"; private static final String ANCHOR_SCREEN = "SCREEN"; private static final String ANCHOR_SHAREBUTTON = "SHAREBUTTON"; private static final Rect EMPTY_RECT = new Rect(); private final Map<String, Rect> anchorMap = new HashMap(); public Rect getItemRect(String nodeName, AttributeMap attributeMap) { Point anchorPoint = findAnchorPoint(findAnchorRect(attributeMap.getAttributeValue("anchor")), attributeMap.getAttributeValue("anchoralign")); Size itemSize = ItemRenderer.itemSize(nodeName, attributeMap); Point itemPoint = addSpacing(attributeMap, findItemBasePoint(anchorPoint, attributeMap.getAttributeValue("align"), itemSize)); Rect itemRect = trimRect(new Rect(itemPoint.x, itemPoint.y, itemPoint.x + itemSize.width, itemPoint.y + itemSize.height)); String namedItem = attributeMap.getAttributeValue("name"); if (namedItem != null) { this.anchorMap.put(namedItem, itemRect); } return itemRect; } private static Rect findGlobalAnchor(String anchorName) { if (anchorName.equalsIgnoreCase(ANCHOR_APPLYBUTTON)) { return findApplyButton(); } if (anchorName.equalsIgnoreCase(ANCHOR_BACKBUTTON)) { return findBackButton(); } if (anchorName.equalsIgnoreCase(ANCHOR_FILTERBUTTON_LEFT)) { return findFilterButtonLeft(); } if (anchorName.equalsIgnoreCase(ANCHOR_FILTERBUTTON_RIGHT)) { return findFilterButtonRight(); } if (anchorName.equalsIgnoreCase(ANCHOR_FILTERLIST)) { return findFilterList(); } if (anchorName.equalsIgnoreCase(ANCHOR_LIBRARYBUTTON)) { return findLibraryList(); } if (anchorName.equalsIgnoreCase(ANCHOR_CAMERABUTTON)) { return findCameraButton(); } if (anchorName.equalsIgnoreCase(ANCHOR_MENUBUTTON)) { return findMenuButton(); } if (anchorName.equalsIgnoreCase(ANCHOR_SHAREBUTTON)) { return findShareButton(); } if (anchorName.equalsIgnoreCase(ANCHOR_SAVEBUTTON)) { return findSaveButton(); } if (anchorName.equalsIgnoreCase(ANCHOR_REVERTBUTTON)) { return findRevertButton(); } if (!anchorName.equalsIgnoreCase(ANCHOR_SCREEN)) { return EMPTY_RECT; } MainActivity.getMainActivity(); RootView rootView = MainActivity.getRootView(); return new Rect(0, 0, rootView.getWidth(), rootView.getHeight()); } private static Rect findFilterList() { MainActivity.getMainActivity(); RootView rootView = MainActivity.getRootView(); return rootView == null ? EMPTY_RECT : calcAnchorBounds(rootView.getFilterList()); } private static Rect findLibraryList() { return EMPTY_RECT; } private static Rect findCameraButton() { return EMPTY_RECT; } private static Rect findMenuButton() { MainActivity.getMainActivity(); RootView rootView = MainActivity.getRootView(); return rootView == null ? EMPTY_RECT : new Rect(rootView.getWidth() - 50, 0, rootView.getWidth(), MainActivity.getMainActivity().getActionBar().getHeight()); } private static Rect findShareButton() { MainActivity.getMainActivity(); RootView rootView = MainActivity.getRootView(); GlobalToolBar globalToolBar = rootView == null ? null : rootView.getGlobalToolBar(); return globalToolBar == null ? EMPTY_RECT : calcAnchorBounds(globalToolBar.getShareButton()); } private static Rect findSaveButton() { MainActivity.getMainActivity(); RootView rootView = MainActivity.getRootView(); GlobalToolBar globalToolBar = rootView == null ? null : rootView.getGlobalToolBar(); return globalToolBar == null ? EMPTY_RECT : calcAnchorBounds(globalToolBar.getSaveButton()); } private static Rect findRevertButton() { MainActivity.getMainActivity(); RootView rootView = MainActivity.getRootView(); GlobalToolBar globalToolBar = rootView == null ? null : rootView.getGlobalToolBar(); return globalToolBar == null ? EMPTY_RECT : calcAnchorBounds(globalToolBar.getRevertButton()); } private static Rect findApplyButton() { MainActivity.getMainActivity(); EditingToolBar editingToolBar = MainActivity.getEditingToolbar(); return editingToolBar == null ? EMPTY_RECT : calcAnchorBounds(editingToolBar.getApplyButton()); } private static Rect findFilterButtonLeft() { MainActivity.getMainActivity(); EditingToolBar editingToolBar = MainActivity.getEditingToolbar(); return editingToolBar == null ? EMPTY_RECT : calcAnchorBounds(editingToolBar.getFilterButtonLeft()); } private static Rect findFilterButtonRight() { MainActivity.getMainActivity(); EditingToolBar editingToolBar = MainActivity.getEditingToolbar(); return editingToolBar == null ? EMPTY_RECT : calcAnchorBounds(editingToolBar.getFilterButtonRight()); } private static Rect findBackButton() { MainActivity.getMainActivity(); EditingToolBar editingToolBar = MainActivity.getEditingToolbar(); return editingToolBar == null ? EMPTY_RECT : calcAnchorBounds(editingToolBar.getBackButton()); } private static Point findAnchorPoint(Rect r, String anchor) { if (anchor == null) { return new Point(r.left, r.top); } if (!anchor.endsWith("°")) { return pointOfInterestInRect(r, anchor); } int angle = 360 - Integer.parseInt(anchor.substring(0, anchor.length() - 1)); MainActivity.getMainActivity(); RootView rootView = MainActivity.getRootView(); float rayLength = (float) (rootView.getWidth() + rootView.getHeight()); Point midPoint = new Point(r.centerX(), r.centerY()); Point rotPoint = new Point(((int) (((double) rayLength) * Math.cos(Math.toRadians((double) angle)))) + midPoint.x, ((int) (((double) rayLength) * Math.sin(Math.toRadians((double) angle)))) + midPoint.y); Point intersection1; if (isInInterval(270, 360, angle)) { intersection1 = getIntersectionPoint(new Point(r.right, r.top), new Point(r.right, r.bottom), midPoint, rotPoint); if (isInInterval(r.top, r.bottom, intersection1.y)) { return intersection1; } return getIntersectionPoint(new Point(r.left, r.top), new Point(r.right, r.top), midPoint, rotPoint); } else if (isInInterval(180, 270, angle)) { intersection1 = getIntersectionPoint(new Point(r.left, r.top), new Point(r.right, r.top), midPoint, rotPoint); if (isInInterval(r.left, r.right, intersection1.x)) { return intersection1; } return getIntersectionPoint(new Point(r.left, r.top), new Point(r.left, r.bottom), midPoint, rotPoint); } else if (isInInterval(90, 180, angle)) { intersection1 = getIntersectionPoint(new Point(r.left, r.top), new Point(r.left, r.bottom), midPoint, rotPoint); if (isInInterval(r.top, r.bottom, intersection1.y)) { return intersection1; } return getIntersectionPoint(new Point(r.left, r.bottom), new Point(r.right, r.bottom), midPoint, rotPoint); } else { intersection1 = getIntersectionPoint(new Point(r.left, r.bottom), new Point(r.right, r.bottom), midPoint, rotPoint); return !isInInterval(r.left, r.right, intersection1.x) ? getIntersectionPoint(new Point(r.right, r.top), new Point(r.right, r.bottom), midPoint, rotPoint) : intersection1; } } public static Point pointOfInterestInRect(Rect rect, String anchor) { if (anchor == null) { return new Point(rect.centerX(), rect.centerY()); } if (anchor.equalsIgnoreCase("CENTER_CENTER")) { return new Point(rect.centerX(), rect.centerY()); } if (anchor.equalsIgnoreCase("CENTER_LEFT")) { return new Point(rect.left, rect.centerY()); } if (anchor.equalsIgnoreCase("CENTER_RIGHT")) { return new Point(rect.right, rect.centerY()); } if (anchor.equalsIgnoreCase("TOP_CENTER")) { return new Point(rect.centerX(), rect.top); } if (anchor.equalsIgnoreCase("TOP_LEFT")) { return new Point(rect.left, rect.top); } if (anchor.equalsIgnoreCase("TOP_RIGHT")) { return new Point(rect.right, rect.top); } if (anchor.equalsIgnoreCase("BOTTOM_CENTER")) { return new Point(rect.centerX(), rect.bottom); } if (anchor.equalsIgnoreCase("BOTTOM_LEFT")) { return new Point(rect.left, rect.bottom); } if (anchor.equalsIgnoreCase("BOTTOM_RIGHT")) { return new Point(rect.right, rect.bottom); } return new Point(rect.centerX(), rect.centerY()); } private static Point findItemBasePoint(Point point, String anchor, Size size) { if (anchor == null) { return new Point(point.x, point.y); } if (anchor.equalsIgnoreCase("CENTER_CENTER")) { return new Point(point.x - (size.width / 2), point.y - (size.height / 2)); } if (anchor.equalsIgnoreCase("CENTER_LEFT")) { return new Point(point.x, point.y - (size.height / 2)); } if (anchor.equalsIgnoreCase("CENTER_RIGHT")) { return new Point(point.x - size.width, point.y - (size.height / 2)); } if (anchor.equalsIgnoreCase("TOP_CENTER")) { return new Point(point.x - (size.width / 2), point.y); } if (anchor.equalsIgnoreCase("TOP_LEFT")) { return new Point(point.x, point.y); } if (anchor.equalsIgnoreCase("TOP_RIGHT")) { return new Point(point.x - size.width, point.y); } if (anchor.equalsIgnoreCase("BOTTOM_CENTER")) { return new Point(point.x - (size.width / 2), point.y - size.height); } if (anchor.equalsIgnoreCase("BOTTOM_LEFT")) { return new Point(point.x, point.y - size.height); } if (anchor.equalsIgnoreCase("BOTTOM_RIGHT")) { return new Point(point.x - size.width, point.y - size.height); } return new Point(point.x, point.y); } private Rect findAnchorRect(String anchor) { if (anchor == null) { return EMPTY_RECT; } return this.anchorMap.containsKey(anchor) ? (Rect) this.anchorMap.get(anchor) : findGlobalAnchor(anchor); } private static boolean isInInterval(int low, int high, int value) { return low <= value && value <= high; } private static Point getIntersectionPoint(Point point1, Point point2, Point point3, Point point4) { float d = (float) (((point1.x - point2.x) * (point3.y - point4.y)) - ((point1.y - point2.y) * (point3.x - point4.x))); float pre = (float) ((point1.x * point2.y) - (point1.y * point2.x)); float post = (float) ((point3.x * point4.y) - (point3.y * point4.x)); return new Point((int) (((((float) (point3.x - point4.x)) * pre) - (((float) (point1.x - point2.x)) * post)) / d), (int) (((((float) (point3.y - point4.y)) * pre) - (((float) (point1.y - point2.y)) * post)) / d)); } private static Rect calcAnchorBounds(View view) { if (view == null) { return EMPTY_RECT; } Rect rect = new Rect(); view.getGlobalVisibleRect(rect); return rect; } private static Rect trimRect(Rect toTrim) { MainActivity.getMainActivity(); View rootView = MainActivity.getRootView(); int width = rootView.getWidth(); int height = rootView.getHeight(); Rect result = new Rect(toTrim.left, toTrim.top, toTrim.right, toTrim.bottom); if (result.left < 0) { result.offset(-result.left, 0); } if (result.top < 0) { result.offset(0, -result.top); } if (result.right > width) { result.offset(width - result.right, 0); } if (result.bottom > height) { result.offset(0, height - result.bottom); } return result; } private static Point addSpacing(AttributeMap attributeMap, Point point) { String spacing = attributeMap.getAttributeValue("spacing"); if (spacing == null) { return point; } String[] values = spacing.split(","); if (values.length != 2) { return point; } int offX = Integer.parseInt(values[0].trim()); int offY = Integer.parseInt(values[1].trim()); float multiplier = DeviceDefs.getScreenDensityRatio(); return new Point(point.x + ((int) (((float) offX) * multiplier)), point.y + ((int) (((float) offY) * multiplier))); } }
package A002_GameOfLife; public class Cell { public int x; public int y; public boolean alive = false; public Cell(int x, int y) { this.x=x; this.y=y; } public void create(){ this.alive=true; } public void kill(){ this.alive=false; } }
package com.group.etoko.Fragment.OrderHistory.repository; import com.group.etoko.BuildConfig; import com.group.etoko.Network.Api; import com.group.etoko.Network.RetrofitClient; import com.group.etoko.Fragment.OrderHistory.model.OrderContainer; import com.group.etoko.Fragment.OrderHistory.viewmodel.OrderHistoryViewModel; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class OrderHistoryRepository { Api api; public OrderHistoryViewModel viewModel; public OrderHistoryRepository(){ api = RetrofitClient.get().create(Api .class); } public void getOrderlist(String customerId){ api.getCustomerOrderHistory(BuildConfig.APP_API,customerId).enqueue(new Callback<OrderContainer>() { @Override public void onResponse(Call<OrderContainer> call, Response<OrderContainer> response) { if(response.isSuccessful()){ viewModel.setOrderlist(response.body().getData()); } else{ viewModel.setOrderlist(null); } } @Override public void onFailure(Call<OrderContainer> call, Throwable t) { viewModel.setOrderlist(null); } }); } }
package com.example.test; import com.baidu.location.BDLocation; import com.baidu.location.BDLocationListener; import com.baidu.location.LocationClient; import com.baidu.location.LocationClientOption; import android.app.Activity; import android.app.Service; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.os.Vibrator; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup.LayoutParams; import android.view.Window; import android.view.WindowManager; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends Activity implements OnClickListener { private WindowManager manager; private WindowManager.LayoutParams p; private LocationClient mLocationClient; private TextView text; @Override protected void onCreate(Bundle savedInstanceState) { mLocationClient = new LocationClient(this.getApplicationContext()); Vibrator mVibrator = (Vibrator) getApplicationContext() .getSystemService(Service.VIBRATOR_SERVICE); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.button).setOnClickListener(this); text = (TextView) findViewById(R.id.textview); manager = (WindowManager) getSystemService(Context.WINDOW_SERVICE); p = new WindowManager.LayoutParams(); p.height = LayoutParams.WRAP_CONTENT; p.width = LayoutParams.MATCH_PARENT; mLocationClient.registerLocationListener(new BDLocationListener() { @Override public void onReceiveLocation(BDLocation location) { StringBuffer sb = new StringBuffer(256); sb.append("您在:" + location.getLocationDescribe()).append( "更新时间:" + location.getTime()); text.setText(sb); } }); } private void initLocation() { // 4 客户端定位参数 LocationClientOption option = new LocationClientOption(); // option.setLocationMode(tempMode);// 可选,默认高精度,设置定位模式,高精度,低功耗,仅设备 option.setIsNeedAddress(true);// 可选,设置是否需要地址信息,默认不需要 option.setOpenGps(true);// 可选,默认false,设置是否使用gps option.setLocationNotify(true);// 可选,默认false,设置是否当gps有效时按照1S1次频率输出GPS结果 option.setIgnoreKillProcess(true);// 可选,默认true,定位SDK内部是一个SERVICE,并放到了独立进程,设置是否在stop的时候杀死这个进程,默认不杀死 option.setEnableSimulateGps(true);// 可选,默认false,设置是否需要过滤gps仿真结果,默认需要 option.setIsNeedLocationDescribe(true);// 可选,默认false,设置是否需要位置语义化结果,可以在BDLocation.getLocationDescribe里得到,结果类似于“在北京天安门附近” option.setIsNeedLocationPoiList(true);// 可选,默认false,设置是否需要POI结果,可以在BDLocation.getPoiList里得到 mLocationClient.setLocOption(option); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.button: initLocation(); mLocationClient.start(); break; default: break; } } }
/* * 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 Forms; import InternalForms.OrderList; import Model.CompletedOrder; import Model.Order; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.event.WindowEvent; import java.awt.print.PageFormat; import java.awt.print.Printable; import java.awt.print.PrinterException; import java.awt.print.PrinterJob; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; /** * * @author HermanCosta */ public class OrderReceipt extends javax.swing.JFrame { Order order; CompletedOrder completedOrder; double deposit, due, total; String formatContactNo; public OrderReceipt() { initComponents(); } public OrderReceipt(Order _order, CompletedOrder _completedOrder, String _formatContactNo) { initComponents(); setResizable(false); this.order = _order; this.completedOrder = _completedOrder; this.formatContactNo = _formatContactNo; loadOrderToPrint(); } public void loadOrderToPrint() { lbl_print_order_no.setText("Order: " + order.getOrderNo()); lbl_print_first_name.setText("Customer name: " + order.getFirstName() + " " + order.getLastName()); lbl_print_contact.setText("Contact no.: " + formatContactNo); lbl_print_email.setText("Email: " + order.getEmail()); lbl_print_brand.setText("Device brand: " + order.getBrand()); lbl_print_model.setText("Device model: " + order.getModel()); lbl_print_sn.setText("S/N: " + order.getSerialNumber()); lbl_print_total_products.setText("Total: €" + String.valueOf(order.getTotal())); lbl_date.setText("Date: " + completedOrder.getPayDate()); lbl_change.setText("Change: €" + completedOrder.getChangeTotal()); if (completedOrder.getCash() == 0 && completedOrder.getCashDeposit() == 0) lbl_paid_by.setText("Paid by Card: €" + (completedOrder.getCard() + completedOrder.getCardDeposit())); else if (completedOrder.getCard() == 0 && completedOrder.getCardDeposit() == 0) lbl_paid_by.setText("Paid by Cash: €" + (completedOrder.getCash() + completedOrder.getCashDeposit())); else lbl_paid_by.setText("Paid by Cash: €" + (completedOrder.getCash() + completedOrder.getCashDeposit()) + " | Card: €" + (completedOrder.getCard() + completedOrder.getCardDeposit())); String[] arrayProducts = order.getStringProducts().split(","); String[] arrayQty = order.getStringQty().split(","); String[] arrayUnitPrice = order.getUnitPrice().split(","); String[] arrayPriceTotal = order.getPriceTotal().split(","); for (String s : arrayProducts) txt_pane_products.setText(txt_pane_products.getText() + " - " + s + " \n"); for (String s : arrayQty) txt_pane_qty.setText(txt_pane_qty.getText() + s + "\n"); for (String s : arrayUnitPrice) txt_pane_unit_price.setText(txt_pane_unit_price.getText() + "€" + s + "\n"); for (String s : arrayPriceTotal) txt_pane_total.setText(txt_pane_total.getText() + "€" + s + "\n"); } @Override protected void processWindowEvent(WindowEvent e) { super.processWindowEvent(e); if (e.getID() == WindowEvent.WINDOW_CLOSING) { OrderList orderList = new OrderList(); MainMenu.mainMenuDesktopPane.removeAll(); MainMenu.mainMenuDesktopPane.add(orderList).setVisible(true); } } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { panel_print_order = new javax.swing.JPanel(); lbl_print_order_no = new javax.swing.JLabel(); lbl_print_first_name = new javax.swing.JLabel(); lbl_print_contact = new javax.swing.JLabel(); lbl_print_email = new javax.swing.JLabel(); lbl_print_brand = new javax.swing.JLabel(); lbl_print_model = new javax.swing.JLabel(); lbl_print_sn = new javax.swing.JLabel(); lbl_print_total_products = new javax.swing.JLabel(); lbl_receipt = new javax.swing.JLabel(); lbl_paid_by = new javax.swing.JLabel(); lbl_date = new javax.swing.JLabel(); panel_header = new javax.swing.JPanel(); lbl_logo_icon1 = new javax.swing.JLabel(); lbl_land_line_number1 = new javax.swing.JLabel(); lbl_mobile_number1 = new javax.swing.JLabel(); line_header = new javax.swing.JSeparator(); lbl_address1 = new javax.swing.JLabel(); panel_products = new javax.swing.JPanel(); lbl_product_service = new javax.swing.JLabel(); lbl_unit_price = new javax.swing.JLabel(); jScrollPane12 = new javax.swing.JScrollPane(); txt_pane_unit_price = new javax.swing.JTextPane(); lbl_qty = new javax.swing.JLabel(); lbl_total = new javax.swing.JLabel(); jScrollPane11 = new javax.swing.JScrollPane(); txt_pane_qty = new javax.swing.JTextPane(); jScrollPane8 = new javax.swing.JScrollPane(); txt_pane_products = new javax.swing.JTextPane(); jScrollPane10 = new javax.swing.JScrollPane(); txt_pane_total = new javax.swing.JTextPane(); lbl_change = new javax.swing.JLabel(); btn_print = new javax.swing.JButton(); jPanel2 = new javax.swing.JPanel(); lbl_order_print_view1 = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); panel_print_order.setBackground(new java.awt.Color(255, 255, 255)); panel_print_order.setPreferredSize(new java.awt.Dimension(595, 842)); lbl_print_order_no.setFont(new java.awt.Font("Lucida Grande", 1, 16)); // NOI18N lbl_print_order_no.setText("orderNo"); lbl_print_first_name.setText("fullName"); lbl_print_contact.setText("contactNo"); lbl_print_email.setText("emailAddress"); lbl_print_brand.setText("deviceBrand"); lbl_print_model.setText("deviceModel"); lbl_print_sn.setText("serialNumber"); lbl_print_total_products.setFont(new java.awt.Font("Lucida Grande", 1, 14)); // NOI18N lbl_print_total_products.setText("totalProducts"); lbl_receipt.setFont(new java.awt.Font("Lucida Grande", 1, 18)); // NOI18N lbl_receipt.setText("Payment Receipt"); lbl_paid_by.setFont(new java.awt.Font("Lucida Grande", 0, 11)); // NOI18N lbl_paid_by.setText("paidBy"); lbl_date.setFont(new java.awt.Font("Lucida Grande", 0, 11)); // NOI18N lbl_date.setText("date"); panel_header.setBackground(new java.awt.Color(255, 255, 255)); lbl_logo_icon1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Img/logo_header.png"))); // NOI18N lbl_land_line_number1.setFont(new java.awt.Font("Lucida Grande", 0, 12)); // NOI18N lbl_land_line_number1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Img/icon_phone_number.png"))); // NOI18N lbl_land_line_number1.setText("+353 (01) 563-9520"); lbl_mobile_number1.setFont(new java.awt.Font("Lucida Grande", 0, 12)); // NOI18N lbl_mobile_number1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Img/icon_mobile_number.png"))); // NOI18N lbl_mobile_number1.setText("+353 (83) 012-8190"); lbl_address1.setFont(new java.awt.Font("Lucida Grande", 0, 12)); // NOI18N lbl_address1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Img/icon_address.png"))); // NOI18N lbl_address1.setText("12A, Frederick Street North, Dublin 1"); javax.swing.GroupLayout panel_headerLayout = new javax.swing.GroupLayout(panel_header); panel_header.setLayout(panel_headerLayout); panel_headerLayout.setHorizontalGroup( panel_headerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panel_headerLayout.createSequentialGroup() .addGap(0, 0, 0) .addGroup(panel_headerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panel_headerLayout.createSequentialGroup() .addComponent(lbl_logo_icon1, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 20, Short.MAX_VALUE) .addGroup(panel_headerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lbl_land_line_number1, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(lbl_mobile_number1, javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(lbl_address1, javax.swing.GroupLayout.Alignment.TRAILING))) .addComponent(line_header, javax.swing.GroupLayout.PREFERRED_SIZE, 552, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); panel_headerLayout.setVerticalGroup( panel_headerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panel_headerLayout.createSequentialGroup() .addContainerGap(12, Short.MAX_VALUE) .addGroup(panel_headerLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lbl_logo_icon1, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(panel_headerLayout.createSequentialGroup() .addGap(12, 12, 12) .addComponent(lbl_land_line_number1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(lbl_mobile_number1) .addGap(0, 0, 0) .addComponent(lbl_address1))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(line_header, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) ); panel_products.setBackground(new java.awt.Color(255, 255, 255)); lbl_product_service.setFont(new java.awt.Font("Lucida Grande", 1, 14)); // NOI18N lbl_product_service.setText("Product | Service"); lbl_unit_price.setFont(new java.awt.Font("Lucida Grande", 1, 14)); // NOI18N lbl_unit_price.setText("Unit €"); jScrollPane12.setBorder(null); jScrollPane12.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); jScrollPane12.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER); jScrollPane12.setDoubleBuffered(true); jScrollPane12.setEnabled(false); txt_pane_unit_price.setEditable(false); txt_pane_unit_price.setBorder(null); txt_pane_unit_price.setFont(new java.awt.Font("Lucida Grande", 0, 12)); // NOI18N txt_pane_unit_price.setFocusable(false); txt_pane_unit_price.setOpaque(false); jScrollPane12.setViewportView(txt_pane_unit_price); lbl_qty.setFont(new java.awt.Font("Lucida Grande", 1, 14)); // NOI18N lbl_qty.setText("Qty"); lbl_total.setFont(new java.awt.Font("Lucida Grande", 1, 14)); // NOI18N lbl_total.setText("Total €"); jScrollPane11.setBorder(null); jScrollPane11.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); jScrollPane11.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER); jScrollPane11.setDoubleBuffered(true); jScrollPane11.setEnabled(false); txt_pane_qty.setEditable(false); txt_pane_qty.setBorder(null); txt_pane_qty.setFont(new java.awt.Font("Lucida Grande", 0, 12)); // NOI18N txt_pane_qty.setFocusable(false); txt_pane_qty.setOpaque(false); jScrollPane11.setViewportView(txt_pane_qty); jScrollPane8.setBorder(null); jScrollPane8.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); jScrollPane8.setToolTipText(""); jScrollPane8.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER); jScrollPane8.setDoubleBuffered(true); jScrollPane8.setEnabled(false); txt_pane_products.setEditable(false); txt_pane_products.setBorder(null); txt_pane_products.setFont(new java.awt.Font("Lucida Grande", 0, 12)); // NOI18N txt_pane_products.setFocusable(false); txt_pane_products.setOpaque(false); jScrollPane8.setViewportView(txt_pane_products); jScrollPane10.setBorder(null); jScrollPane10.setHorizontalScrollBarPolicy(javax.swing.ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); jScrollPane10.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_NEVER); jScrollPane10.setDoubleBuffered(true); jScrollPane10.setEnabled(false); txt_pane_total.setEditable(false); txt_pane_total.setBorder(null); txt_pane_total.setFont(new java.awt.Font("Lucida Grande", 0, 12)); // NOI18N txt_pane_total.setFocusable(false); txt_pane_total.setOpaque(false); jScrollPane10.setViewportView(txt_pane_total); javax.swing.GroupLayout panel_productsLayout = new javax.swing.GroupLayout(panel_products); panel_products.setLayout(panel_productsLayout); panel_productsLayout.setHorizontalGroup( panel_productsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panel_productsLayout.createSequentialGroup() .addGap(0, 0, 0) .addGroup(panel_productsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lbl_product_service) .addComponent(jScrollPane8, javax.swing.GroupLayout.PREFERRED_SIZE, 336, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(0, 0, 0) .addGroup(panel_productsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lbl_qty) .addComponent(jScrollPane11, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(panel_productsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane12, javax.swing.GroupLayout.PREFERRED_SIZE, 78, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(lbl_unit_price)) .addGroup(panel_productsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panel_productsLayout.createSequentialGroup() .addComponent(lbl_total) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jScrollPane10)) .addGap(6, 6, 6)) ); panel_productsLayout.setVerticalGroup( panel_productsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panel_productsLayout.createSequentialGroup() .addContainerGap() .addGroup(panel_productsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(lbl_product_service) .addComponent(lbl_qty) .addComponent(lbl_unit_price) .addComponent(lbl_total)) .addGap(4, 4, 4) .addGroup(panel_productsLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jScrollPane11) .addComponent(jScrollPane10) .addGroup(panel_productsLayout.createSequentialGroup() .addComponent(jScrollPane12, javax.swing.GroupLayout.PREFERRED_SIZE, 114, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(0, 0, Short.MAX_VALUE)) .addComponent(jScrollPane8)) .addContainerGap()) ); lbl_change.setFont(new java.awt.Font("Lucida Grande", 0, 11)); // NOI18N lbl_change.setText("change"); javax.swing.GroupLayout panel_print_orderLayout = new javax.swing.GroupLayout(panel_print_order); panel_print_order.setLayout(panel_print_orderLayout); panel_print_orderLayout.setHorizontalGroup( panel_print_orderLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panel_print_orderLayout.createSequentialGroup() .addGap(20, 20, 20) .addGroup(panel_print_orderLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(lbl_print_model, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(lbl_print_order_no, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(lbl_print_first_name, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(lbl_print_contact, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(lbl_print_email, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(lbl_print_brand, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(lbl_print_sn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(lbl_print_total_products, javax.swing.GroupLayout.DEFAULT_SIZE, 552, Short.MAX_VALUE) .addComponent(lbl_paid_by, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(lbl_date, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(panel_products, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(lbl_change, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(0, 10, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel_print_orderLayout.createSequentialGroup() .addContainerGap(15, Short.MAX_VALUE) .addGroup(panel_print_orderLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel_print_orderLayout.createSequentialGroup() .addComponent(lbl_receipt) .addGap(217, 217, 217)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel_print_orderLayout.createSequentialGroup() .addComponent(panel_header, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addContainerGap()))) ); panel_print_orderLayout.setVerticalGroup( panel_print_orderLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(panel_print_orderLayout.createSequentialGroup() .addContainerGap() .addComponent(panel_header, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(20, 20, 20) .addComponent(lbl_receipt) .addGap(21, 21, 21) .addComponent(lbl_print_order_no, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(4, 4, 4) .addComponent(lbl_print_first_name, javax.swing.GroupLayout.PREFERRED_SIZE, 16, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(4, 4, 4) .addComponent(lbl_print_contact) .addGap(4, 4, 4) .addComponent(lbl_print_email) .addGap(4, 4, 4) .addComponent(lbl_print_brand) .addGap(4, 4, 4) .addComponent(lbl_print_model) .addGap(4, 4, 4) .addComponent(lbl_print_sn) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(panel_products, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(16, 16, 16) .addComponent(lbl_print_total_products) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(lbl_paid_by) .addGap(3, 3, 3) .addComponent(lbl_change) .addGap(3, 3, 3) .addComponent(lbl_date) .addContainerGap(43, Short.MAX_VALUE)) ); btn_print.setBackground(new java.awt.Color(21, 76, 121)); btn_print.setFont(new java.awt.Font("Lucida Grande", 1, 18)); // NOI18N btn_print.setForeground(new java.awt.Color(255, 255, 255)); btn_print.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Img/icon_print.png"))); // NOI18N btn_print.setText("Print"); btn_print.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { btn_printActionPerformed(evt); } }); jPanel2.setBackground(new java.awt.Color(204, 204, 204)); lbl_order_print_view1.setFont(new java.awt.Font("sansserif", 1, 18)); // NOI18N lbl_order_print_view1.setText("Payment Receipt Print View"); javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2); jPanel2.setLayout(jPanel2Layout); jPanel2Layout.setHorizontalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(lbl_order_print_view1) .addGap(73, 73, 73)) ); jPanel2Layout.setVerticalGroup( jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel2Layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(lbl_order_print_view1) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(22, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(btn_print, javax.swing.GroupLayout.PREFERRED_SIZE, 181, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(panel_print_order, javax.swing.GroupLayout.PREFERRED_SIZE, 589, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(btn_print, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(panel_print_order, javax.swing.GroupLayout.PREFERRED_SIZE, 602, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(20, 20, 20)) ); pack(); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void btn_printActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_printActionPerformed // TODO add your handling code here: PrinterJob printerJob = PrinterJob.getPrinterJob(); printerJob.setJobName("ReceiptOrder" + this.order.getOrderNo()); PageFormat format = printerJob.getPageFormat(null); printerJob.setPrintable(new Printable() { @Override public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException { if (pageIndex > 0) { return Printable.NO_SUCH_PAGE; } Graphics2D graphics2D = (Graphics2D) graphics; panel_print_order.paint(graphics2D); return Printable.PAGE_EXISTS; } }, format); boolean returningResult = printerJob.printDialog(); if (returningResult) { try { printerJob.print(); JOptionPane.showMessageDialog(this, "Receipt: " + order.getOrderNo() + " Printed Successfully", "Payment Receipt", JOptionPane.INFORMATION_MESSAGE); this.dispose(); OrderList orderList = new OrderList(); MainMenu.mainMenuDesktopPane.removeAll(); MainMenu.mainMenuDesktopPane.add(orderList).setVisible(true); } catch (PrinterException ex) { Logger.getLogger(OrderReceipt.class.getName()).log(Level.SEVERE, null, ex); } } }//GEN-LAST:event_btn_printActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btn_print; private javax.swing.JPanel jPanel2; private javax.swing.JScrollPane jScrollPane10; private javax.swing.JScrollPane jScrollPane11; private javax.swing.JScrollPane jScrollPane12; private javax.swing.JScrollPane jScrollPane8; private javax.swing.JLabel lbl_address1; private javax.swing.JLabel lbl_change; private javax.swing.JLabel lbl_date; private javax.swing.JLabel lbl_land_line_number1; private javax.swing.JLabel lbl_logo_icon1; private javax.swing.JLabel lbl_mobile_number1; private javax.swing.JLabel lbl_order_print_view1; private javax.swing.JLabel lbl_paid_by; private javax.swing.JLabel lbl_print_brand; private javax.swing.JLabel lbl_print_contact; private javax.swing.JLabel lbl_print_email; private javax.swing.JLabel lbl_print_first_name; private javax.swing.JLabel lbl_print_model; private javax.swing.JLabel lbl_print_order_no; private javax.swing.JLabel lbl_print_sn; private javax.swing.JLabel lbl_print_total_products; private javax.swing.JLabel lbl_product_service; private javax.swing.JLabel lbl_qty; private javax.swing.JLabel lbl_receipt; private javax.swing.JLabel lbl_total; private javax.swing.JLabel lbl_unit_price; private javax.swing.JSeparator line_header; private javax.swing.JPanel panel_header; private javax.swing.JPanel panel_print_order; private javax.swing.JPanel panel_products; private javax.swing.JTextPane txt_pane_products; private javax.swing.JTextPane txt_pane_qty; private javax.swing.JTextPane txt_pane_total; private javax.swing.JTextPane txt_pane_unit_price; // End of variables declaration//GEN-END:variables }
package com.guillermomadoery.examen.ui.configuracion; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.view.LayoutInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.drawerlayout.widget.DrawerLayout; import androidx.fragment.app.Fragment; import androidx.navigation.Navigation; import com.google.android.material.navigation.NavigationView; import com.guillermomadoery.examen.BaseFragment; import com.guillermomadoery.examen.ui.MainActivity; import com.guillermomadoery.examen.R; import static android.content.Context.MODE_PRIVATE; public class ConfiguracionFragment extends BaseFragment { public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.fragment_tools, container, false); final TextView textView = root.findViewById(R.id.text_tools); return root; } @Override public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); } }
public class Book { String title = ""; String author = ""; int number; int pageCount; Book(String title){ this.title = title; } Book(String title, int pageCount){ this.title = title; this.pageCount = pageCount; } Book(String title, int pageCount, String author){ this.title = title; this.pageCount = pageCount; this.author = author; } Book(String title, int pageCount, String author, int number){ this.title = title; this.pageCount = pageCount; this.author = author; this.number = number; } @Override public String toString() { return "Book{" + "title='" + title + '\'' + ", author='" + author + '\'' + ", number=" + number + ", pageCount=" + pageCount + '}'; } }
package com.ngocdt.tttn.entity; import javax.persistence.*; import lombok.Getter; import lombok.Setter; import java.util.Date; import java.util.HashSet; import java.util.List; import java.util.Set; @Entity @Table(name="Receiption") @Getter @Setter public class Receiption { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column private int receiptionID; @OneToOne @JoinColumn(name="orderForSupplierID",unique = true) private OrderForSupplier orderForSupplier; @Column private Date date=new Date(); @Column private long totalPrice; @ManyToOne(fetch = FetchType.EAGER) @JoinColumn(name = "employeeID", nullable = false) private Employee employee; @OneToMany(fetch = FetchType.LAZY, mappedBy = "receiption") private List<ReceiptionDetail> receiptionDetails; public int getReceiptionID() { return receiptionID; } public void setReceiptionID(int receiptionID) { this.receiptionID = receiptionID; } public OrderForSupplier getOrderForSupplier() { return orderForSupplier; } public void setOrderForSupplier(OrderForSupplier orderForSupplier) { this.orderForSupplier = orderForSupplier; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public long getTotalPrice() { return totalPrice; } public void setTotalPrice(long totalPrice) { this.totalPrice = totalPrice; } public Employee getEmployee() { return employee; } public void setEmployee(Employee employee) { this.employee = employee; } public List<ReceiptionDetail> getReceiptionDetails() { return receiptionDetails; } public void setReceiptionDetails(List<ReceiptionDetail> receiptionDetails) { this.receiptionDetails = receiptionDetails; } }
package ru.job4j.socket; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.net.ServerSocket; import java.net.Socket; public class EchoServer { public static void main(String[] args) throws IOException { try (ServerSocket server = new ServerSocket(9000)) { while (!server.isClosed()) { Socket socket = server.accept(); try (OutputStream out = socket.getOutputStream(); BufferedReader in = new BufferedReader( new InputStreamReader(socket.getInputStream()))) { String str = in.readLine(); if (str.startsWith("GET") && str.contains("stop")) { server.close(); } if (!server.isClosed()) { while (!(str.isEmpty())) { str = in.readLine(); System.out.println(str); } out.write("HTTP/1.1 200 OK\r\n\\".getBytes()); } } } } } }
package com.citibank.ods.persistence.pl.dao; import java.math.BigInteger; import java.util.ArrayList; import com.citibank.ods.entity.pl.TplDocTransferHistEntity; // //©2002-2007 Accenture. All rights reserved. // /** * [Class description] * *@see package com.citibank.ods.persistence.pl.dao; *@version 1.0 *@author gerson.a.rodrigues,Apr 16, 2007 * *<PRE> *<U>Updated by:</U> *<U>Description:</U> *</PRE> */ public interface TplDocTransferHistDAO extends BaseTplDocTransferDAO { public TplDocTransferHistEntity insert( TplDocTransferHistEntity tplDocTransferHistEntity ); public ArrayList findByPK( BigInteger ipDocCode_, BigInteger custNbr_ ); }
package cn.xeblog.xechat.constant; /** * 机器人相关常量 * * @author yanpanyi * @date 2019/4/10 */ public interface RobotConstant { /** * 存储的key */ String key = "robot"; /** * 触发机器人聊天的消息前缀 */ String prefix = "#"; /** * 机器人名称 */ String name = "小小毅"; /** * 机器人头像 */ String avatar = "./images/avatar/robot.jpeg"; /** * 机器人地理位置 */ String address = "火星"; }
package com.gys.sm.fun.demo.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.gys.sm.fun.demo.bean.GysBean; import com.gys.sm.fun.demo.dao.IGysDemoDao; @Service public class GysServiceImpl{ @Autowired private IGysDemoDao dao; public List<GysBean> getGysList(){ return dao.getGysList(); } }
import java.awt.*; import java.awt.event.*; import javax.swing.*; public class SomeShapes extends JFrame implements ActionListener { /** * */ private static final long serialVersionUID = 1L; private JButton button; private JPanel panel; public static void main (String[] args) { SomeShapes frame = new SomeShapes(); frame.setTitle("My first drawing attempt using java"); frame.setSize(500, 400); frame.createGUI(); frame.setVisible(true); } private void createGUI() { setDefaultCloseOperation(EXIT_ON_CLOSE); Container window = getContentPane(); window.setLayout(new FlowLayout() ); panel = new JPanel(); panel.setPreferredSize(new Dimension(400, 300)); panel.setBackground(Color.white); window.add(panel); button = new JButton("Click here"); window.add(button); button.addActionListener(this); } public void actionPerformed(ActionEvent event) { Graphics paper = panel.getGraphics(); paper.drawString("Rectangle", 30,25); paper.drawRect(30, 35, 90, 90); paper.setColor(Color.black); paper.drawString("Oval", 130,30); paper.setColor(Color.black); paper.fillOval(130, 60, 50, 50); paper.setColor(Color.black); paper.drawString("Oval", 230,30); paper.fillOval(230, 60, 30, 50); paper.setColor(Color.cyan); paper.fillRect(30, 100, 90, 70); paper.setColor(Color.black); paper.drawOval(130, 100, 50, 50); paper.setColor(Color.black); paper.drawOval(230, 100, 30, 50); } }
package de.tuberlin.dima.bdapro.solutions.gameoflife; public class Cell { private boolean state; private long row; private long column; public Cell (long i, long j){ this.row = i; this.column = j; this.state = false; } public Cell (long i, long j, boolean state){ this.row = i; this.column = j; this.state = state; } public long getRow(){ return this.row; } public long getColumn(){ return this.column; } public boolean getState(){ return this.state; } public void updateCell(boolean newState){ this.state = newState; } public String toString(){ return "(" + this.row + ", " + this.column + ")"; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Cell cell = (Cell) o; if (state != cell.state) return false; if (row != cell.row) return false; return column == cell.column; } @Override public int hashCode() { int result = (state ? 1 : 0); result = 31 * result + (int) (row ^ (row >>> 32)); result = 31 * result + (int) (column ^ (column >>> 32)); return result; } }
package com.tang.onetomany.action; import java.util.List; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.Test; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.tang.onetomany.dao.OrdersDao; import com.tang.onetomany.model.Customer; import com.tang.onetomany.model.Orders; public class OrdersTest { private static OrdersDao ordersDao; @BeforeClass public static void before(){ ApplicationContext ctx = null; ctx = new ClassPathXmlApplicationContext("applicationContext.xml"); ordersDao = (OrdersDao) ctx.getBean("ordersDao"); } @Test @Ignore public void insertInfo(){ Customer customer = new Customer(); customer.setCId(2); Orders orders = new Orders(); orders.setOId(2); orders.setOCode("222222222"); orders.setCustomer(customer); ordersDao.insertInfo(orders); } @Test public void selectAll(){ Orders orders = new Orders(); orders.setOId(1); List<Orders> oList = ordersDao.selectAll(orders); for(Orders o : oList){ System.out.println(o); } } }
package com.docker.script.i18n; import java.util.Properties; /** * Created by zhanjing on 2017/7/17. */ public class MessageProperties extends Properties { public String getMessage(String key) { return getMessage(key, null, null); } public String getMessage(String key, String[] parameters) { return getMessage(key, parameters, null); } public String getMessage(String key, String[] parameters, String defaultValue) { String value = this.getProperty(key, defaultValue); if (parameters != null && parameters.length > 0) { for (int i = 0; i < parameters.length; i++) { if (value.contains("#{" + i + "}")) value = value.replace("#{" + i + "}", parameters[i]); } } return value; } }
/* * Created on Jul 28, 2015 */ package basics; import javafx.application.Application; import javafx.application.Platform; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.Scene; import javafx.scene.control.Button; import javafx.scene.layout.BorderPane; import javafx.scene.layout.HBox; import javafx.scene.shape.Rectangle; import javafx.stage.Stage; public class ThreadingExample extends Application { @Override public void start(Stage stage) { Rectangle rectangle = new Rectangle(100, 100); Button badButton = new Button("Bad grow"); badButton.setOnAction(event -> { try { Thread.sleep(5000); rectangle.setWidth(rectangle.getWidth() * 1.2); rectangle.setHeight(rectangle.getHeight() * 1.2); } catch (Exception e) { e.printStackTrace(); } }); Button goodButton = new Button("Good shrink"); goodButton.setOnAction(event -> { new Thread(() -> { try { Thread.sleep(5000); Platform.runLater(() -> { rectangle.setWidth(rectangle.getWidth() / 1.2); rectangle.setHeight(rectangle.getHeight() / 1.2); }); } catch (Exception e) { e.printStackTrace(); } }).start(); }); HBox buttons = new HBox(badButton, goodButton); buttons.alignmentProperty().set(Pos.CENTER); buttons.setSpacing(10); buttons.setPadding(new Insets(10)); BorderPane root = new BorderPane(); root.setCenter(rectangle); root.setBottom(buttons); Scene scene = new Scene(root, 500, 500); stage.setScene(scene); stage.show(); } public static void main(String[] args) { Application.launch(args); } }