text
stringlengths
10
2.72M
package com.stark.innerclass; /** * ๅŒฟๅๅ†…้ƒจ็ฑป * ๅณๆ—ถๅฎšไน‰ๅณๆ—ถไฝฟ็”จใ€‚็œไปฃ็ ๅ•Š๏ผ */ public class AnyInnerTest { public static void main(String[] args) { //ๅฎž็ŽฐไธคไธชๅŒฟๅ็ฑป๏ผŒๅˆ†ๅˆซๅฎž็ŽฐๆŽฅๅฃๅ’Œ็ปงๆ‰ฟๆŠฝ่ฑก็ฑปใ€‚ new Thread(new Runnable() { @Override public void run() { new AbstracAny("any") { @Override void say() { System.out.println("my name : " + name); } }.say(); } }).start(); } } abstract class AbstracAny { public String name; public AbstracAny(String name) { this.name = name; } abstract void say(); }
package Algorithms; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Stack; public class KeyPadLetter2Num { static Map<Character, Integer> MAP; static class BSTreeNode{ long value; String s; BSTreeNode left; BSTreeNode right; BSTreeNode(long v, String str){ value = v; s = str; left = null; right = null; } } static class BSTree{ BSTreeNode root; BSTree(){ root = null; } BSTree(BSTreeNode node) { root = node; } public void add(BSTreeNode node){ BSTreeNode tmp = root; if(root==null) root = node; while(tmp != null) { int res = compare(tmp, node); if(res > 0) { // insert to left subtree if(tmp.left == null){ tmp.left = node; break; } else tmp = tmp.left; } else if(res < 0) { // insert to right subtree if(tmp.right == null){ tmp.right = node; return; } else tmp = tmp.right; } else throw new IllegalArgumentException("Same Node in the BSTree!" + node.value + node.s); } } // Reverse Inorder public void viewInDesc(){ Stack<BSTreeNode> stack = new Stack<BSTreeNode>(); if(root == null) return; BSTreeNode node = root; while(true){ if(node == null) { if(!stack.isEmpty()) { node = stack.pop(); System.out.println(node.value + " " + node.s); node = node.left; continue; } else return; } else if(node.right != null) { stack.push(node); node = node.right; } else { System.out.println(node.value + " " + node.s); node = node.left; } } } } public static int compare(BSTreeNode node1, BSTreeNode node2) { if(node1.value > node2.value) return 1; else if(node1.value == node2.value){ return 0 - node1.s.compareTo(node2.s); } else return -1; } public KeyPadLetter2Num(){ MAP = new HashMap<Character, Integer>(); MAP.put('a', 2); MAP.put('b', 2); MAP.put('c', 2); MAP.put('d', 3); MAP.put('e', 3); MAP.put('f', 3); MAP.put('g', 4); MAP.put('h', 4); MAP.put('i', 4); MAP.put('j', 5); MAP.put('k', 5); MAP.put('l', 5); MAP.put('m', 6); MAP.put('n', 6); MAP.put('o', 6); MAP.put('p', 7); MAP.put('q', 7); MAP.put('r', 7); MAP.put('s', 7); MAP.put('t', 8); MAP.put('u', 8); MAP.put('v', 8); MAP.put('w', 9); MAP.put('x', 9); MAP.put('y', 9); MAP.put('z', 9); } public static void keyPadLetter2Num(List<String> l){ BSTree tree = new BSTree(); // Step 1: convert string -> integer for(int i = 0; i < l.size(); i++) { String s = l.get(i); long value = 0; for(int j = 0; j < s.length(); j++){ value = value * 10 + MAP.get(s.charAt(j)); } tree.add(new BSTreeNode(value, s)); } tree.viewInDesc(); } public static void main(String[] args) { // TODO Auto-generated method stub List<String> l = new ArrayList<String>(); l.add("amazon"); l.add("rat"); l.add("pat"); l.add("aa"); l.add("zz"); l.add("zzz"); l.add("pingpingwu"); System.out.println("MAX_VALUE " + Integer.MAX_VALUE); KeyPadLetter2Num kp = new KeyPadLetter2Num(); keyPadLetter2Num(l); } }
/* * 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 jpaModel; import java.io.Serializable; import java.util.Date; import java.util.List; import javax.persistence.Basic; import javax.persistence.CascadeType; 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.Lob; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.OneToMany; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlTransient; /** * * @author Fallou */ @Entity @Table(name = "patient") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Patient.findAll", query = "SELECT p FROM Patient p") , @NamedQuery(name = "Patient.findById", query = "SELECT p FROM Patient p WHERE p.id = :id") , @NamedQuery(name = "Patient.findByAdresse", query = "SELECT p FROM Patient p WHERE p.adresse = :adresse") , @NamedQuery(name = "Patient.findByMail", query = "SELECT p FROM Patient p WHERE p.mail = :mail") , @NamedQuery(name = "Patient.findByMatricule", query = "SELECT p FROM Patient p WHERE p.matricule = :matricule") , @NamedQuery(name = "Patient.findByNaissance", query = "SELECT p FROM Patient p WHERE p.naissance = :naissance") , @NamedQuery(name = "Patient.findByNom", query = "SELECT p FROM Patient p WHERE p.nom = :nom") , @NamedQuery(name = "Patient.findByPrenom", query = "SELECT p FROM Patient p WHERE p.prenom = :prenom") , @NamedQuery(name = "Patient.findByTelephone", query = "SELECT p FROM Patient p WHERE p.telephone = :telephone") , @NamedQuery(name = "Patient.findByIdticket", query = "SELECT p FROM Patient p WHERE p.idticket = :idticket") , @NamedQuery(name = "Patient.findByHosptaliser", query = "SELECT p FROM Patient p WHERE p.hosptaliser = :hosptaliser")}) public class Patient implements Serializable { @Lob @Column(name = "photo") private byte[] photo; @OneToMany(cascade = CascadeType.ALL, mappedBy = "idpatient") private List<Hospitalisation> hospitalisationList; private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "id") private Integer id; @Column(name = "adresse") private String adresse; @Column(name = "mail") private String mail; @Column(name = "matricule") private String matricule; @Column(name = "naissance") @Temporal(TemporalType.DATE) private Date naissance; @Column(name = "nom") private String nom; @Column(name = "prenom") private String prenom; @Column(name = "telephone") private String telephone; @Basic(optional = false) @Column(name = "idticket") private String idticket; @Basic(optional = false) @Column(name = "hosptaliser") private int hosptaliser; @OneToMany(cascade = CascadeType.ALL, mappedBy = "idpatient") private List<Vaccinations> vaccinationsList; @JoinColumn(name = "idsexe", referencedColumnName = "id") @ManyToOne private Sexe idsexe; @OneToMany(cascade = CascadeType.ALL, mappedBy = "idpatient") private List<Consultations> consultationsList; @OneToMany(cascade = CascadeType.ALL, mappedBy = "idpatient") private List<Carnet> carnetList; @OneToMany(cascade = CascadeType.ALL, mappedBy = "idpatient") private List<Ordonnance> ordonnanceList; @OneToMany(cascade = CascadeType.ALL, mappedBy = "idpatient") private List<RendezVous> rendezVousList; @OneToMany(cascade = CascadeType.ALL, mappedBy = "idpatient") private List<Simplevaccination> simplevaccinationList; public Patient() { } public Patient(Integer id) { this.id = id; } public Patient(Integer id, String idticket, int hosptaliser) { this.id = id; this.idticket = idticket; this.hosptaliser = hosptaliser; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getAdresse() { return adresse; } public void setAdresse(String adresse) { this.adresse = adresse; } public String getMail() { return mail; } public void setMail(String mail) { this.mail = mail; } public String getMatricule() { return matricule; } public void setMatricule(String matricule) { this.matricule = matricule; } public Date getNaissance() { return naissance; } public void setNaissance(Date naissance) { this.naissance = naissance; } public String getNom() { return nom; } public void setNom(String nom) { this.nom = nom; } public String getPrenom() { return prenom; } public void setPrenom(String prenom) { this.prenom = prenom; } public String getTelephone() { return telephone; } public void setTelephone(String telephone) { this.telephone = telephone; } public String getIdticket() { return idticket; } public void setIdticket(String idticket) { this.idticket = idticket; } public int getHosptaliser() { return hosptaliser; } public void setHosptaliser(int hosptaliser) { this.hosptaliser = hosptaliser; } @XmlTransient public List<Vaccinations> getVaccinationsList() { return vaccinationsList; } public void setVaccinationsList(List<Vaccinations> vaccinationsList) { this.vaccinationsList = vaccinationsList; } public Sexe getIdsexe() { return idsexe; } public void setIdsexe(Sexe idsexe) { this.idsexe = idsexe; } @XmlTransient public List<Consultations> getConsultationsList() { return consultationsList; } public void setConsultationsList(List<Consultations> consultationsList) { this.consultationsList = consultationsList; } @XmlTransient public List<Carnet> getCarnetList() { return carnetList; } public void setCarnetList(List<Carnet> carnetList) { this.carnetList = carnetList; } @XmlTransient public List<Ordonnance> getOrdonnanceList() { return ordonnanceList; } public void setOrdonnanceList(List<Ordonnance> ordonnanceList) { this.ordonnanceList = ordonnanceList; } @XmlTransient public List<RendezVous> getRendezVousList() { return rendezVousList; } public void setRendezVousList(List<RendezVous> rendezVousList) { this.rendezVousList = rendezVousList; } @XmlTransient public List<Simplevaccination> getSimplevaccinationList() { return simplevaccinationList; } public void setSimplevaccinationList(List<Simplevaccination> simplevaccinationList) { this.simplevaccinationList = simplevaccinationList; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Patient)) { return false; } Patient other = (Patient) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "jpaModel.Patient[ id=" + id + " ]"; } public byte[] getPhoto() { return photo; } public void setPhoto(byte[] photo) { this.photo = photo; } @XmlTransient public List<Hospitalisation> getHospitalisationList() { return hospitalisationList; } public void setHospitalisationList(List<Hospitalisation> hospitalisationList) { this.hospitalisationList = hospitalisationList; } }
package popcol.service; import java.util.List; import popcol.model.Movie; public interface MovieService { /*์ˆ˜์—ฐ*/ List<Movie> movieChart(); Movie movieDetail(int mid); List<Movie> reviewGoodBadCount(); List<Movie> nowMoviesList(); List<Movie> preMoviesList(); /*๊ทœ๋ž‘*/ List<Movie> adminList(int startRow, int endRow); int getTotal(); int adminInsert(Movie movie); Movie adminSelect(int mid); int adminUpdate(Movie movie); int adminDelete(int mid); List<Movie> movieList(); /* ๋„์€ */ /* ๋ฉ”์ธ */ Movie selectRunningMovieRandom(); /* ๋งˆ์ดํŽ˜์ด์ง€ */ Movie selectMovieForReview(int mid); }
package com.application.udemy; import java.util.Scanner; public class Main { private static Scanner scanner = new Scanner(System.in); public static void main(String[] args) { int[] myIntegers = getIntegers(5); } public static int[] getIntegers(int capacity) { int[] array = new int[capacity]; System.out.println("Enter elements of array"); for (int i = 0; i < array.length; i++) { array[i] = scanner.nextInt(); } return array; } public static void printArray(int[] anArray) { for (int i = 0; i < anArray.length; i++) { System.out.println("Element " + i + " containt " + anArray[i]); } } }
package org.newdawn.slick; import java.io.IOException; import java.io.InputStream; import java.net.URL; import org.newdawn.slick.opengl.Texture; public class SpriteSheet extends Image { private int tw; private int th; private int margin = 0; private Image[][] subImages; private int spacing; private Image target; public SpriteSheet(URL ref, int tw, int th) throws SlickException, IOException { this(new Image(ref.openStream(), ref.toString(), false), tw, th); } public SpriteSheet(Image image, int tw, int th) { super(image); this.target = image; this.tw = tw; this.th = th; initImpl(); } public SpriteSheet(Image image, int tw, int th, int spacing, int margin) { super(image); this.target = image; this.tw = tw; this.th = th; this.spacing = spacing; this.margin = margin; initImpl(); } public SpriteSheet(Image image, int tw, int th, int spacing) { this(image, tw, th, spacing, 0); } public SpriteSheet(String ref, int tw, int th, int spacing) throws SlickException { this(ref, tw, th, (Color)null, spacing); } public SpriteSheet(String ref, int tw, int th) throws SlickException { this(ref, tw, th, (Color)null); } public SpriteSheet(String ref, int tw, int th, Color col) throws SlickException { this(ref, tw, th, col, 0); } public SpriteSheet(String ref, int tw, int th, Color col, int spacing) throws SlickException { super(ref, false, 2, col); this.target = this; this.tw = tw; this.th = th; this.spacing = spacing; } public SpriteSheet(String name, InputStream ref, int tw, int th) throws SlickException { super(ref, name, false); this.target = this; this.tw = tw; this.th = th; } protected void initImpl() { if (this.subImages != null) return; int tilesAcross = (getWidth() - this.margin * 2 - this.tw) / (this.tw + this.spacing) + 1; int tilesDown = (getHeight() - this.margin * 2 - this.th) / (this.th + this.spacing) + 1; if ((getHeight() - this.th) % (this.th + this.spacing) != 0) tilesDown++; this.subImages = new Image[tilesAcross][tilesDown]; for (int x = 0; x < tilesAcross; x++) { for (int y = 0; y < tilesDown; y++) this.subImages[x][y] = getSprite(x, y); } } public Image getSubImage(int x, int y) { init(); if (x < 0 || x >= this.subImages.length) throw new RuntimeException("SubImage out of sheet bounds: " + x + "," + y); if (y < 0 || y >= (this.subImages[0]).length) throw new RuntimeException("SubImage out of sheet bounds: " + x + "," + y); return this.subImages[x][y]; } public Image getSprite(int x, int y) { this.target.init(); initImpl(); if (x < 0 || x >= this.subImages.length) throw new RuntimeException("SubImage out of sheet bounds: " + x + "," + y); if (y < 0 || y >= (this.subImages[0]).length) throw new RuntimeException("SubImage out of sheet bounds: " + x + "," + y); return this.target.getSubImage(x * (this.tw + this.spacing) + this.margin, y * (this.th + this.spacing) + this.margin, this.tw, this.th); } public int getHorizontalCount() { this.target.init(); initImpl(); return this.subImages.length; } public int getVerticalCount() { this.target.init(); initImpl(); return (this.subImages[0]).length; } public void renderInUse(int x, int y, int sx, int sy) { this.subImages[sx][sy].drawEmbedded(x, y, this.tw, this.th); } public void endUse() { if (this.target == this) { super.endUse(); return; } this.target.endUse(); } public void startUse() { if (this.target == this) { super.startUse(); return; } this.target.startUse(); } public void setTexture(Texture texture) { if (this.target == this) { super.setTexture(texture); return; } this.target.setTexture(texture); } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\org\newdawn\slick\SpriteSheet.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package es.jcolladosp.daviscope; import android.annotation.TargetApi; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Configuration; import android.content.res.Resources; import android.media.MediaPlayer; import android.net.Uri; import android.os.Build; import android.support.v7.app.ActionBar; import android.util.Log; import android.view.inputmethod.EditorInfo; import android.widget.TextView; import android.view.KeyEvent; import android.os.Bundle; import android.text.Html; import android.text.method.LinkMovementMethod; import android.util.DisplayMetrics; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.RelativeLayout; import android.widget.TextView; import java.util.ArrayList; import java.util.Locale; import java.util.Random; import es.jcolladosp.daviscope.Util.BaseActivity; import es.jcolladosp.daviscope.Util.Tipografias; public class PreguntaActivity extends BaseActivity implements View.OnClickListener { Button aceptar; EditText edpregunta; RelativeLayout fondo; public String pregunta; AlertDialog levelDialog; MediaPlayer mp; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pregunta); setListeners(); findViews(); generateBackground(); listernerIntro(); TextView explicacion = (TextView) findViewById(R.id.txExplicacion); explicacion.setTypeface(Tipografias.getTypeface(this, "")); mp = MediaPlayer.create(this, R.raw.sonido); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setCustomView(R.layout.actionbar_custom); actionBar.setDisplayShowTitleEnabled(false); actionBar.setDisplayShowCustomEnabled(true); } edpregunta.setOnKeyListener(new View.OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN && event.getKeyCode() == KeyEvent.KEYCODE_ENTER) { Log.i("event", "captured"); preguntaNueva(); return false; } return false; } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.menu_pregunta, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); if (id == R.id.action_settings) { selectLanguage(); return true; } if (id == R.id.ajuda) { Intent send = new Intent(Intent.ACTION_SENDTO); String uriText = "mailto:" + Uri.encode("jousselin.new.antique@gmail.com") + "?subject=" + Uri.encode(getResources().getString(R.string.email) + "Daviscope") + "&body=" + Uri.encode(""); Uri uri = Uri.parse(uriText); send.setData(uri); startActivityForResult(Intent.createChooser(send, getResources().getString(R.string.email)), 1); return true; } if (id == android.R.id.home) { onBackPressed(); return true; } if (id == R.id.develop) { developAlert(); return true; } return super.onOptionsItemSelected(item); } @Override public void onBackPressed() { Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_HOME); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startActivity(intent); } private void setListeners() { aceptar = (Button) findViewById(R.id.btAceptar); aceptar.setTypeface(Tipografias.getTypeface(this, "")); aceptar.setOnClickListener(this); } private void findViews() { edpregunta = (EditText) findViewById(R.id.edPregunta); edpregunta.setTypeface(Tipografias.getTypeface(this, "")); } private void developAlert() { TextView tv = new TextView(this); tv.setMovementMethod(LinkMovementMethod.getInstance()); tv.setText(Html.fromHtml("Idea original: David Jousselin " + "<br />" + "<a href=\"mailto:jousselin.new.antique@gmail.com\">Enviar Email</a>" + "<br />" + "<br />" + "Desarrollo: Jose Collado" + "<br />" + "<a href=\"mailto:jose528@gmail.com\">Enviar Email</a>" + "<br />" + "<a href=https://github.com/jcolladosp>GitHub</a>")); tv.setTextColor(getResources().getColor(R.color.icons)); tv.setTextSize(20); AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AppCompatAlertDialogStyle); builder.setTitle(getResources().getString(R.string.develop)); builder.setView(tv); builder.setPositiveButton("OK", null); builder.show(); } @TargetApi(Build.VERSION_CODES.JELLY_BEAN) private void generateBackground() { fondo = (RelativeLayout) findViewById(R.id.fondoPregunta); ArrayList<Integer> numbers = generateRandomNumbers(1, 4); switch (numbers.get(0)) { case 0: fondo.setBackground(getResources().getDrawable(R.drawable.fondo1)); break; case 1: fondo.setBackground(getResources().getDrawable(R.drawable.fondo2)); break; case 2: fondo.setBackground(getResources().getDrawable(R.drawable.fondo3)); break; case 3: fondo.setBackground(getResources().getDrawable(R.drawable.fondo4)); break; } } public ArrayList generateRandomNumbers(int nnumbers, int maxnumber) { ArrayList<Integer> numbers = new ArrayList<Integer>(); Random randomGenerator = new Random(); while (numbers.size() < nnumbers) { int random = randomGenerator.nextInt(maxnumber); if (!numbers.contains(random)) { numbers.add(random); } } return numbers; } private void selectLanguage() { final CharSequence[] items = {" English ", " Espaรฑol ", " Franรงais "}; // Creating and Building the Dialog AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTitle(getResources().getString(R.string.action_settings)); builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int item) { switch (item) { case 0: setLocale("en"); break; case 1: setLocale("es"); break; case 2: setLocale("fr"); break; } levelDialog.dismiss(); } }); levelDialog = builder.create(); levelDialog.show(); } public void setLocale(String lang) { Locale myLocale = new Locale(lang); Resources res = getResources(); DisplayMetrics dm = res.getDisplayMetrics(); Configuration conf = res.getConfiguration(); conf.locale = myLocale; res.updateConfiguration(conf, dm); Intent refresh = new Intent(this, PreguntaActivity.class); startActivity(refresh); finish(); } public void preguntaNueva() { mp.start(); pregunta = edpregunta.getText().toString(); Intent i = new Intent(getApplicationContext(), ResultadoActivity.class); i.putExtra("pregunta", pregunta); startActivity(i); edpregunta.setText(""); } @Override public void onClick(View v) { if (v.getId() == R.id.btAceptar) { preguntaNueva(); } } public void listernerIntro() { } }
/* * [y] hybris Platform * * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved. * * This software is the confidential and proprietary information of SAP * ("Confidential Information"). You shall not disclose such Confidential * Information and shall use it only in accordance with the terms of the * license agreement you entered into with SAP. */ package de.hybris.platform.commerceservices.model; import de.hybris.platform.commerceservices.model.consent.ConsentModel; import de.hybris.platform.servicelayer.model.attribute.AbstractDynamicAttributeHandler; public class ConsentActiveAttribute extends AbstractDynamicAttributeHandler<Boolean, ConsentModel> { @Override public Boolean get(final ConsentModel model) { if (model == null) { throw new IllegalArgumentException("consent must not be null"); } return Boolean.valueOf(model.getConsentWithdrawnDate() == null); } }
package models; import java.util.ArrayList; import java.util.List; import javax.persistence.Entity; import javax.persistence.OneToOne; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Lob; import javax.persistence.OneToMany; import play.Logger; import play.db.jpa.Model; @Entity public class Comment extends Model { @ManyToOne() public Post post; @ManyToOne() public User user; public String title; @Lob public String contentText; public Long time; //not meant as for storage, more as helper object for ember public boolean isMine; public Comment(Post post, User user, String title, String contentText) { this.post=post; this.user=user; this.title = title; this.contentText = contentText; this.time=System.currentTimeMillis(); } public String toString() { return contentText; } }
package com.hxzy.controller.student; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping(value = "/student/homework") public class StudentHomeWorkController { //ๅทฒๆ‰นๆ”น็š„ไฝœไธš @GetMapping(value = "/check") public String checkHomeWork(Model model){ return "student/yipigai"; } }
import java.util.ArrayList; import java.util.List; public class NaryTreePostorderTraversal { public static List<Integer> postorder(Node root) { List<Integer> res = new ArrayList<>(); return res; } public static void main(String[] args) { Node root = new Node(); List<Integer> res = postorder(root); } }
package com.mypackage.executors; import com.google.gson.Gson; import org.apache.kafka.clients.producer.KafkaProducer; import org.apache.kafka.clients.producer.ProducerRecord; import org.apache.log4j.Logger; import org.apache.spark.api.java.function.ForeachPartitionFunction; import org.apache.spark.api.java.function.VoidFunction; import java.io.Serializable; import java.util.Iterator; import java.util.Properties; //import org.slf4j.Logger; //import org.slf4j.LoggerFactory; //import com.twitter.bijection.Injection; //import com.twitter.bijection.avro.GenericAvroCodecs; public class SendKafkaExecutor<I> implements VoidFunction<Iterator<I>>, Serializable, ForeachPartitionFunction<I> { public SendKafkaExecutor(String targetTopic, String targetKafkaServerPort, boolean shouldUseAVRO, Class<?> inputClass) { this.targetTopic = targetTopic; this.targetKafkaServerPort = targetKafkaServerPort; this.shouldUseAVRO = shouldUseAVRO; this.inputClass = inputClass; } // final static Logger logger = LoggerFactory.getLogger(SendJSON.class); final static Logger logger = Logger.getLogger(SendKafkaExecutor.class); private static final long serialVersionUID = 1L; String targetTopic; String targetKafkaServerPort; boolean shouldUseAVRO; Class<?> inputClass; public String getTargetTopic() { return targetTopic; } public void setTargetTopic(String targetTopic) { this.targetTopic = targetTopic; } public String getTargetKafkaServerPort() { return targetKafkaServerPort; } public void setTargetKafkaServerPort(String targetKafkaServerPort) { this.targetKafkaServerPort = targetKafkaServerPort; } public boolean isShouldUseAVRO() { return shouldUseAVRO; } public void setShouldUseAVRO(boolean shouldUseAVRO) { this.shouldUseAVRO = shouldUseAVRO; } @Override public void call(Iterator<I> iterator) throws Exception { if (logger.isDebugEnabled()) logger.debug("<o> ---> apply Method START - shouldUseAVRO: " + shouldUseAVRO); Properties propsNoAVRO = new Properties(); propsNoAVRO.put("bootstrap.servers", targetKafkaServerPort); propsNoAVRO.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer"); propsNoAVRO.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer"); KafkaProducer<String, String> producerNoAVRO = new KafkaProducer<>(propsNoAVRO); // Gson gson = new Gson(); while (iterator.hasNext()) { I employee = iterator.next(); logger.debug("<o> ---> employee : " + employee.toString()); String json = gson.toJson(employee); logger.debug("<o> ---> employee json: " + employee.toString()); if (shouldUseAVRO) { // TODO To be revised AVRO case // if (logger.isDebugEnabled()) // logger.debug("<o> ---> apply Method, toKafkaRawAVRO will be invoked"); // toKafkaRawAVRO(json,targetTopic,targetKafkaServerPort,producerRawAVRO,recordInjection,avroRecord); } else { toKafkaNoAVRO(json, targetTopic, targetKafkaServerPort, producerNoAVRO); } } // Close producers // producerRawAVRO.close(); producerNoAVRO.close(); if (logger.isDebugEnabled()) logger.debug("<o> ---> apply Method EXIT"); } public void toKafkaNoAVRO(String jsonRowObject, String targetTopic, String targetKafkaServerPort, KafkaProducer<String, String> producerNoAVRO) { if (logger.isDebugEnabled()) logger.debug("<o> START toKafkaNoAVRO"); ProducerRecord<String, String> record = new ProducerRecord<>(targetTopic, jsonRowObject); producerNoAVRO.send(record); if (logger.isDebugEnabled()) logger.debug("<o>============== >> toKafkaNoAVRO: - string: --> " + record.toString()); } }
package com.application.controller; import com.application.exception.ProductNotFoundException; import com.application.exception.ProductShortageException; import com.application.model.product.Product; import com.application.service.CartService; import java.math.BigInteger; import java.util.Map; import java.util.Objects; /** * Controls cart activities */ public class CartController { private final CartService cartService; public CartController(final CartService cartService) { this.cartService = Objects.requireNonNull(cartService, "cartService is NULL!!"); } /** * Fetch complete cart elements * * @return map of products in cart and their counts */ public Map<Product, BigInteger> fetchCartItems() { return cartService.fetchCartItems(); } /** * Adds given product id with number of pieces in cart * * @param productId product to be added * @param count number of pieces to be addes * @throws ProductNotFoundException In case product asked for is not available * @throws ProductShortageException In case quantity asked for is not available */ public void addToCart(final int productId, final int count) throws ProductNotFoundException, ProductShortageException { cartService.add(productId, count); } /** * Removes given product id's number of pieces from cart * * @param productId item id to be removed * @param count number of items to be removed */ public void removeFromCart(final int productId, final int count) { cartService.remove(productId, count); } /** * Removes given product from cart(if available in cart) * * @param productId product if to be removed */ public void removeItem(final int productId) { cartService.removeAll(productId); } }
package prog12ํ™ฉ์ธํ˜ธ; public class SearchComparsion { public static void main(String[] args) { // TODO Auto-generated method stub int key; // ํƒ์ƒ‰ํ•  ์ˆซ์ž int[] randomArray; // ๋‚œ์ˆ˜ ๋ฐฐ์—ด int index; // key๊ฐ€ ๋ฐฐ์—ด์˜ ์–ด๋А ์œ„์น˜์— ์žˆ๋Š”์ง€ ๊ฐ€๋ฆฌํ‚ค๋Š” ๋ณ€์ˆ˜ // ์ด์ง„ ํƒ์ƒ‰ // ๋ฐฐ์—ด์˜ ํฌ๊ธฐ๋ฅผ ์ฆ๊ฐ€์‹œํ‚ค๋ฉด์„œ ํƒ์ƒ‰์— ํ•„์š”ํ•œ ๋ฃจํ”„ ์ˆ˜๋ฅผ ๊ด€์ฐฐํ•จ System.out.println("์ด์ง„ํƒ์ƒ‰ ------------------"); for(int i = 10 ; i < 100000; i *= 10) { System.out.print(i + " ์ดํ•˜ ๋‚œ์ˆ˜" + i + "๊ฐœ๋ฅผ ๋ฐœ์ƒ์‹œ์ผœ ๋ฐฐ์—ด์— ์ €์žฅํ•˜๊ณ  ํƒ์ƒ‰"); System.out.println("(์ค‘๋ณต ํ—ˆ์šฉ)"); // 1 ์ด์ƒ i ์ดํ•˜ ๋‚œ์ˆ˜๋ฅผ i๊ฐœ ๋ฐœ์ƒ์‹œ์ผœ ๋ฐฐ์—ด์— ์ €์žฅ randomArray = new int[i]; for(int j=0; j<i; j++) { randomArray[j] = (int)(i*Math.random()) + 1; } InsertionSort.insertionSort(randomArray, i); // ๋ฐฐ์—ด์„ ์ •๋ ฌ key = (int)(Math.random() * i) + 1; // key๋ฅผ 1 ์ด์ƒ i์ดํ•˜ ๋‚œ์ˆ˜๋กœ ํ•˜๋‚˜ ์ •ํ•จ System.out.println("ํ‚ค : " + key); // key๊ฐ€ ์–ผ๋งˆ์ธ์ง€ ์ถœ๋ ฅ // ๋ฐฐ์—ด์—์„œ key๋ฅผ ํƒ์ƒ‰ index = MonitoredSearch.binarySearch(randomArray, i, key); if(index == -1) { System.out.println("ํ‚ค๊ฐ€ ๋“ค์–ด ์žˆ์ง€ ์•Š์Šต๋‹ˆ๋‹ค."); System.out.println(); } else { System.out.println("ํ‚ค๋Š” " + index + "๋ฒˆ ๋ฐฉ์— ๋“ค์–ด ์žˆ์Šต๋‹ˆ๋‹ค."); System.out.println("๊ทธ ๊ฐ’์€ " + randomArray[index] + "์ž…๋‹ˆ๋‹ค."); System.out.println(); } } // ์„ ํ˜• ํƒ์ƒ‰ // ๋ฐฐ์—ด์˜ ํฌ๊ธฐ๋ฅผ ์ฆ๊ฐ€์‹œํ‚ค๋ฉด์„œ ํƒ์ƒ‰์— ํ•„์š”ํ•œ ๋ฃจํ”„ ์ˆ˜๋ฅผ ๊ด€์ฐฐํ•จ System.out.println("์„ ํ˜•ํƒ์ƒ‰ --------------------"); for( int i = 10 ; i < 100000; i *=10) { System.out.println(i + " ์ดํ•˜ ๋‚œ์ˆ˜ " + i + "๊ฐœ๋ฅผ ๋ฐœ์ƒ์‹œ์ผœ ๋ฐฐ์—ด์— ์ €์žฅํ•˜๊ณ  ํƒ์ƒ‰"); System.out.println("(์ค‘๋ณตํ—ˆ์šฉ)"); // 1์ด์ƒ i์ดํ•˜ ๋‚œ์ˆ˜๋ฅผ i๊ฐœ ๋ฐœ์ƒ์‹œ์ผœ ๋ฐฐ์—ด์— ์ €์žฅ randomArray = new int[i]; for(int j=0; j<i; j++) { randomArray[j] = (int)(i*Math.random()) + 1; } key = (int)(Math.random() * i) + 1; // key๋ฅผ 1์ด์ƒ i์ดํ•˜ ๋‚œ์ˆ˜๋กœ ํ•˜๋‚˜ ์ •ํ•จ System.out.println("ํ‚ค : " + key); // key๊ฐ€ ์–ผ๋งˆ์ธ์ง€ ์ถœ๋ ฅ // ๋ฐฐ์—ด์—์„œ key๋ฅผ ํƒ์ƒ‰ index = MonitoredSearch.linearSearch(randomArray, i, key); if(index == -1) { System.out.println("ํ‚ค๊ฐ€ ๋“ค์–ด ์žˆ์ง€ ์•Š์Šต๋‹ˆ๋‹ค."); System.out.println(); } else { System.out.println("ํ‚ค๋Š”" + index + "๋ฒˆ ๋ฐฉ์— ๋“ฃ์–ด ์žˆ์Šต๋‹ˆ๋‹ค."); System.out.println("๊ทธ ๊ฐ’์€" + randomArray[index] + "์ž…๋‹ˆ๋‹ค."); System.out.println(); } } } }
package com.fireblaze.foodiee.models; import com.fireblaze.foodiee.Constants; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.Exclude; import com.google.firebase.database.FirebaseDatabase; import java.util.HashMap; import java.util.Map; /** * Created by fireblaze on 15/12/16. */ public class BookedEvent { private String eventID; private String userID; private String organizerID; public BookedEvent(String eventID, String userID, String organizerID) { this.eventID = eventID; this.userID = userID; this.organizerID = organizerID; } @Exclude public Map<String,Object> toMap(){ HashMap<String, Object> result = new HashMap<>(); result.put("eventID",eventID); result.put("userID",userID); result.put("organizerID",organizerID); return result; } public BookedEvent(){ //Important } public static String bookEvent(String eventID, String UID, String organizerID){ DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child(Constants.BOOKED_EVENTS); String bookingID = ref.push().getKey(); ref.child(bookingID).setValue(new BookedEvent(eventID, UID, organizerID)); return bookingID; } public static void unBookEvent(String bookingID){ DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child(Constants.BOOKED_EVENTS); ref.child(bookingID).setValue(null); } public String getEventID() { return eventID; } public String getOrganizerID(){ return organizerID; } public String getUserID(){ return userID; } }
package oop02.encapsule; public class RpsService { private RpsVO vo = new RpsVO(); public void setVO(RpsVO vo){ this.vo = vo; } /* * ์ปดํ“จํ„ฐ๊ฐ€ ๋žœ๋ค์œผ๋กœ ๋ฐœ์ƒ์‹œํ‚จ ์ˆ˜ 1 ~ 3๊นŒ์ง€ */ public int displayComVal() { return (int) ((Math.random() * 3) + 1); } /* * ์Šน์ž๋ฅผ ๋ณด์—ฌ์ฃผ๋Š” ๋กœ์ง */ public String showWinner(int playerValue, int comValue) { int result = playerValue - comValue; String msg = ""; switch(result){ case -1: case 2: msg = "์Šน๋ฆฌ์ž๋Š” ์ปดํ“จํ„ฐ์ž…๋‹ˆ๋‹ค."; break; case 1: case -2: msg = "์Šน๋ฆฌ์ž๋Š” ์‚ฌ์šฉ์ž์ž…๋‹ˆ๋‹ค."; break; case 0: msg = "๋น„๊ฒผ์Šต๋‹ˆ๋‹ค."; break; } return msg; } // ์ˆซ์ž์— ํ• ๋‹น๋œ ๊ฐ€์œ„,๋ฐ”์œ„,๋ณด๋ฅผ ๋ฌธ์ž๋กœ ์ „ํ™˜ํ•ด์„œ ๋ณด์—ฌ์ฃผ๋Š” ์—ญํ•  public String showRpsVal(int playerVal) { String text = null; switch (playerVal) { case 1: text = "๊ฐ€์œ„"; break; case 2: text = "๋ฐ”์œ„"; break; case 3: text = "๋ณด"; break; } return text; } }
package kh.picsell.project; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.multipart.MultipartFile; import kh.picsell.dto.MemberDTO; import kh.picsell.service.MyInfoService; import kh.picsell.service.WriterpageService; @Controller @RequestMapping("/myInfo") public class MyInfoController { @Autowired private HttpSession session; @Autowired private MyInfoService myInfoService; @Autowired private WriterpageService writerservice; @RequestMapping("/myInfo.do") public String myInfo(HttpServletRequest request) { System.out.println("์˜ค๋ƒ?"); String nickName = (String)session.getAttribute("loginInfo"); Map<String,Integer> imginfo = writerservice.imginfo(nickName); request.setAttribute("imginfo", imginfo); MemberDTO memberDto = myInfoService.myInfo(nickName); memberDto.toString(); System.out.println("ze"); session.setAttribute("memberDto", memberDto); return "myPage/myPage"; } @RequestMapping("/infoModifyProc.do") public String infoModifyProc(MemberDTO memberDto, String id) { memberDto.setId(id); System.out.println(memberDto.toString()); myInfoService.infoModifyProc(memberDto); session.removeAttribute("loginInfo"); return "redirect:../home"; } @RequestMapping("/modiPage.do") public String modiPage(HttpServletRequest request) { String nickName = (String)session.getAttribute("loginInfo"); MemberDTO memberDto = myInfoService.myInfo(nickName); Map<String,Integer> imginfo = writerservice.imginfo(nickName); request.setAttribute("imginfo", imginfo); session.setAttribute("memberDto", memberDto); return "myPage/modiPage"; } @RequestMapping("/modifyPw.do") public String modifyPw() { return "myPage/modifyPw"; } @RequestMapping(value="/currentPwCheck.do", produces="text/html; charset=UTF-8") @ResponseBody public String currentPwCheck(String currentPw) { String nickName = (String)session.getAttribute("loginInfo"); return myInfoService.currentPwCheck(nickName, currentPw); } @RequestMapping("/modifyPwProc.do") public String modifyPwProc(String pw) { String nickName = (String)session.getAttribute("loginInfo"); myInfoService.modifyPwProc(pw, nickName); session.removeAttribute("loginInfo"); return "redirect:../home"; } @RequestMapping(value="profileimg", produces="text/html; charset=UTF-8") @ResponseBody public String modiprofileimg(MultipartFile file, String nickname) { System.out.println("์˜ค๋‹ˆ"); System.out.println(nickname); System.out.println(file); String path = session.getServletContext().getRealPath("profileimage"); String url = myInfoService.modiprofileimg(file, path, nickname); System.out.println(); return url; } }
package zuoshen.DP; public class ๅคš้‡่ƒŒๅŒ… { public static int method(int[]w,int[]v,int[]m,int c,int index){ int result=0; if(c==0||index==0){ result=0; }else if(c<w[index]){ result=method(w,v,m,c,index-1); }else { for (int i = 0; i <m[index]&&i*w[index]<c ; i++) { int temp=method(w,v,m,c-i*w[index],index-1)+i*v[index]; if(temp>result){ result=temp; } } } return result; } }
package com.example.prefecture.domain.model.prefecture; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import org.junit.jupiter.api.Test; import com.example.prefecture.domain.model.PrefectureCode; class PrefectureCodeTest { @Test void _้ƒฝ้“ๅบœ็œŒใ‚ณใƒผใƒ‰ใ‚’่จญๅฎš() { PrefectureCode code = new PrefectureCode("13"); assertEquals("13", code.getValue()); } @Test void _Nullใฎๅ ดๅˆใฏIllegalArgumentExceptionใŒ็™บ็”Ÿใ™ใ‚‹() { Exception thrown = assertThrows(IllegalArgumentException.class, () -> new PrefectureCode(null)); assertTrue(thrown instanceof IllegalArgumentException); assertEquals("้ƒฝ้“ๅบœ็œŒใ‚ณใƒผใƒ‰ใ‚’ๆŒ‡ๅฎšใ—ใฆใใ ใ•ใ„ใ€‚", thrown.getMessage()); } }
package com.tencent.mm.plugin.record.ui; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AbsListView.LayoutParams; import android.widget.ListView; import com.tencent.mm.R; import com.tencent.mm.g.a.rz; import com.tencent.mm.plugin.fav.ui.detail.BaseFavDetailReportUI; import com.tencent.mm.plugin.record.ui.h.b; import com.tencent.mm.pluginsdk.e; import com.tencent.mm.pluginsdk.ui.d.j; import com.tencent.mm.sdk.b.a; import com.tencent.mm.sdk.platformtools.bi; import com.tencent.mm.sdk.platformtools.x; public abstract class RecordMsgBaseUI extends BaseFavDetailReportUI { protected long bJC = -1; protected ListView eVT = null; protected h msU; protected abstract h bqB(); protected abstract String bqC(); protected abstract String bqD(); protected abstract String bqE(); protected abstract void bqF(); protected abstract void c(int i, int i2, Intent intent); protected final int getLayoutId() { return R.i.record_msg_detail_ui; } protected final int getForceOrientation() { return 1; } public void onCreate(Bundle bundle) { e.k(this); super.onCreate(bundle); bqA(); e.l(this); } protected void bqA() { this.msU = bqB(); this.bJC = getIntent().getLongExtra("message_id", -1); this.eVT = (ListView) findViewById(R.h.record_listview); bqI(); String bqD = bqD(); String bqE = bqE(); if (bi.oW(bqD) || bi.oW(bqE)) { x.i("MicroMsg.RecordMsgBaseUI", "subtitle time error!"); } else { bqD = bqD.split(" ")[0]; bqE = bqE.split(" ")[0]; if (bqD.equals(bqE)) { this.msU.msO = false; } else { bqD = bqD + "~" + bqE; this.msU.msO = true; } setMMSubTitle(bqD); } View view = new View(this.mController.tml); view.setLayoutParams(new LayoutParams(-1, getResources().getDimensionPixelSize(R.f.RecordListTopMargin))); this.eVT.addHeaderView(view, null, false); view = View.inflate(this.mController.tml, R.i.record_listview_footer, null); this.eVT.setAdapter(this.msU); this.msU.CU = this.eVT; this.msU.bqG(); this.eVT.setOnScrollListener(new 1(this)); setBackBtn(new 2(this)); bqF(); this.eVT.postDelayed(new 3(this, view), 100); } protected void onResume() { super.onResume(); rz rzVar = new rz(); if (this.eVT != null) { rzVar.ccO.type = 0; rzVar.ccO.ccP = this.eVT.getFirstVisiblePosition(); rzVar.ccO.ccQ = this.eVT.getLastVisiblePosition(); rzVar.ccO.ccR = this.eVT.getHeaderViewsCount(); a.sFg.m(rzVar); } } protected void onPause() { super.onPause(); if (this.msU != null) { h hVar = this.msU; int i = 0; while (true) { int i2 = i; if (i2 >= hVar.msN.size()) { break; } b bVar = (b) hVar.msN.valueAt(i2); if (bVar != null) { bVar.pause(); } i = i2 + 1; } } rz rzVar = new rz(); rzVar.ccO.type = 1; a.sFg.m(rzVar); } protected void onDestroy() { super.onDestroy(); if (this.msU != null) { this.msU.destroy(); } } protected void onActivityResult(int i, int i2, Intent intent) { c(i, i2, intent); } protected final void bqI() { CharSequence bqC = bqC(); String string = this.mController.tml.getString(R.l.expose_example); if (bqC != null && bqC.endsWith(string) && bqC.lastIndexOf(string) > 0) { bqC = bqC.substring(0, bqC.lastIndexOf(string) - 1); } M(j.a(this.mController.tml, bqC, getResources().getDimensionPixelSize(R.f.BigTextSize))); } }
package com.example.android.bluetoothlegatt; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import java.io.IOException; import java.io.PrintWriter; import java.net.Socket; import java.net.UnknownHostException; public class ClientActivity extends Activity { private Socket client; private PrintWriter printwriter; private EditText textFieldMessage, textFieldAddress; private Button button; private String messsage; private String ipAddress; private int PORT = 4444; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.client_activity); textFieldMessage = (EditText) findViewById(R.id.message); // reference to the text field textFieldAddress = (EditText) findViewById(R.id.address); button = (Button) findViewById(R.id.button1); // reference to the send button // Button press event listener button.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { messsage = textFieldMessage.getText().toString(); // get the text message on the text field ipAddress = textFieldAddress.getText().toString(); textFieldMessage.setText(""); // Reset the text field to blank SendMessage sendMessageTask = new SendMessage(); sendMessageTask.execute(); } }); } private class SendMessage extends AsyncTask<Void, Void, Void> { @Override protected Void doInBackground(Void... params) { System.out.println("proveraaaaaaaaaaaaaaaaaaaa"); try { client = new Socket(ipAddress, PORT); // connect to the server printwriter = new PrintWriter(client.getOutputStream(), true); printwriter.write(messsage); // write the message to output stream printwriter.flush(); printwriter.close(); client.close(); // closing the connection } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } } }
package com.brasilprev.customermanagement.commons.entrypoint.dto.client; import javax.validation.constraints.NotBlank; import javax.validation.constraints.Pattern; import org.hibernate.validator.constraints.Length; import com.fasterxml.jackson.databind.PropertyNamingStrategy; import com.fasterxml.jackson.databind.annotation.JsonNaming; import lombok.AllArgsConstructor; import lombok.Builder; import lombok.Getter; import lombok.NoArgsConstructor; @NoArgsConstructor @AllArgsConstructor @Getter @Builder @JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class) public class IdentityDocumentDTO { @Pattern(regexp = "CPF") @Length(min = 2, max = 197) @NotBlank private String identityType; @Pattern(regexp = "\\d{3}\\.\\d{3}\\.\\d{3}\\-\\d{2}") @NotBlank private String identity; }
package com.pkjiao.friends.mm.services; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.os.Handler; import android.os.IBinder; import android.os.Message; import android.widget.RemoteViews; import com.pkjiao.friends.mm.MarrySocialMainActivity; import com.pkjiao.friends.mm.R; import com.pkjiao.friends.mm.common.CommonDataStructure; public class UpdateAppServices extends Service { private static final int TIMEOUT = 10 * 1000;// ่ถ…ๆ—ถ private static final String DOWNLOAD_URL = "http://www.pkjiao.com/apk"; private static final int DOWNLOAD_OK = 1; private static final int DOWNLOAD_ERROR = 0; private static final int NOTIFICATION_ID = 0; private NotificationManager mNotificationManager; private Notification mNotification; private Intent mUpdateIntent; private PendingIntent mPendingIntent; private RemoteViews mDownloadView; private Handler mHandler; @Override public IBinder onBind(Intent arg0) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { mHandler = new Handler() { @SuppressWarnings("deprecation") @Override public void handleMessage(Message msg) { switch (msg.what) { case DOWNLOAD_OK: File file = new File(CommonDataStructure.DOWNLOAD_APP_URL); Uri uri = Uri.fromFile(file); Intent intent = new Intent(Intent.ACTION_VIEW); intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); intent.setDataAndType(uri, "application/vnd.android.package-archive"); mPendingIntent = PendingIntent.getActivity( UpdateAppServices.this, 0, intent, 0); mNotification = new Notification(); mNotification.icon = R.drawable.ic_notification; mNotification.tickerText = "ๆญฃๅœจไธ‹่ฝฝ"; mNotification.when = System.currentTimeMillis(); mNotification.flags = Notification.FLAG_ONGOING_EVENT; mNotification.flags = Notification.FLAG_AUTO_CANCEL; mNotification.contentIntent = mPendingIntent; mNotification.setLatestEventInfo(UpdateAppServices.this, "friends+", "ไธ‹่ฝฝๆˆๅŠŸ๏ผŒ็‚นๅ‡ปๅฎ‰่ฃ…", mPendingIntent); mNotificationManager.notify(NOTIFICATION_ID, mNotification); stopSelf(); break; case DOWNLOAD_ERROR: mNotification.flags = Notification.FLAG_ONGOING_EVENT; mNotification.flags = Notification.FLAG_AUTO_CANCEL; mNotification.setLatestEventInfo(UpdateAppServices.this, "friends+", "ไธ‹่ฝฝๅคฑ่ดฅ", mPendingIntent); break; default: stopSelf(); break; } } }; createAppFile(); createNotification(); createThread(); return super.onStartCommand(intent, flags, startId); } public void createThread() { new Thread(new Runnable() { @Override public void run() { try { long downloadSize = downloadUpdateFile(DOWNLOAD_URL, CommonDataStructure.DOWNLOAD_APP_URL); if (downloadSize > 0) { mHandler.sendEmptyMessage(DOWNLOAD_OK); } else { mHandler.sendEmptyMessage(DOWNLOAD_ERROR); } } catch (Exception e) { mHandler.sendEmptyMessage(DOWNLOAD_ERROR); } } }).start(); } public void createNotification() { mDownloadView = new RemoteViews(getPackageName(), R.layout.notification_download_app_layout); mDownloadView.setTextViewText(R.id.notificationTitle, "friends+ ๆญฃๅœจไธ‹่ฝฝ..."); mDownloadView.setTextViewText(R.id.notificationPercent, "0%"); mDownloadView.setProgressBar(R.id.notificationProgress, 100, 0, false); mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); mNotification = new Notification(); mNotification.icon = R.drawable.ic_notification; mNotification.tickerText = "ๆญฃๅœจไธ‹่ฝฝ"; mNotification.when = System.currentTimeMillis(); mNotification.contentView = mDownloadView; mNotification.flags = Notification.FLAG_ONGOING_EVENT; mNotification.flags = Notification.FLAG_AUTO_CANCEL; mUpdateIntent = new Intent(this, MarrySocialMainActivity.class); mUpdateIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP); mPendingIntent = PendingIntent.getActivity(this, 0, mUpdateIntent, 0); mNotification.contentIntent = mPendingIntent; mNotificationManager.notify(NOTIFICATION_ID, mNotification); } public long downloadUpdateFile(String down_url, String file) { int down_step = 5;// ๆ็คบstep int totalSize;// ๆ–‡ไปถๆ€ปๅคงๅฐ int downloadCount = 0;// ๅทฒ็ปไธ‹่ฝฝๅฅฝ็š„ๅคงๅฐ int updateCount = 0;// ๅทฒ็ปไธŠไผ ็š„ๆ–‡ไปถๅคงๅฐ InputStream inputStream = null; OutputStream outputStream = null; URL url = null; HttpURLConnection httpURLConnection = null; try { url = new URL(down_url); if (url == null) return downloadCount; httpURLConnection = (HttpURLConnection) url.openConnection(); if (httpURLConnection == null) return downloadCount; httpURLConnection.setConnectTimeout(TIMEOUT); httpURLConnection.setReadTimeout(TIMEOUT); totalSize = httpURLConnection.getContentLength(); if (httpURLConnection.getResponseCode() != 200) { return downloadCount; } inputStream = httpURLConnection.getInputStream(); outputStream = new FileOutputStream(file, false);// ๆ–‡ไปถๅญ˜ๅœจๅˆ™่ฆ†็›–ๆމ byte buffer[] = new byte[1024]; int readsize = 0; while ((readsize = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, readsize); downloadCount += readsize;// ๆ—ถๆ—ถ่Žทๅ–ไธ‹่ฝฝๅˆฐ็š„ๅคงๅฐ if (updateCount == 0 || (downloadCount * 100 / totalSize - down_step) >= updateCount) { updateCount += down_step; mDownloadView.setTextViewText(R.id.notificationPercent, updateCount + "%"); mDownloadView.setProgressBar(R.id.notificationProgress, 100, updateCount, false); mNotificationManager.notify(NOTIFICATION_ID, mNotification); } } inputStream.close(); outputStream.close(); } catch (Exception exp) { exp.printStackTrace(); } finally { if (httpURLConnection != null) { httpURLConnection.disconnect(); } } return downloadCount; } public void createAppFile() { if (android.os.Environment.MEDIA_MOUNTED.equals(android.os.Environment .getExternalStorageState())) { File updateAppDir = new File( CommonDataStructure.DOWNLOAD_APP_DIR_URL); File updateAppFile = new File(CommonDataStructure.DOWNLOAD_APP_URL); if (!updateAppDir.exists()) { updateAppDir.mkdirs(); } if (!updateAppFile.exists()) { try { updateAppFile.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } } } }
/* * Copyright (c) 2008 by Bjoern Kolbeck, * Zuse Institute Berlin * * Licensed under the BSD License, see LICENSE file for details. * */ package org.xtreemfs.common.auth; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import org.xtreemfs.foundation.logging.Logging; import org.xtreemfs.foundation.logging.Logging.Category; import org.xtreemfs.foundation.pbrpc.channels.ChannelIO; /** * authentication provider for the Contrail project. * * @author PS */ public class FederationIdX509AuthProvider implements AuthenticationProvider { private final static String USER_ID = "CN"; private final static String GROUP_ID = "O"; // String privilegedCertificatePathname = "privileged.txt"; // private HashSet<String> privilegedCertificates; @Override public UserCredentials getEffectiveCredentials( org.xtreemfs.foundation.pbrpc.generatedinterfaces.RPC.UserCredentials ctx, ChannelIO channel) throws AuthenticationException { // use cached info, if present! if (channel.getAttachment() != null) { if (Logging.isDebug()) { Logging.logMessage( Logging.LEVEL_DEBUG, Category.auth, this, "using attachment..."); } final UserCredentials creds = (UserCredentials)channel.getAttachment(); if (Logging.isDebug()) { Logging.logMessage( Logging.LEVEL_DEBUG, Category.auth, this, "using cached creds: " + creds); } return creds; } // parse cert if no cached info is present try { final Certificate[] certs = channel.getCerts(); if (certs.length > 0) { final X509Certificate cert = ((X509Certificate) certs[0]); String fullDN = cert.getSubjectX500Principal().getName(); final List<String> globalUIDs = getNamedElements( cert.getSubjectX500Principal().getName(), USER_ID); // only use the UUID of the certificate String globalUID = null; if (!globalUIDs.isEmpty()) { globalUID = globalUIDs.iterator().next(); } else { globalUID = fullDN; } final List<String> globalGIDs = getNamedElements( cert.getSubjectX500Principal().getName(), GROUP_ID); if (globalGIDs.isEmpty()) { globalGIDs.add(fullDN); } if (Logging.isDebug()) { Logging.logMessage( Logging.LEVEL_DEBUG, Category.auth, this, "X.509-User cert present: %s, %s", globalUID, globalGIDs); } // the super user is required for the GAFS manager to // act in behalf of a user to create/delete volumes and // add policies to volumes boolean isSuperUser = false; // for (String privilegedCert : this.privilegedCertificates) { // if (fullDN.contains(privilegedCert)) { // isSuperUser = true; // break; // } // } final UserCredentials creds = new UserCredentials(globalUID, globalGIDs, isSuperUser); channel.setAttachment(creds); return creds; } else { throw new AuthenticationException("no X.509-certificates present"); } } catch (Exception ex) { Logging.logUserError(Logging.LEVEL_ERROR, Category.auth, this, ex); throw new AuthenticationException("invalid credentials " + ex); } } private List<String> getNamedElements(String principal, String element) { String[] elems = principal.split(","); List<String> elements = new ArrayList<String>(); for (String elem : elems) { String[] kv = elem.split("="); if (kv.length == 2 && kv[0].equals(element)) { elements.add(kv[1]); } } return elements; } public void initialize(boolean useSSL) throws RuntimeException { if (!useSSL) { throw new RuntimeException(this.getClass().getName() + " can only be used if SSL is enabled!"); } // InputStream privilegedCertificatesStream // = getClass().getClassLoader().getResourceAsStream(this.privilegedCertificatePathname); // service certs // this.privilegedCertificates = readHosts(privilegedCertificatesStream); } public static HashSet<String> readHosts(InputStream serviceCertificatesStream) { HashSet<String> serviceCertificates = new HashSet<String>(); if (serviceCertificatesStream == null) { Logging.logMessage( Logging.LEVEL_WARN, Category.auth, FederationIdX509AuthProvider.class, "The list of privileged-certificates does not exist."); return serviceCertificates; // throw new RuntimeException("The list of privileged-certificates does not exist"); } InputStreamReader in = null; BufferedReader reader = null; try { in = new InputStreamReader(serviceCertificatesStream); reader = new BufferedReader(in); String line = null; while ((line = reader.readLine()) != null) { line.trim(); if (line == null || line.equals("")) { continue; } else { serviceCertificates.add(line); Logging.logMessage(Logging.LEVEL_INFO, Category.auth, FederationIdX509AuthProvider.class, "Adding service-certificate: " + line); } } } catch (FileNotFoundException e) { Logging.logMessage( Logging.LEVEL_WARN, Category.auth, FederationIdX509AuthProvider.class, "The list of privileged-certificates does not exist."); // throw new RuntimeException( // "The list of privileged-certificates does not exist."); } catch (IOException e) { Logging.logMessage( Logging.LEVEL_WARN, Category.auth, FederationIdX509AuthProvider.class, "Could not parse the list of privileged-certificates."); // throw new RuntimeException( // "Could not parse the list of privileged-certificates."); } finally { try { if (reader != null) { reader.close(); } } catch (IOException e) { } } return serviceCertificates; } }
package id.slametriyadi.wisataindonesia.Response; import com.google.gson.annotations.SerializedName; public class ListAirTerjun { @SerializedName("nama_airterjun") private String namaAirterjun; @SerializedName("tiket_airterjun") private String tiketAirterjun; @SerializedName("desk_airterjun") private String deskAirterjun; @SerializedName("id_daerah") private String idDaerah; @SerializedName("id") private String id; @SerializedName("img_airterjun") private String imgAirterjun; public void setNamaAirterjun(String namaAirterjun){ this.namaAirterjun = namaAirterjun; } public String getNamaAirterjun(){ return namaAirterjun; } public void setTiketAirterjun(String tiketAirterjun){ this.tiketAirterjun = tiketAirterjun; } public String getTiketAirterjun(){ return tiketAirterjun; } public void setDeskAirterjun(String deskAirterjun){ this.deskAirterjun = deskAirterjun; } public String getDeskAirterjun(){ return deskAirterjun; } public void setIdDaerah(String idDaerah){ this.idDaerah = idDaerah; } public String getIdDaerah(){ return idDaerah; } public void setId(String id){ this.id = id; } public String getId(){ return id; } public void setImgAirterjun(String imgAirterjun){ this.imgAirterjun = imgAirterjun; } public String getImgAirterjun(){ return imgAirterjun; } @Override public String toString(){ return "ListAirTerjun{" + "nama_airterjun = '" + namaAirterjun + '\'' + ",tiket_airterjun = '" + tiketAirterjun + '\'' + ",desk_airterjun = '" + deskAirterjun + '\'' + ",id_daerah = '" + idDaerah + '\'' + ",id = '" + id + '\'' + ",img_airterjun = '" + imgAirterjun + '\'' + "}"; } }
package org.training.issuetracker.controllers; import java.util.List; import java.util.Locale; import javax.servlet.http.HttpServletRequest; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.MessageSource; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.training.issuetracker.dao.entities.User; import org.training.issuetracker.logic.AccessLogic; import org.training.issuetracker.pages.MainPage; import org.training.issuetracker.pages.UsersPage; import org.training.issuetracker.services.UserService; @Controller @RequestMapping("/users") public class UsersController { @Autowired private MainController mainController; @Autowired private UserService userService; @Autowired private MessageSource messageSource; @Autowired private AccessLogic accessLogic; private final String DEFAULT_FILTER = null; @RequestMapping() public String showProjects(Model model, Locale locale, HttpServletRequest request) { return showUsers(model, request, locale, DEFAULT_FILTER); } @RequestMapping(value = "filter/{filter}", method=RequestMethod.POST) public String showUsers(Model model, HttpServletRequest request, Locale locale, @PathVariable("filter") String filter) { String page = UsersPage.NAME; if(accessLogic.isHaveAdminAccess(request)){ model.addAttribute(UsersPage.ATTR_PAGE_TITLE, UsersPage.getMessage(UsersPage.MSG_TTL_FIND_USER, messageSource, locale)); model.addAttribute(UsersPage.ATTR_FILTER, filter); List<User> users = null; if(filter == null){ // full list users = userService.getUsers(); } else{ // search users users = userService.getUsersWithFilter(filter); } if(users != null){ model.addAttribute(UsersPage.ATTR_USERS, users); } else{ model.addAttribute(UsersPage.ATTR_ERROR_MESSAGE, UsersPage.getMessage(UsersPage.MSG_ERR_NO_USERS, messageSource, locale)); } } else{ // we don't have access to this page // tell this to a user and forward him to the main page model.addAttribute(MainPage.ATTR_ERROR_MESSAGE, UsersPage.getMessage(UsersPage.MSG_ERR_NO_ACCESS, messageSource, locale)); page = mainController.showMainPage(model, request, locale); } return page; } }
package cn.gavinliu.notificationbox.model; import android.content.Intent; import com.litesuits.orm.db.annotation.Column; import com.litesuits.orm.db.annotation.Ignore; import com.litesuits.orm.db.annotation.NotNull; import com.litesuits.orm.db.annotation.PrimaryKey; import com.litesuits.orm.db.annotation.Table; import com.litesuits.orm.db.enums.AssignType; /** * Created by Gavin on 2016/10/11. */ @Table("notifications") public class NotificationInfo { @PrimaryKey(AssignType.AUTO_INCREMENT) @Column("_id") private int id; @NotNull private String packageName; private String title; private String text; private long time; private int flag=-1; @Ignore private Intent mIntent; public NotificationInfo(String packageName, String title, String text, long time) { this.packageName = packageName; this.title = title; this.text = text; this.time = time; } // ๆ นๆฎๅˆๅง‹ๅŒ–ๆ—ถ่พ“ๅ…ฅๅ†…ๅฎนไธๅŒ๏ผŒ็กฎๅฎšflagๅšไธๅšๅˆๅง‹ๅŒ– public NotificationInfo(String packageName, String title, String text, long time,int flag) { this.packageName = packageName; this.title = title; this.text = text; this.time = time; this.flag=flag; } public int getFlag(){ return flag; } public void setFlag(int flag){ this.flag=flag; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getPackageName() { return packageName; } public void setPackageName(String packageName) { this.packageName = packageName; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getText() { return text; } public void setText(String text) { this.text = text; } public long getTime() { return time; } public void setTime(long time) { this.time = time; } public Intent getIntent() { return mIntent; } public void setIntent(Intent intent) { mIntent = intent; } }
package com.game.taoy3.webviewdemo; import android.os.Environment; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; /** * Created by taoy3 on 16/3/17. */ public class HttpThread extends Thread{ private String url; public HttpThread(String url){ this.url = url; } @Override public void run() { try { URL httpUrl = new URL(url); HttpURLConnection connection = (HttpURLConnection) httpUrl.openConnection(); connection.setDoInput(true); connection.setDoOutput(true); InputStream inputStream = connection.getInputStream(); File downFile; File sdfFile; FileOutputStream out = null; if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){ downFile = Environment.getExternalStorageDirectory(); sdfFile = new File(downFile,"test.apk"); out = new FileOutputStream(sdfFile); } byte[] b = new byte[6*1024]; int len; while ((len = inputStream.read())!=-1){ if(out!=null){ out.write(b,0,len); } } if(inputStream!=null){ inputStream.close(); } if(out !=null){ out.close(); } } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }
package com.company.order.controller; import static org.junit.Assert.assertTrue; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.junit.FixMethodOrder; import org.junit.Test; import org.junit.runners.MethodSorters; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MvcResult; import com.company.order.base.BaseTest; import com.company.order.entity.ItemOrder; import com.company.order.entity.Order; import com.company.order.entity.OrderStatus; import com.company.order.entity.customer.Customer; import com.company.order.entity.customer.DeliveryAddress; import com.company.order.entity.customer.IdentityType; import com.company.order.entity.item.Item; import com.company.order.entity.item.Unit; @FixMethodOrder(MethodSorters.NAME_ASCENDING) public class OrderControllerTest extends BaseTest { private static String id; public OrderControllerTest() { super("/orders"); } private Item getItem() { Unit unit = new Unit(); unit.setId(UUID.randomUUID().toString()); unit.setDescription("Unit Description"); Item item = new Item(); item.setSku(UUID.randomUUID().toString()); item.setName("Test Item"); item.setUnit(unit); return item; } private ItemOrder[] getItens() { List<ItemOrder> itens = new ArrayList<>(); ItemOrder item = new ItemOrder(); item.setItem(getItem()); item.setQuantity(2); item.setUnitPrice(1.99); itens.add(item); return itens.toArray(new ItemOrder[itens.size()]); } private DeliveryAddress getDeliveryAddress() { DeliveryAddress address = new DeliveryAddress(); address.setCity("City"); address.setComplement("complement"); address.setCountry("Country"); address.setDistrict("district"); address.setNumber("0"); address.setState("state"); address.setStreet("street"); address.setZipCode("00000-000"); return address; } private Customer getCustomer() { Customer customer = new Customer(); customer.setId(UUID.randomUUID().toString()); customer.setEmail("teste@email.com"); customer.setIdentity("00000000000"); customer.setIdentityType(IdentityType.CPF); customer.setName("Customer"); return customer; } private Order getOrder() { Order order = new Order(); order.setCustomer(getCustomer()); order.setDeliveryAddress(getDeliveryAddress()); order.addItem(getItens()); order.setStatus(OrderStatus.CREATED); return order; } @Test public void test1_save() throws Exception { Order order = getOrder(); MvcResult result = mvc .perform(post(getUri()).contentType(MediaType.APPLICATION_JSON_VALUE).content(asJson(order))) .andExpect(status().isCreated()).andReturn(); id = getIdFromLocation(result); } @Test public void test2_one() throws Exception { MvcResult response = mvc.perform(get(getUri()).contentType(MediaType.APPLICATION_JSON_VALUE).param("id", id)) .andExpect(status().isOk()).andReturn(); assertTrue(response.getResponse().getContentAsString().contains(id)); } @Test public void test3_all() throws Exception { mvc.perform(get(getUri()).contentType(MediaType.APPLICATION_JSON_VALUE)).andExpect(status().isOk()); } @Test public void test4_update() throws Exception { Order order = getOrder(); mvc.perform(put(getUri() + "/" + id).contentType(MediaType.APPLICATION_JSON_VALUE).content(asJson(order))) .andExpect(status().isOk()); } @Test public void test5_remove() throws Exception { mvc.perform(delete(getUri() + "/" + id).contentType(MediaType.APPLICATION_JSON_VALUE)) .andExpect(status().isOk()); } }
package com.mkay.scorecard; import android.annotation.SuppressLint; import android.app.ActionBar; import android.support.v4.app.Fragment; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.SupportMapFragment; import java.util.ArrayList; import android.widget.LinearLayout; @SuppressLint("NewApi") public class FragmentTwo extends Fragment implements ShotsDialogFragment.OnCompleteListener { ArrayList<Player> playerList; View view; public FragmentTwo() { } public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { view = inflater.inflate(R.layout.fragment_two, container, false); playerList = new ArrayList(); //createPlayers(4, view); initMap(); initTextViews(); return view; } private void createPlayers(int nrPlayers, View view) { LinearLayout scorecardLayout = (LinearLayout) view.findViewById(R.id.scorecard_container); Player player; TextView textView; for(int i = 0; i < nrPlayers; i++) { player = new Player("Player"+Integer.toString(i), 36); playerList.add(player); textView = new TextView(view.getContext()); textView.setText(playerList.get(i).name + "\nHandicap: " + playerList.get(i).handicap); textView.setLayoutParams(new LinearLayout.LayoutParams( LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT)); scorecardLayout.addView(textView); } } private void initMap () { SupportMapFragment googleMapFragment; GoogleMap googleMap; FragmentManager fragmentManager = getChildFragmentManager(); googleMapFragment = (SupportMapFragment) fragmentManager.findFragmentById(R.id.map_container); // check if map is created successfully or not if (googleMapFragment == null) { googleMapFragment = SupportMapFragment.newInstance(); fragmentManager.beginTransaction().replace(R.id.map_container, googleMapFragment).commit(); } googleMap = googleMapFragment.getMap(); } private void initTextViews() { view.findViewById(R.id.p0shots).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showDialog(); } }); } public void showDialog() { ShotsDialogFragment dialog = new ShotsDialogFragment(); dialog.setTargetFragment(this, 0); dialog.show(getFragmentManager(), "ShotsDialogFragment"); } @Override public void onComplete(int shots) { // After the dialog fragment completes, it calls this callback. // use the string here TextView textView = (TextView)view.findViewById(R.id.p0shots); String output = Integer.toString(shots); textView.setText(output); } @Override public void onResume() { super.onResume(); } }
package config; public class Paths { public static final String HOME_FOLDER = System.getProperty("user.dir"); public static final String CHROME_FILE = ".\\vendor\\chromedriver.exe"; public static final String DEFAULT_SCREENSHOT_FILENAME = "screenshot.png"; public static final String CALCULATOR_URL = "http://web2.0calc.com/"; }
package br.edu.ifam.saf.api.dto; import javax.enterprise.context.ApplicationScoped; import br.edu.ifam.saf.modelo.Cidade; @ApplicationScoped public class CidadeTransformer implements DTOTransformer<Cidade, CidadeDTO> { @Override public Cidade toEntity(CidadeDTO dto) { Cidade cidade = new Cidade(); cidade.setNome(dto.getNome()); cidade.setEstado(dto.getEstado()); cidade.setId(dto.getId()); return cidade; } @Override public CidadeDTO toDTO(Cidade entity) { if (entity == null) return null; CidadeDTO dto = new CidadeDTO(); dto.setId(entity.getId()); dto.setNome(entity.getNome()); dto.setEstado(entity.getEstado()); return dto; } }
package one.kii.summer.asdf.api; import one.kii.summer.io.context.WriteContext; public interface SimpleCommitApi<R, F> extends CommitApi<R, WriteContext, F> { }
package net.minecraft.network.rcon; import net.minecraft.command.ICommandSender; import net.minecraft.server.MinecraftServer; import net.minecraft.util.text.ITextComponent; import net.minecraft.world.World; public class RConConsoleSource implements ICommandSender { private final StringBuffer buffer = new StringBuffer(); private final MinecraftServer server; public RConConsoleSource(MinecraftServer serverIn) { this.server = serverIn; } public String getName() { return "Rcon"; } public void addChatMessage(ITextComponent component) { this.buffer.append(component.getUnformattedText()); } public boolean canCommandSenderUseCommand(int permLevel, String commandName) { return true; } public World getEntityWorld() { return this.server.getEntityWorld(); } public boolean sendCommandFeedback() { return true; } public MinecraftServer getServer() { return this.server; } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\network\rcon\RConConsoleSource.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package com.xuecheng; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ManageCmsClientApplication { public static void main(String[] args) { SpringApplication.run(ManageCmsClientApplication.class, args); } }
package com.music.DAO; import java.util.List; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.music.model.UserDetail; @Repository @Transactional public class UserDAOImpl implements UserDAO { private List<UserDetail> listUser; @Autowired SessionFactory sessionFactory; @Override public void addUser(UserDetail ud) { Session sess=sessionFactory.openSession(); Transaction tx=sess.beginTransaction(); sess.save(ud); tx.commit(); sess.close(); System.out.println("successssss valu is "+ud.getUrole()); } @Override public void updateUser(UserDetail ud) { Session sess=sessionFactory.openSession(); Transaction trx=sess.beginTransaction(); sess.saveOrUpdate(ud); trx.commit(); sess.close(); } @Override public void removeUSer(int uid) { Session sess=sessionFactory.openSession(); Transaction trx=sess.beginTransaction(); UserDetail ud=(UserDetail)sess.load(UserDetail.class,uid ); sess.delete(ud); trx.commit(); sess.close(); } @Override public List<UserDetail> getUser() { Session sess=sessionFactory.openSession(); listUser=sess.createQuery("from UserDetail").list(); return listUser; } @Override public UserDetail getUserbyId(int uid) { Session sess=sessionFactory.openSession(); Transaction tx=sess.beginTransaction(); listUser= sess.createQuery("from UserDetail u where u.uid=:uid").setParameter("uid", uid).list(); tx.commit(); sess.close(); return listUser.size()>0?listUser.get(0):null; } }
package fontys.sot.rest.service.models; import java.util.ArrayList; import java.util.List; public class Order { private static int orderNumber = 0; private int number; private int userId; List<LineItem> lineItems; public Order() { super(); } public Order(int userId) { this(); number = ++orderNumber; this.userId = userId; lineItems = new ArrayList<>(); } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public double getTotal() { double sum = 0.0; for (LineItem lineItem: lineItems) { sum += lineItem.getTotal(); } return sum; } public void addLineItem(LineItem lineItem) { for (LineItem li: lineItems) { if (li.getProduct().equals(lineItem.getProduct())) { li.addQuantity(lineItem.getQuantity()); return; } } lineItems.add(lineItem); } public boolean isEmpty() { return lineItems.size() == 0; } public void remove(LineItem lineItem) { lineItems.remove(lineItem); } public List<LineItem> getLineItems() { return lineItems; } public void setLineItems(List<LineItem> lineItems) { this.lineItems = lineItems; } }
package com.sharpower.dao.impl; import com.sharpower.entity.VariableType; public class VariableTypeDaoImpl extends BaseDaoImpl<VariableType> { }
package pat; /** * @author kangkang lou * <p> * ็ด ๆ•ฐ * <p> * ็ด ๆ•ฐ * <p> * ็ด ๆ•ฐ */ /** * ็ด ๆ•ฐ */ import java.util.Scanner; public class Main_3 { public static void main(String[] args) { Scanner in = new Scanner(System.in); int begin = in.nextInt(); int end = in.nextInt(); in.close(); int[] array = new int[end]; int index = 0; int i = 2; while (index < end) { if (isPrime(i)) { array[index] = i; index++; } i++; } int ten = 0; for (int j = (begin - 1); j < end; j++) { System.out.print(array[j]); ten++; if (ten % 10 == 0) { System.out.println(); continue; } if (j != end - 1) { System.out.print(" "); } } } public static boolean isPrime(int n) { if (n == 1) { return false; } else if (n == 2) { return true; } else if (n % 2 == 0) { return false; } else { for (int i = 3; i <= (int) Math.sqrt(n); i += 2) { if (n % i == 0) { return false; } } return true; } } }
package io.beaniejoy.bootapiserver.model; import lombok.*; import java.util.List; // Entity ์ •์˜ํ•œ Class์—๋Š” Default Constructor & All Arguments Constructor ๋‘˜๋‹ค ์žˆ์–ด์•ผํ•œ๋‹ค. // ๊ทธ๋ž˜์•ผ default mapper mapping์ด ๊ฐ€๋Šฅํ•˜๋‹ค. @Getter @Builder @NoArgsConstructor @AllArgsConstructor public class Company { private Long id; private String companyName; private String companyAddress; private List<Employee> employeeList; public void updateInfo(String companyName, String companyAddress) { this.companyName = companyName; this.companyAddress = companyAddress; } }
package com.oddle.app.weather.models.open_weather; import com.fasterxml.jackson.annotation.JsonProperty; public class Weather { private int id; private String group; private String description; private String icon; public int getId() { return id; } public void setId(int id) { this.id = id; } @JsonProperty("group") public String getGroup() { return group; } @JsonProperty("main") public void setGroup(String group) { this.group = group; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } }
public class ListNode{ int val; ListNode next; ListNode(int x) { val = x; } public String printNode() { if (this.next == null) return Integer.toString(this.val); return Integer.toString(this.val) + "->" + this.next.printNode(); } public void print() { System.out.println(this.printNode()); } public static void main (String[] args) { ListNode one = new ListNode(1); ListNode two = new ListNode(2); ListNode three = new ListNode(3); one.next = two; two.next = three; System.out.println(one.printNode()); } }
package com.podarbetweenus.Adapter; import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.podarbetweenus.Entity.teacherStudBehaviourResult; import com.podarbetweenus.R; import java.util.ArrayList; /** * Created by Gayatri on 2/2/2016. */ public class ViewBehaviourAdapter extends BaseAdapter { LayoutInflater layoutInflater; Context context; String date; ArrayList<teacherStudBehaviourResult> TeacherStudBehaviourResultv = new ArrayList<teacherStudBehaviourResult>(); public ViewBehaviourAdapter(Context context,ArrayList<teacherStudBehaviourResult> TeacherStudBehaviourResultv) { this.context = context; this.TeacherStudBehaviourResultv = TeacherStudBehaviourResultv; this.layoutInflater = layoutInflater.from(this.context); layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { return TeacherStudBehaviourResultv.size(); } @Override public Object getItem(int position) { return TeacherStudBehaviourResultv.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { ViewHolder holder = null; View showLeaveStatus = convertView; if (showLeaveStatus == null) { holder = new ViewHolder(); showLeaveStatus = layoutInflater.inflate(R.layout.view_behaviour_list_item, null); holder.tv_behaviour_date = (TextView) showLeaveStatus.findViewById(R.id.tv_behaviour_date); holder.tv_behaviour_desc = (TextView) showLeaveStatus.findViewById(R.id.tv_behaviour_desc); holder.img_behaviour_response = (ImageView)showLeaveStatus.findViewById(R.id.img_behaviour_response); } else { holder = (ViewHolder) showLeaveStatus.getTag(); } showLeaveStatus.setTag(holder); holder.tv_behaviour_date.setText(TeacherStudBehaviourResultv.get(position).sbh_date1); holder.tv_behaviour_desc.setText(TeacherStudBehaviourResultv.get(position).bhr_name); if(TeacherStudBehaviourResultv.get(position).bhr_type.equalsIgnoreCase("0")) { holder.img_behaviour_response.setBackgroundResource(R.drawable.thumbsup); } else{ holder.img_behaviour_response.setBackgroundResource(R.drawable.thumbsdown); } return showLeaveStatus; } public static class ViewHolder { TextView tv_behaviour_date,tv_behaviour_desc; ImageView img_behaviour_response; } }
package com.snab.tachkit.ClassesJson; import android.os.Parcel; import android.os.Parcelable; /** * Created by ะขะฐะฝั on 08.05.2015. * ะกั‚ั€ัƒะบั‚ัƒั€ะฐ ะฟั€ะธะฝัั‚ั‹ั… ะฝะพะฒะพัั‚ะตะน ั ัะฒะตั€ะฒะฐ */ public class DataNews implements Parcelable { String first_img; String title; String date; String author; String source_photo; String source_photo_url; String source_text; String source_text_url; String description; String content; public String getFirst_img() { return first_img; } public String getTitle() { return title; } public String getDate() { return date; } public String getAuthor() { return author; } public String getSource_photo() { return source_photo; } public String getSource_photo_url() { return source_photo_url; } public String getSource_text() { return source_text; } public String getSource_text_url() { return source_text_url; } public String getDescription() { return description; } public String getContent() { return content; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeString(first_img); dest.writeString(title); dest.writeString(date); dest.writeString(author); dest.writeString(source_photo); dest.writeString(source_photo_url); dest.writeString(source_text); dest.writeString(source_text_url); dest.writeString(description); dest.writeString(content); } }
package com.examples.chapter02; public class LearningVariables { // ใƒกใƒณใƒๅค‰ๆ•ฐใฎๅฎฃ่จ€ไพ‹๏ผš // ใ‚ฏใƒฉใ‚นๅ†…ใงๅฎฃ่จ€ใ™ใ‚‹ๅค‰ๆ•ฐใฏใ€ใƒกใƒณใƒๅค‰ๆ•ฐใจใ„ใ„ใพใ™ใ€‚ // ใ‚ฏใƒฉใ‚นๅ†…ใฎๅ„ใƒกใ‚ฝใƒƒใƒ‰ใ‹ใ‚‰ๅ‚็…งใ™ใ‚‹ใ“ใจใŒใงใใพใ™ใ€‚ // ใ‚คใƒณใ‚นใ‚ฟใƒณใ‚นๆฏŽใซๅค‰ๆ•ฐใ‚’ๆŒใกใพใ™ใ€‚ // staticใƒกใ‚ฝใƒƒใƒ‰ใ‹ใ‚‰ใฏๅ‚็…งใงใใพใ›ใ‚“ใ€‚ // ๅค‰ๆ•ฐๅฎฃ่จ€ใฎไพ‹: [ใ‚ขใ‚ฏใ‚ปใ‚นไฟฎ้ฃพๅญ] ใƒ‡ใƒผใ‚ฟๅž‹ ๅค‰ๆ•ฐๅ; private String name1; private int value1; // ๅฎฃ่จ€ๆ™‚ใซๅ€คใ‚’ๅˆๆœŸๅŒ–ใ™ใ‚‹ใ“ใจใ‚‚ใงใใพใ™ใ€‚ private String name2 = "FOO"; private int value2 = 100; // ใ‚ฏใƒฉใ‚นๅค‰ๆ•ฐใฎๅฎฃ่จ€ไพ‹๏ผš // staticไป˜ใฎๅค‰ๆ•ฐใฏใ€ใ‚ฏใƒฉใ‚นๅค‰ๆ•ฐ(staticๅค‰ๆ•ฐ)ใจ่จ€ใ„ใพใ™ใ€‚ // ใ‚ฏใƒฉใ‚นใŒๆŒใคๅค‰ๆ•ฐใงใ‚ใ‚Šใ€่ค‡ๆ•ฐใฎใ‚นใƒฌใƒƒใƒ‰ใ€ใ‚คใƒณใ‚นใ‚ฟใƒณใ‚นใ‹ใ‚‰ใฏๅ…ฑๆœ‰ใ•ใ‚Œใพใ™ใ€‚ private static String staticName1 = "STATIC1"; private static int staticValue1 = 10; // public static void main(String[] args) { // ใ‚คใƒณใ‚นใ‚ฟใƒณใ‚นใ‚’็”Ÿๆˆ LearningVariables bean1 = new LearningVariables(); LearningVariables bean2 = new LearningVariables(); // ใ‚คใƒณใ‚นใ‚ฟใƒณใ‚นใฎๅค‰ๆ•ฐใ‚’ๅค‰ๆ›ดใ—ใฆใฟใพใ—ใ‚‡ใ† bean1.name1 = "bean1"; bean1.value1 = 1; bean2.name1 = "bean2"; bean2.value1 = 2; // ใ‚คใƒณใ‚นใ‚ฟใƒณใ‚นใฎๅค‰ๆ•ฐใ‚’ๆจ™ๆบ–ๅ‡บๅŠ›ใ—ใฆใฟใพใ—ใ‚‡ใ† bean1.helloMethod(); bean2.helloMethod(); // staticๅค‰ๆ•ฐใฎๅ€คใ‚’ๅค‰ๆ›ดใ—ใŸๅ ดๅˆใฏใฉใ†ใชใ‚‹ใฎใ‹๏ผŸ staticName1 = "TEST"; staticValue1 = 200; bean1.helloMethod(); bean2.helloMethod(); } // ใƒกใ‚ฝใƒƒใƒ‰ๅ†…ใงๅฎฃ่จ€ใ™ใ‚‹ๅค‰ๆ•ฐใฏใ€ใƒญใƒผใ‚ซใƒซๅค‰ๆ•ฐใจใ„ใ„ใพใ™ใ€‚ public void helloMethod() { // ใƒญใƒผใ‚ซใƒซๅค‰ๆ•ฐใฎๅฎฃ่จ€ไพ‹ใ€‚ใ‚ขใ‚ฏใ‚ปใ‚นไฟฎ้ฃพๅญใฏใคใ‘ใ‚‰ใ‚Œใพใ›ใ‚“ใ€‚ // ใƒญใƒผใ‚ซใƒซๅค‰ๆ•ฐใฎๅ ดๅˆใ€ๆœชๅˆๆœŸๅŒ–ใ ใจใ‚จใƒฉใƒผใซใชใ‚‹ใฎใงๅˆๆœŸๅŒ–ใ—ใพใ—ใ‚‡ใ†ใ€‚ String localName1 = null; int localValue1 = 0; // ้€šๅธธใฏnullใงๅˆๆœŸๅŒ–ใ›ใšใซใ€ไฝ•ใ‹ใ—ใ‚‰ใฎๅ€คใงๅˆๆœŸๅŒ–ใ—ใพใ™ String localName2 = "LOCAL"; int localValue2 = 200; // ๅ„ๅค‰ๆ•ฐใฎๅ€คใ‚’่กจ็คบใ—ใพใ™ System.out.println("----------------------------------------"); System.out.println("name1=" + name1 + ", value1=" + value1); System.out.println("name2=" + name2 + ", value2=" + value2); System.out.println("localName1=" + localName1 + ", localValue1=" + localValue1); System.out.println("localName2=" + localName2 + ", localValue2=" + localValue2); System.out.println("staticName1=" + staticName1 + ", staticValue1=" + staticValue1); } }
package com.tencent.xweb.c; import android.content.Context; import com.tencent.xweb.WebView; import com.tencent.xweb.WebView.c; import com.tencent.xweb.c.b.a; import com.tencent.xweb.c.b.b; import com.tencent.xweb.g; import org.xwalk.core.WebViewExtensionListener; public interface i$a { h createWebView(WebView webView); Object excute(String str, Object[] objArr); a getCookieManager(); b getCookieSyncManager(); g getJsCore(g.a aVar, Context context); boolean hasInited(); void initCallback(WebViewExtensionListener webViewExtensionListener); void initEnviroment(Context context); void initInterface(); boolean initWebviewCore(Context context, c cVar); }
/** * */ package com.sellsy.apientities; /** * @author yves * */ public class Pagination { private int nbperpage=5; private int pagenum=1; public Pagination( int pagenum ,int nbperpage) { this.nbperpage = nbperpage; this.pagenum = pagenum; } public int getNbperpage() { return nbperpage; } public void setNbperpage(int nbperpage) { this.nbperpage = nbperpage; } public int getPagenum() { return pagenum; } public void setPagenum(int pagenum) { this.pagenum = pagenum; } // @Override // public String toString() { // return "Pagination [nbperpage=" + nbperpage + ", pagenum=" + pagenum + "]"; // } }
package com.ht.entity; import lombok.Data; /** * @company ๅฎๅ›พ * @User Kodak * @create 2019-03-19 -10:07 */ //@Data //ไฝฟ็”จlombokๆ’ไปถ่‡ชๅŠจ็”Ÿๆˆget() set() tostring()ๆ–นๆณ• public class User { private Integer id; private Integer age; private String name; private String email; public User() { } public User(Integer id, Integer age, String name, String email) { this.id = id; this.age = age; this.name = name; this.email = email; } @Override public String toString() { return "User{" + "id=" + id + ", age=" + age + ", name='" + name + '\'' + ", email='" + email + '\'' + '}'; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
package com.yfancy.common.base.enums; /** * ๅพฎไฟก่œๅ•ๆŒ‰้’ฎ็ฑปๅž‹ */ public enum WeixinButtonTypeEnum { click("็‚นๅ‡ป"), view("ๆœ็ดข"), miniprogram("ๅฐ็จ‹ๅบ"), scancode_waitmsg("ๆ‰ซ็ ๆ็คบ"), scancode_push("ๆ‰ซ็ ๆŽจ้€"), pic_sysphoto("็ณป็ปŸๆ‹็…ง"), pic_photo_or_album("็ณป็ปŸๆ‹็…งๆˆ–่€…็›ธๅ†Œๅ‘ๅ›พ"), pic_weixin("ๅพฎไฟก็›ธๅ†Œๅ‘ๅ›พ"), location_select("ๅ‘้€ไฝ็ฝฎ"), media_id("ๅ›พ็‰‡"), view_limited("ๅ›พๆ–‡ๆถˆๆฏ"), ; private String desc; WeixinButtonTypeEnum(String desc) { this.desc = desc; } }
package com.jasoftsolutions.mikhuna.store; import android.support.annotation.Nullable; /** * Created by pc07 on 26/08/2014. * */ public class StoreAdapter implements StoreListener { @Override public void onReady(Object sender, Object data) { } @Override public void onUpdate(Object sender, Object data) { } @Override public void onTimeOut(Object sender, @Nullable Object data) { } @Override public void onFailedConnection(Object sender, @Nullable Object data) { } @Override public void onSuccess(Object sender, Object data) { } @Override public void onFail(Object sender, Object data) { } }
package uptc.softMin.logic.scalability; public class Cl_Atkison { }
package inter; public class MinimumCoinChange1D { public static void main(String[] args) { int[] coins = new int[] { 1, 5, 6, 8 }; int total = 11; int dp[] = new int[total + 1]; dp[0] = 0; for (int i = 1; i < total + 1; i++) { int min = Integer.MAX_VALUE; for (int j = 0; j < coins.length; j++) { if (i >= coins[j]) min = Math.min(min, dp[i - coins[j]]); } dp[i] = min + 1; } for (int i = 0; i < dp.length; i++) { System.out.print(dp[i] + " "); } } }
package navi.common.connector.client; public interface ClientListener { void notifyReceived(byte[] object); void notifyDisconnected(); }
package com.example.android.applicationmovies; import com.example.android.applicationmovies.model.ExtraInfo; import com.example.android.applicationmovies.model.GenreResponse; import com.example.android.applicationmovies.model.Movie; import com.example.android.applicationmovies.model.ReviewResponse; import java.util.ArrayList; import java.util.List; import retrofit2.Call; import retrofit2.http.GET; import retrofit2.http.Path; import retrofit2.http.Query; public interface Api { @GET("movie/popular") Call<ExtraInfo> getPopularMovies(@Query("api_key") String api_key, @Query("language") String language, @Query("page") int page); @GET("genre/movie/list") Call<GenreResponse> getGenres(@Query("api_key") String api_key, @Query("language") String language); @GET("movie/{id}/reviews") Call<ReviewResponse> getReviews(@Path("id") int id, @Query("api_key") String api_key); }
package Controller; import Model.Course; import Model.PageLoader; import Model.Student; import Model.StudentFileStream; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.event.ActionEvent; import javafx.fxml.FXML; import javafx.scene.control.*; import javafx.scene.text.Text; import java.io.IOException; import java.util.List; public class AdminsStudentListViewController { private List<Student> studentList = new StudentFileStream().read(); @FXML public Button backButton, okButton; @FXML public ListView<String> theStudentsNamesList, theStudentsCoursesList; @FXML public Text thePass, theBalance, theGPA; @FXML public TextField studentTextField; public void initialize(){ showStudents(); } private void showStudents(){ ObservableList<String> studentNames = FXCollections.observableArrayList(); for (Student student : studentList) studentNames.add(student.getUsername()); theStudentsNamesList.setItems(studentNames); } public void goBackToHomepage() throws IOException { new PageLoader().loadScene("/View/AdminHomepage.fxml"); } public void showStudentDetails() { String name = studentTextField.getText(); Student student = null; for (Student s : studentList) { if (s.getUsername().equals(name)){ student = s; break; } } if(student != null) { ObservableList<String> studentCourses = FXCollections.observableArrayList(); thePass.setText(student.getPassword()); theBalance.setText(Long.toString(student.getBalance())); theGPA.setText(Float.toString(student.getGPA())); thePass.setVisible(true); theBalance.setVisible(true); theGPA.setVisible(true); for (Course c : student.getCOURSES_TAKEN()) { studentCourses.add("ุงุณู… ฺฉู„ุงุณ: " + c.getName() + " / ูˆุงุญุฏ: " + c.getUnit() + " / ุงุณุชุงุฏ: " + c.getProfessor() + " / ู†ู…ุฑู‡: " + (c.getGrade() == null ? "-" : c.getGrade())); } theStudentsCoursesList.setItems(studentCourses); } } }
package com.example.loginregisterfirebase; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.tasks.OnCompleteListener; import com.google.android.gms.tasks.Task; import com.google.firebase.auth.FirebaseAuth; public class MainActivity extends AppCompatActivity { EditText email,password; Button btnDaftar; TextView tvLogin; FirebaseAuth mFirebaseAuth; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mFirebaseAuth = FirebaseAuth.getInstance(); email = findViewById(R.id.email); password = findViewById(R.id.password); btnDaftar = findViewById(R.id.btnDaftar); tvLogin = findViewById(R.id.linkLogin); btnDaftar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String mail = email.getText().toString(); String pwd = password.getText().toString(); if(mail.isEmpty()){ email.setError("Silahkan Masukan Email"); email.requestFocus(); } else if(pwd.isEmpty()){ password.setError("Silahkan Masukan Password"); password.requestFocus(); } else if(mail.isEmpty() && pwd.isEmpty()){ Toast.makeText(MainActivity.this, "Email dan Password Tidak Boleh Kosong!", Toast.LENGTH_SHORT).show(); } else if(!(mail.isEmpty() && pwd.isEmpty())){ mFirebaseAuth.createUserWithEmailAndPassword(mail,pwd).addOnCompleteListener(MainActivity.this, new OnCompleteListener<com.google.firebase.auth.AuthResult>() { @Override public void onComplete(@NonNull Task<com.google.firebase.auth.AuthResult> task) { if(!task.isSuccessful()){ Toast.makeText(MainActivity.this, "Daftar Gagal, Silahkan Coba Lagi!", Toast.LENGTH_SHORT).show(); } else{ startActivity(new Intent(MainActivity.this, HomeActivity.class)); } } }); } else{ Toast.makeText(MainActivity.this, "Error!", Toast.LENGTH_SHORT).show(); } } }); tvLogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(MainActivity.this, LoginActivity.class); startActivity(i); } }); } }
package com.cnk.travelogix.supplier.credentials.core.interceptors; import de.hybris.platform.servicelayer.interceptor.InterceptorContext; import de.hybris.platform.servicelayer.interceptor.InterceptorException; import de.hybris.platform.servicelayer.interceptor.PrepareInterceptor; import de.hybris.platform.servicelayer.keygenerator.KeyGenerator; import org.apache.log4j.Logger; import com.cnk.travelogix.supplier.credentials.core.indents.model.TicketCappingIndentModel; /** * Prepare interceptor for TicketCappingIndent */ public class TicketCappingIndentPrepareInterceptor implements PrepareInterceptor<TicketCappingIndentModel> { private final Logger log = Logger.getLogger(TicketCappingIndentPrepareInterceptor.class); private KeyGenerator keyGenerator; private static final String CODE_PREFIX = "CAPTKT"; @Override public void onPrepare(final TicketCappingIndentModel ticketCappingIndent, final InterceptorContext context) throws InterceptorException { if (ticketCappingIndent.getCode() == null) { ticketCappingIndent.setCode(CODE_PREFIX + keyGenerator.generate().toString()); log.debug("Set new code for TicketCappingIndentModel -" + ticketCappingIndent.getCode()); } } /** * @return the keyGenerator */ public KeyGenerator getKeyGenerator() { return keyGenerator; } /** * @param keyGenerator * the keyGenerator to set */ public void setKeyGenerator(final KeyGenerator keyGenerator) { this.keyGenerator = keyGenerator; } }
// // GCALDaemon is an OS-independent Java program that offers two-way // synchronization between Google Calendar and various iCalalendar (RFC 2445) // compatible calendar applications (Sunbird, Rainlendar, iCal, Lightning, etc). // // Apache License // Version 2.0, January 2004 // http://www.apache.org/licenses/ // // Project home: // http://gcaldaemon.sourceforge.net // package org.gcaldaemon.api; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.RandomAccessFile; import java.net.URL; import java.util.Properties; import org.gcaldaemon.core.CachedCalendar; import org.gcaldaemon.core.Configurator; import org.gcaldaemon.core.GCalUtilities; import org.gcaldaemon.core.Request; import org.gcaldaemon.core.StringUtils; import org.gcaldaemon.logger.QuickWriter; /** * Embeddable synchronizer engine for Google Calendar. Examples:<br> * <br> * * File workDir = new File("/etc/work");<br> * File localCalendar = new File("/etc/calendar.ics");<br> * URL remoteCalendar = new URL("http://www.google.com/private ical url");<br> * String username = "user@gmail.com";<br> * String password = "gmailpassword";<br> * <br> * * SyncEngine engine = new SyncEngine(workDir);<br> * engine.synchronize(localCalendar, remoteCalendar, username, password);<br> * <br> * * or<br> * <br> * * PDAConnection pda = new PDAConnection("COM3");<br> * File workDir = new File("/etc/work");<br> * byte[] icalBytes = pda.loadCalendar();<br> * URL remoteCalendar = new URL("http://www.google.com/private ical url");<br> * String username = "user@gmail.com";<br> * String password = "gmailpassword";<br> * <br> * * SyncEngine engine = new SyncEngine(workDir);<br> * icalBytes = engine.synchronize(icalBytes, remoteCalendar, username, * password);<br> * pda.saveCalendar(icalBytes);<br> * <br> * * WARNING: SyncEngine is NOT a thread-safe object, so web components such as * Servlets and JSPs should avoid injecting it and storing it as a shared field. * If you wish to use SyncEngine in a multithreaded environment, you will have * to create a static synchronization object or a static synchronization block * to manage a cached instance.<br> * <br> * * SyncEngine utilizes the logging interface provided by the Commons Logging * package. Commons Logging provides a simple and generalized log interface to * various logging packages. By using Commons Logging, SyncEngine can be * configured for a variety of different logging behaviours. That means the * developer will have to make a choice which logging framework to use. To * specify a specific logger be used, set this system property:<br> * <br> * * org.apache.commons.logging.Log<br> * <br> * * to one of:<br> * <li>org.apache.commons.logging.impl.SimpleLog * <li>org.apache.commons.logging.impl.AvalonLogger * <li>org.apache.commons.logging.impl.Jdk13LumberjackLogger * <li>org.apache.commons.logging.impl.Jdk14Logger * <li>org.apache.commons.logging.impl.Log4JLogger * <li>org.apache.commons.logging.impl.LogKitLogger * <li>org.apache.commons.logging.impl.NoOpLog * <li>org.gcaldaemon.logger.DefaultLog<br> * * By default, the SyncEngine will use the DefaultLog framework. DefaultLog is a * simple implementation of the Log interface that sends all log messages to * "System.out". Configuration example: * System.setProperty("org.apache.commons.logging.Log", * "org.apache.commons.logging.impl.Jdk14Logger"); * * Created: Jan 22, 2008 12:50:56 PM * * @author Andras Berkes */ public final class SyncEngine { // --- CONSTANTS --- private static final String GOOGLE_HTTPS_URL = "https://www.google.com"; // --- INTERNAL VARIABLES --- /** * Contains the engine's registry, ToDo items, and backups. */ private File workDir; /** * Container of the engine's configuration. */ private Properties properties; /** * Internal configurator and calendar synchronizer utility (cached * instance). */ private Configurator configurator; /** * Property that indicates the properties in the engine's configuration have * been changed. */ private boolean configChanged; // --- CONSTRUCTORS --- /** * Default constructor, the SyncEngine will use 'USER_HOME/.gcaldaemon' * folder as working directory. * * @throws FileNotFoundException * unable to open or create the 'USER_HOME/.gcaldaemon' * directory (file permission problem) */ public SyncEngine() throws FileNotFoundException { // 'null' means 'USER_HOME/.gcaldaemon' this(null); } /** * Creates a SyncEngine instance with the given working directory. Google * Calendar - unlike Sunbird/Lightning - does not support ToDo (Task) items. * Therefore GCALDaemon stores ToDo items in a local file storage. This * storage is the 'working directory'. * * @param workDir * working directory (contains the engine's registry, ToDo items, * and backups) * * @throws FileNotFoundException * unable to open or create the specified working directory * (file permission problem) */ public SyncEngine(File workDir) throws FileNotFoundException { // Init working directory if (workDir == null) { String home = System.getProperty("user.home"); if (home == null || home.length() == 0) { home = "/"; } workDir = new File(home, ".gcaldaemon"); } if (!workDir.isDirectory() && !workDir.mkdirs()) { // File permission problem throw new FileNotFoundException(String.valueOf(workDir)); } this.workDir = workDir; String workDirPath = workDir.getAbsolutePath(); properties = new Properties(); configChanged = true; // Set default engine properties (synchronizer) properties.put(Configurator.WORK_DIR, workDirPath); properties.put(Configurator.CACHE_TIMEOUT, "180000"); properties.put(Configurator.HTTP_ENABLED, "false"); properties.put(Configurator.PROGRESS_ENABLED, "false"); properties.put(Configurator.SEND_INVITATIONS, "false"); properties.put(Configurator.ICAL_BACKUP_TIMEOUT, "604800000"); properties.put(Configurator.EXTENDED_SYNC_ENABLED, "true"); properties.put(Configurator.REMOTE_ALARM_TYPES, "email,sms,popup"); // Set default engine properties (RSS/ATOM feed converter) try { // Verify classpath Class.forName("com.sun.syndication.io.SyndFeedInput"); // Enable feed converter properties.put(Configurator.FEED_ENABLED, "true"); properties.put(Configurator.FEED_CACHE_TIMEOUT, "3600000"); properties.put(Configurator.FEED_EVENT_LENGTH, "2700000"); properties.put(Configurator.FEED_DUPLICATION_FILTER, "70"); } catch (Throwable ignored) { // Disable feed converter properties.put(Configurator.FEED_ENABLED, "false"); } // Init default logger (DefaultLog). DefaultLog is an implementation of // the Log interface that sends all enabled log messages, for all // defined loggers, to System.out. if (System.getProperty("org.apache.commons.logging.Log") == null) { // You can override this setting with the // "org.apache.commons.logging.Log" system property. // Available log factories: // // 1) org.apache.commons.logging.impl.SimpleLog // 2) org.apache.commons.logging.impl.AvalonLogger // 3) org.apache.commons.logging.impl.Jdk13LumberjackLogger // 4) org.apache.commons.logging.impl.Jdk14Logger // 5) org.apache.commons.logging.impl.Log4JLogger // 6) org.apache.commons.logging.impl.LogKitLogger // 7) org.apache.commons.logging.impl.NoOpLog // 8) org.gcaldaemon.logger.DefaultLog // System.setProperty("org.apache.commons.logging.Log", "org.gcaldaemon.logger.DefaultLog"); } } // --- GOOGLE CALENDAR INFO --- /** * Lists Google Calendars in the account specified by the given * username/password. * * @param username * full name of the user (eg. "username@gmail.com" or * "username@mydomain.org") * @param password * Gmail password (in unencrypted, plain text format) * * @return array of the remote calendars * * @throws Exception * any exception (eg. i/o, invalid param, invalid password) * * @see #loadCalendar * @see #synchronize */ public final RemoteCalendar[] listCalendars(String username, String password) throws Exception { // Verify required parameters if (username == null || username.length() == 0) { throw new NullPointerException("username = null"); } if (username.indexOf('@') == -1) { throw new IllegalArgumentException("invalid username"); } if (password == null || password.length() == 0) { throw new NullPointerException("password = null"); } // Create (or reinitialize) the cached instance if (configChanged) { configChanged = false; if (configurator != null) { configurator.interrupt(); } configurator = new Configurator(null, properties, false, Configurator.MODE_EMBEDDED); } // Create request container Request request = new Request(); request.username = username; request.password = password; // Load paths String[] paths = GCalUtilities.getCalendarURLs(request, workDir); // Convert to RemoteCalendar array RemoteCalendar[] array = new RemoteCalendar[paths.length]; String path; URL url; for (int i = 0; i < paths.length; i++) { path = paths[i]; url = new URL(GOOGLE_HTTPS_URL + path); array[i] = new RemoteCalendar(GCalUtilities.getCalendarName(path, workDir), url); } return array; } // --- GOOGLE CALENDAR LOADER / FEED CONVERTER --- /** * Downloads a specified RSS/ATOM feed and converts it to iCalendar (ICS) * format (or gets from the calendar cache). * * @param feedURL * RSS/ATOM feed's URL (eg. * "http://newsrss.bbc.co.uk/rss/newsonline_uk_edition/sci/tech/rss.xml") * * @return the converted content of the feed in iCalendar format * * @throws Exception * any exception (eg. i/o, invalid param, etc) * * @see #getCacheTimeout * @see #setCacheTimeout */ public final byte[] loadCalendar(URL feedURL) throws Exception { return synchronize((byte[]) null, feedURL, null, null); } /** * Downloads a specified Google Calendar (with ToDo entries) in iCalendar * (ICS) format, or gets from the calendar cache). * * @param remoteCalendar * Google Calendar's private ICAL URL * ("https://www.google.com/calendar/ical/.../basic.ics"), or the * RSS/ATOM feed's URL (= feed converter mode) * @param username * full name of the user (eg. "username@gmail.com" or * "username@mydomain.org"), this value is optional in feed * converter mode * @param password * Gmail password (in unencrypted, plain text format), this value * is optional in feed converter mode * * @return the new, synchronized content of the calendar in iCalendar format * * @throws Exception * any exception (eg. i/o, invalid param, invalid calendar * syntax, etc) * * @see #getCacheTimeout * @see #setCacheTimeout */ public final byte[] loadCalendar(URL remoteCalendar, String username, String password) throws Exception { return synchronize((byte[]) null, remoteCalendar, username, password); } // --- MAIN SYNCHRONIZER / FEED CONVERTER METHODS --- /** * Synchronizes a remote Google Calendar to a local iCalendar (RFC 2445) * file. If the local calendar file does not exists, the SyncEngine will * download and save the original iCalendar file (with ToDo entries) without * any synchronization. Creates daily backups of all Google AND local * calendars into the 'backup' subdirectory (under the working directory). * * @param localCalendar * local calendar file * @param remoteCalendar * Google Calendar's private ICAL URL * ("https://www.google.com/calendar/ical/.../basic.ics"), or the * RSS/ATOM feed's URL (= feed converter mode) * @param username * full name of the user (eg. "username@gmail.com" or * "username@mydomain.org"), this value is optional in feed * converter mode * @param password * Gmail password (in unencrypted, plain text format), this value * is optional in feed converter mode * * @throws Exception * any exception (eg. i/o, invalid param, invalid calendar * syntax, etc) * * @see #getCacheTimeout * @see #setCacheTimeout */ public final void synchronize(File localCalendar, URL remoteCalendar, String username, String password) throws Exception { // Verify required parameters if (localCalendar == null) { throw new NullPointerException("localCalendar = null"); } if (remoteCalendar == null) { throw new NullPointerException("remoteCalendar = null"); } String path = remoteCalendar.getPath(); if (path.endsWith(".ics")) { // Synchronizer mode if (username == null || username.length() == 0) { throw new NullPointerException("username = null"); } if (username.indexOf('@') == -1) { throw new IllegalArgumentException("invalid username"); } if (password == null || password.length() == 0) { throw new NullPointerException("password = null"); } } else { // Feed converter mode checkFeedConverter(); path = remoteCalendar.toString(); } // Load local calendar file byte[] bytes = null; if (localCalendar.isFile()) { RandomAccessFile file = null; try { file = new RandomAccessFile(localCalendar, "r"); bytes = new byte[(int) localCalendar.length()]; file.readFully(bytes); } finally { if (file != null) { file.close(); } } } // Create (or reinitialize) the cached instance if (configChanged) { configChanged = false; configurator = new Configurator(null, properties, false, Configurator.MODE_EMBEDDED); } // Create request container Request request = new Request(); request.body = bytes; request.url = path; request.username = username; request.password = password; request.filePath = localCalendar.getAbsolutePath(); // Do synchronization (if the 'localCalendar' is defined) if (bytes != null && bytes.length != 0) { configurator.synchronizeNow(request); } // Return the modified calendar (with ToDo entries) CachedCalendar calendar = configurator.getCalendar(request); bytes = calendar.toByteArray(); // Save new content into the calendar file FileOutputStream out = null; try { out = new FileOutputStream(localCalendar); out.write(bytes); out.flush(); } finally { if (out != null) { out.close(); } } } /** * Synchronizes a remote Google Calendar to a local iCalendar specified as * an iCalendar (ICS) byte array. Creates daily backups of all Google * Calendars into the 'backup' subdirectory (under the working directory). * * @param localCalendar * bytes of the local calendar in iCalendar format (or null = * downloads calendar without any synchronization, or returns * from the calendar cache) * @param remoteCalendar * Google Calendar's private ICAL URL * ("https://www.google.com/calendar/ical/.../basic.ics"), or the * RSS/ATOM feed's URL (= feed converter mode) * @param username * full name of the user (eg. "username@gmail.com" or * "username@mydomain.org"), this value is optional in feed * converter mode * @param password * Gmail password (in unencrypted, plain text format), this value * is optional in feed converter mode * * @return the new, synchronized content of the calendar, in iCalendar * format * * @throws Exception * any exception (eg. i/o, invalid param, invalid calendar * syntax, etc) * * @see #getCacheTimeout * @see #setCacheTimeout */ public final byte[] synchronize(byte[] localCalendar, URL remoteCalendar, String username, String password) throws Exception { // Verify required parameters if (remoteCalendar == null) { throw new NullPointerException("remoteCalendar = null"); } String path = remoteCalendar.getPath(); if (path.endsWith(".ics")) { // Synchronizer mode if (username == null || username.length() == 0) { throw new NullPointerException("username = null"); } if (username.indexOf('@') == -1) { throw new IllegalArgumentException("invalid username"); } if (password == null || password.length() == 0) { throw new NullPointerException("password = null"); } } else { // Feed converter mode checkFeedConverter(); path = remoteCalendar.toString(); } // Create (or reinitialize) the cached instance if (configChanged) { configChanged = false; configurator = new Configurator(null, properties, false, Configurator.MODE_EMBEDDED); } // Create request container Request request = new Request(); request.body = localCalendar; request.url = path; request.username = username; request.password = password; // Do synchronization (if the 'localCalendar' is defined) if (localCalendar != null && localCalendar.length != 0) { configurator.synchronizeNow(request); } // Return the modified calendar (with ToDo entries) CachedCalendar calendar = configurator.getCalendar(request); return calendar.toByteArray(); } // --- PRIVATE PROPERTY GETTERS/SETTERS --- /** * Puts a String property into the engine's configuration. * * @param key * name of the config property * @param value * value of the config property */ private final void setConfigProperty(String key, String value) { // Compare to the previous value String previous = properties.getProperty(key, ""); if (previous.equals(value)) { return; } // Set new value properties.setProperty(key, value); configChanged = true; } /** * Puts a boolean property into the engine's configuration. * * @param key * name of the config property * @param value * value of the config property * * @see #setConfigProperty */ private final void setConfigProperty(String key, boolean value) { setConfigProperty(key, Boolean.toString(value)); } /** * Puts a numeric (long) property into the engine's configuration. * * @param key * name of the config property * @param value * value of the config property * * @see #setConfigProperty */ private final void setConfigProperty(String key, long value) { setConfigProperty(key, Long.toString(value)); } /** * Sets the value of the 'remote.alarm.types' property. * * @param enableEmail * enables/disables email alerts (or null) * @param enableSMS * enables/disables sms alerts (or null) * @param enablePopup * enables/disables popups (or null) * * @see #setConfigProperty */ private final void setConfigProperty(Boolean enableEmail, Boolean enableSMS, Boolean enablePopup) { String value = properties.getProperty(Configurator.REMOTE_ALARM_TYPES, "email,sms,popup"); boolean email = value.indexOf("mail") != -1; boolean sms = value.indexOf("sms") != -1; boolean popup = value.indexOf("pop") != -1; if (enableEmail != null) { email = enableEmail.booleanValue(); } if (enableSMS != null) { email = enableSMS.booleanValue(); } if (enablePopup != null) { email = enablePopup.booleanValue(); } if (!email && !sms && !popup) { email = true; sms = true; popup = true; } QuickWriter alarm = new QuickWriter(20); if (email) { alarm.write("email,"); } if (sms) { alarm.write("sms,"); } if (popup) { alarm.write("popup,"); } alarm.setLength(alarm.length() - 1); setConfigProperty(Configurator.REMOTE_ALARM_TYPES, alarm.toString()); } /** * Searches for the property with the specified key in the configuration. * The method returns the default value argument if the property is not * found (or empty). * * @param key * name of the config property * @param defaultValue * a default value * * @return the value in the config with the specified key value * * @see #getConfigProperty */ private final String getConfigProperty(String key, String defaultValue) { String value = properties.getProperty(key, defaultValue); if (value == null) { return defaultValue; } else { value = value.trim(); if (value.length() == 0) { return defaultValue; } } return value; } /** * Searches for a boolean property with the specified key in the * configuration. * * @param key * name of the config property * @param defaultValue * default boolean value * * @return the value in the config with the specified key value * * @see #getConfigProperty */ private final boolean getConfigProperty(String key, boolean defaultValue) { String bool = properties.getProperty(key, Boolean.toString(defaultValue)).toLowerCase(); return "true".equals(bool) || "on".equals(bool) || "1".equals(bool); } /** * Searches for a numeric (long) property with the specified key in the * configuration. * * @param key * name of the config property * @param defaultValue * default long value * * @return the value in the config with the specified key value * * @see #getConfigProperty */ private final long getConfigProperty(String key, long defaultValue) { String number = properties .getProperty(key, Long.toString(defaultValue)); try { return StringUtils.stringToLong(number); } catch (Exception ignored) { } return defaultValue; } // --- PUBLIC PROPERTY GETTERS/SETTERS [SYNCHRONIZER] --- /** * Returns the value of the 'cache.timeout' property (= calendar timeout in * the local cache). The default value is '60000'; * * @return cache timeout in milliseconds (eg. 60000 = 1 minute) * * @see #setCacheTimeout * @see #getConfigProperty */ public final long getCacheTimeout() { return getConfigProperty(Configurator.CACHE_TIMEOUT, 60000L); } /** * Sets the value of the 'cache.timeout' property (= calendar timeout in the * local cache). Minimum (and default) value is 60000 milliseconds; * * @param millis * cache timeout in milliseconds (eg. 60000 = 1 minute) * * @see #getCacheTimeout * @see #setConfigProperty */ public final void setCacheTimeout(long millis) { // Verification (60000...n) if (millis < 60000L) { throw new IllegalArgumentException("cache.timeout < 1 min"); } setConfigProperty(Configurator.CACHE_TIMEOUT, millis); } /** * Returns the value of the 'progress.enabled' property (= show animated * progress bar while synching). The default value is 'false'. * * @return true or false (true = enabled) * * @see #setProgressEnabled * @see #getConfigProperty */ public final boolean getProgressEnabled() { return getConfigProperty(Configurator.PROGRESS_ENABLED, false); } /** * Sets the value of the 'progress.enabled' property (= show animated * progress bar while synching). The default value is 'false'. * * @param enable * true or false (true = enabled) * * @see #getProgressEnabled * @see #setConfigProperty */ public final void setProgressEnabled(boolean enable) { setConfigProperty(Configurator.PROGRESS_ENABLED, enable); } /** * Returns the value of the 'send.invitations' property (= Google Calendar * send an email to the attendees to invite them to attend). The default * value is 'false'. * * @return true or false (true = enabled) * * @see #setSendInvitations * @see #getConfigProperty */ public final boolean getSendInvitations() { return getConfigProperty(Configurator.SEND_INVITATIONS, false); } /** * Sets the value of the 'send.invitations' property (= Google Calendar send * an email to the attendees to invite them to attend). The default value is * 'false'. * * @param enable * true or false (true = enabled) * * @see #getSendInvitations * @see #setConfigProperty */ public final void setSendInvitations(boolean enable) { setConfigProperty(Configurator.SEND_INVITATIONS, enable); } /** * Returns the value of the 'ical.backup.timeout' property (= backup file * timeout in the working directory). Default is 604800000 = one week, 0 = * disable backups. * * @return backup timeout in milliseconds (eg. 604800000 = 1 week) * * @see #setIcalBackupTimeout * @see #getConfigProperty */ public final long getIcalBackupTimeout() { return getConfigProperty(Configurator.ICAL_BACKUP_TIMEOUT, 604800000L); } /** * Sets the value of the 'ical.backup.timeout' property (= backup file * timeout in the working directory). Default is 604800000 = one week, 0 = * disable backups. * * @param millis * backup timeout in milliseconds (eg. 604800000 = 1 week) * * @see #getIcalBackupTimeout * @see #setConfigProperty */ public final void setIcalBackupTimeout(long millis) { // Verification (0 or 86400000...n) if (millis < 86400000L && millis != 0) { throw new IllegalArgumentException("ical.backup.timeout < 1 day"); } setConfigProperty(Configurator.ICAL_BACKUP_TIMEOUT, millis); } /** * Returns the value of the 'extended.sync.enabled' property (= enable to * sync alarms, categories, urls, priorities = full synchronization). The * default value is 'true'. * * @return true or false (true = enabled) * * @see #setExtendedSyncEnabled * @see #getConfigProperty */ public final boolean getExtendedSyncEnabled() { return getConfigProperty(Configurator.EXTENDED_SYNC_ENABLED, true); } /** * Sets the value of the 'extended.sync.enabled' property (= enable to sync * alarms, categories, urls, priorities = full synchronization). The default * value is 'true'. * * @param enable * true or false (true = enabled) * * @see #getExtendedSyncEnabled * @see #setConfigProperty */ public final void setExtendedSyncEnabled(boolean enable) { setConfigProperty(Configurator.EXTENDED_SYNC_ENABLED, enable); } /** * Returns true if the Email alarm type is enabled. The default value is * 'true'. * * @return true or false (true = enabled) * * @see #setEmailAlarmsEnabled * @see #getConfigProperty */ public final boolean getEmailAlarmsEnabled() { String value = getConfigProperty(Configurator.REMOTE_ALARM_TYPES, "email,sms,popup"); return (value.indexOf("email") != -1); } /** * Enables/disables the Email alarm type. The default value is 'true'. * * @param enable * true or false (true = enabled) * * @see #getEmailAlarmsEnabled * @see #setConfigProperty */ public final void setEmailAlarmsEnabled(boolean enable) { setConfigProperty(Boolean.valueOf(enable), null, null); } /** * Returns true if the SMS alarm type is enabled. The default value is * 'true'. * * @return true or false (true = enabled) * * @see #setSMSAlarmsEnabled * @see #getConfigProperty */ public final boolean getSMSAlarmsEnabled() { String value = getConfigProperty(Configurator.REMOTE_ALARM_TYPES, "email,sms,popup"); return (value.indexOf("sms") != -1); } /** * Enables/disables the SMS alarm type. The default value is 'true'. * * @param enable * true or false (true = enabled) * * @see #getSMSAlarmsEnabled * @see #setConfigProperty */ public final void setSMSAlarmsEnabled(boolean enable) { setConfigProperty(null, Boolean.valueOf(enable), null); } /** * Returns true if the 'popup' alarm type is enabled. The default value is * 'true'. * * @return true or false (true = enabled) * * @see #setPopupAlarmsEnabled * @see #getConfigProperty */ public final boolean getPopupAlarmsEnabled() { String value = getConfigProperty(Configurator.REMOTE_ALARM_TYPES, "email,sms,popup"); return (value.indexOf("popup") != -1); } /** * Enables/disables the 'popup' alarm type. The default value is 'true'. * * @param enable * true or false (true = enabled) * * @see #getPopupAlarmsEnabled * @see #setConfigProperty */ public final void setPopupAlarmsEnabled(boolean enable) { setConfigProperty(null, null, Boolean.valueOf(enable)); } // --- PUBLIC PROPERTY GETTERS/SETTERS [FEED CONVERTER] --- /** * Make sure the RSS/ATOM converter is available. * * @throws UnsupportedOperationException * feed converter unavailable (missing JARs) */ private final void checkFeedConverter() throws UnsupportedOperationException { if (!getConfigProperty(Configurator.FEED_ENABLED, true)) { throw new UnsupportedOperationException( "feed converter unavailable, check classpath"); } } /** * Returns the value of the 'feed.cache.timeout' property (= timeout of the * RSS files in the memory cache). The default value is '3600000' (= 1 * hour). * * @return cache timeout in milliseconds (eg. 60000 = 1 minute) * * @see #setFeedCacheTimeout * @see #getConfigProperty */ public final long getFeedCacheTimeout() { return getConfigProperty(Configurator.FEED_CACHE_TIMEOUT, 3600000L); } /** * Sets the value of the 'feed.cache.timeout' property (= timeout of the RSS * files in the memory cache). The default value is '3600000' (= 1 hour). * * @param millis * cache timeout in milliseconds (min. 60000 = 1 minute) * * @see #getFeedCacheTimeout * @see #setConfigProperty */ public final void setFeedCacheTimeout(long millis) { // Make sure the RSS/ATOM converter is available checkFeedConverter(); // Verification (60000...n) if (millis < 60000L) { throw new IllegalArgumentException("feed.cache.timeout < 1 min"); } setConfigProperty(Configurator.FEED_CACHE_TIMEOUT, millis); } /** * Returns the value of the 'feed.event.length' property (= length of the * converted feed events in calendar). The default value is '2700000' (= 45 * minutes). * * @return event length in milliseconds (eg. 60000 = 1 minute) * * @see #setFeedEventLength * @see #getConfigProperty */ public final long getFeedEventLength() { return getConfigProperty(Configurator.FEED_EVENT_LENGTH, 2700000L); } /** * Sets the value of the 'feed.event.length' property (= length of the * converted feed events in calendar). The default value is '2700000' (= 45 * minutes). * * @param millis * event length in milliseconds (min 60000 = 1 minute) * * @see #getFeedEventLength * @see #setConfigProperty */ public final void setFeedEventLength(long millis) { // Make sure the RSS/ATOM converter is available checkFeedConverter(); // Verification (60000...n) if (millis < 60000L) { throw new IllegalArgumentException("feed.event.length < 1 min"); } setConfigProperty(Configurator.FEED_EVENT_LENGTH, millis); } /** * Returns the value of the 'feed.duplication.filter' property (= * sensitivity of the RSS duplication filter, 50 = very sensitive, 100 = * disabled). The default value is '70'. * * @return sensitivity (40 - 100) * * @see #setFeedDuplicationFilter * @see #getConfigProperty */ public final int getFeedDuplicationFilter() { return (int) getConfigProperty(Configurator.FEED_DUPLICATION_FILTER, 70); } /** * Sets the value of the 'feed.duplication.filter' property (= sensitivity * of the RSS duplication filter, 50 = very sensitive, 100 = disabled). The * default value is '70'. * * @param percent * sensitivity (40 - 100) * * @see #getFeedDuplicationFilter * @see #setConfigProperty */ public final void setFeedDuplicationFilter(int percent) { // Make sure the RSS/ATOM converter is available checkFeedConverter(); // Verification (40...100) if (percent < 40) { throw new IllegalArgumentException("feed.duplication.filter < 40"); } if (percent > 100) { throw new IllegalArgumentException("feed.duplication.filter > 100"); } setConfigProperty(Configurator.FEED_DUPLICATION_FILTER, percent); } }
package com.tencent.tencentmap.mapsdk.a; class gr$a extends gr { gk d; public gr$a(int i, double... dArr) { super(i, null); a(dArr); } public void a(double... dArr) { super.a(dArr); this.d = (gk) this.c; } /* renamed from: c */ public gr$a clone() { gr$a gr_a = (gr$a) super.a(); gr_a.d = (gk) gr_a.c; return gr_a; } }
package com.wooky.dao; import com.wooky.model.Contact; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import java.util.List; @Stateless public class ContactDao { @PersistenceContext private EntityManager entityManager; public Long save(Contact c) { entityManager.persist(c); return c.getId(); } public void delete(Long id) { final Contact c = entityManager.find(Contact.class, id); if (c != null) { entityManager.remove(c); } } public Contact update(Contact c) { return entityManager.merge(c); } public Contact findById(Long id) { return entityManager.find(Contact.class, id); } public List<Contact> findAll() { final Query query = entityManager.createQuery("SELECT c FROM Contact c"); return query.getResultList(); } public List<Contact> search(String phrase) { final Query query = entityManager.createQuery("SELECT c FROM Contact c WHERE c.name LIKE :phrase OR c.surname LIKE :phrase OR c.email LIKE :phrase").setParameter("phrase", "%"+phrase+"%"); return query.getResultList(); } }
package com.zhonghuilv.shouyin.mapper; import com.zhonghuilv.shouyin.common.CommonMapper; import com.zhonghuilv.shouyin.pojo.StockBack; import org.apache.ibatis.annotations.Mapper; @Mapper public interface StockBackMapper extends CommonMapper<StockBack> { }
package com.tencent.mm.plugin.appbrand.jsapi.audio; import android.text.TextUtils; import com.tencent.mm.g.a.s; import com.tencent.mm.plugin.appbrand.jsapi.e; import com.tencent.mm.plugin.appbrand.l; import com.tencent.mm.sdk.b.a; import com.tencent.mm.sdk.platformtools.x; import com.tencent.mm.z.c; import java.util.HashMap; import java.util.Map; class f$a extends a { public String appId = ""; public String bGW = ""; public int bGX; public int dGB; public String dGC; public int dGs; public int duration = 0; public int eiO; private e fFF; public l fFa; public int fFd; public String fHW; public boolean fHX = false; public f$a(e eVar, l lVar, int i) { this.fFF = eVar; this.fFa = lVar; this.fFd = i; } public final void ahW() { String str = this.bGW; s sVar = new s(); sVar.bGU.action = 6; sVar.bGU.bGW = str; a.sFg.m(sVar); c cVar = sVar.bGV.bHa; if (cVar == null) { x.e("MicroMsg.Audio.JsApiGetAudioState", "return parameter is invalid, audioState is null, audioId:%s", new Object[]{this.bGW}); this.fHX = true; this.fHW = "return parameter is invalid"; En(); } else if (cVar.duration < 0 || cVar.bGX < 0) { x.e("MicroMsg.Audio.JsApiGetAudioState", "return parameter is invalid, duration:%d, currentTime:%d", new Object[]{Integer.valueOf(cVar.duration), Integer.valueOf(cVar.bGX)}); this.fHX = true; this.fHW = "return parameter is invalid"; En(); } else { this.duration = cVar.duration; this.bGX = cVar.bGX; this.eiO = cVar.dGz ? 1 : 0; this.dGC = cVar.dGC; this.dGB = cVar.dGB; this.dGs = cVar.dGs; x.d("MicroMsg.Audio.JsApiGetAudioState", "duration: %d , currentTime: %d ,paused: %d , buffered: %d , src: %s, startTime:%d", new Object[]{Integer.valueOf(this.duration), Integer.valueOf(this.bGX), Integer.valueOf(this.eiO), Integer.valueOf(this.dGB), this.dGC, Integer.valueOf(this.dGs)}); En(); } } public final void En() { if (this.fFa == null) { x.e("MicroMsg.Audio.JsApiGetAudioState", "service is null"); return; } Map hashMap = new HashMap(); hashMap.put("duration", Integer.valueOf(this.duration)); hashMap.put("currentTime", Integer.valueOf(this.bGX)); hashMap.put("paused", Boolean.valueOf(this.eiO == 1)); hashMap.put("buffered", Integer.valueOf(this.dGB)); hashMap.put("src", this.dGC); hashMap.put("startTime", Integer.valueOf(this.dGs)); String str = TextUtils.isEmpty(this.fHW) ? "" : this.fHW; if (this.fHX) { x.e("MicroMsg.Audio.JsApiGetAudioState", "getAudioState fail, err:%s", new Object[]{str}); this.fFa.E(this.fFd, this.fFF.f("fail:" + str, null)); return; } this.fFa.E(this.fFd, this.fFF.f("ok", hashMap)); } }
package com.nagainfo.myapplication; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import com.android.volley.Response; import org.json.JSONObject; import java.util.ArrayList; import java.util.List; /** * Created by nagainfo on 30/3/16. */ public class InsertData extends SQLiteOpenHelper { private static int DB_VERSION =1; private static String DB_NAME ="web"; private static String TABLE_NAME ="film"; private static String ID ="_id"; private static String TITLE ="title"; private static String IMG ="image"; public InsertData(Context context, String name, SQLiteDatabase.CursorFactory factory, int version) { super(context, DB_NAME,null,DB_VERSION); } public InsertData(Context con){ super(con,DB_NAME,null,DB_VERSION); } @Override public void onCreate(SQLiteDatabase db) { String create_qry = "CREATE TABLE TEST (id INTEGER PRIMARY KEY)"; String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_NAME + "(" + ID + " INTEGER PRIMARY KEY," + TITLE + " TEXT," + IMG + " TEXT" + ")"; db.execSQL(CREATE_CONTACTS_TABLE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); } public void addData(Data data){ SQLiteDatabase db=this.getWritableDatabase(); ContentValues contentValues =new ContentValues(); contentValues.put(TITLE,data.getTitle()); contentValues.put(IMG,data.getImg()); long id=db.insert(TABLE_NAME, null, contentValues); db.close(); } public List<Data> getSavedData(String search_val){ List<Data> savedData =new ArrayList<Data>(); String select_qry ="SELECT * FROM "+TABLE_NAME + " WHERE "+ TITLE +"= "+search_val; SQLiteDatabase db=this.getWritableDatabase(); Cursor cursor =db.rawQuery(select_qry,null); if(cursor.moveToFirst()){ do { Data data=new Data(); data.setTitle(cursor.getString(1)); data.setTitle(cursor.getString(2)); savedData.add(data); }while (cursor.moveToNext()); } return savedData; } }
package javabasico.aula19labs; import java.util.Scanner; /** * @author Kim Tsunoda * Objetivo Ler um vetor A com 20 elementos. Separar os elementos pares e รญmpares de A utilizando apenas um vetor extra B. Sugestรฃo: no inรญcio do vetor B armazene os elementos pares * de A e nas posiรงรตes restantes do vetor B armazene os elementos de A que sรฃo รญmpares. */ public class Exercicio31 { public static void main(String[] args) { Scanner scan = new Scanner (System.in); int[] vetorA = new int[20]; int[] vetorB = new int[vetorA.length]; int posB =0; for (int i=0; i <vetorA.length; i++) { System.out.println("Digite um valor para o vetor A posicao " + i); vetorA[i] = scan.nextInt(); } for (int i=0 ; i < vetorA.length ; i++) { if (vetorA[i] % 2 ==0) { vetorB [posB] = vetorA[i]; posB ++; } } for (int i=0 ; i < vetorA.length ; i++) { if (vetorA[i] % 2 !=0) { vetorB [posB] = vetorA[i]; posB ++; } } System.out.print("Vetor A "); for (int i=0 ; i < vetorA.length ; i++) { System.out.print(vetorA [i] + " "); } System.out.println(""); System.out.print("Vetor B "); for (int i=0 ; i < posB ; i++) { System.out.print(vetorB [i] + " "); } } }
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2017.01.28 at 02:10:24 PM CST // package org.mesa.xml.b2mml; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for LinkType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="LinkType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="ID" type="{http://www.mesa.org/xml/B2MML-V0600}IDType"/> * &lt;element name="FromID" type="{http://www.mesa.org/xml/B2MML-V0600}FromIDType" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="ToID" type="{http://www.mesa.org/xml/B2MML-V0600}ToIDType" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="LinkType" type="{http://www.mesa.org/xml/B2MML-V0600}LinkTypeType"/> * &lt;element name="Depiction" type="{http://www.mesa.org/xml/B2MML-V0600}DepictionType"/> * &lt;element name="EvaluationOrder" type="{http://www.mesa.org/xml/B2MML-V0600}EvaluationOrderType" minOccurs="0"/> * &lt;element name="Description" type="{http://www.mesa.org/xml/B2MML-V0600}DescriptionType" maxOccurs="unbounded" minOccurs="0"/> * &lt;group ref="{http://www.mesa.org/xml/B2MML-V0600-AllExtensions}Link" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "LinkType", propOrder = { "id", "fromID", "toID", "linkType", "depiction", "evaluationOrder", "description" }) public class LinkType { @XmlElement(name = "ID", required = true) protected IDType id; @XmlElement(name = "FromID") protected List<FromIDType> fromID; @XmlElement(name = "ToID") protected List<ToIDType> toID; @XmlElement(name = "LinkType", required = true) protected LinkTypeType linkType; @XmlElement(name = "Depiction", required = true) protected DepictionType depiction; @XmlElement(name = "EvaluationOrder") protected EvaluationOrderType evaluationOrder; @XmlElement(name = "Description") protected List<DescriptionType> description; /** * Gets the value of the id property. * * @return * possible object is * {@link IDType } * */ public IDType getID() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link IDType } * */ public void setID(IDType value) { this.id = value; } /** * Gets the value of the fromID property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the fromID property. * * <p> * For example, to add a new item, do as follows: * <pre> * getFromID().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link FromIDType } * * */ public List<FromIDType> getFromID() { if (fromID == null) { fromID = new ArrayList<FromIDType>(); } return this.fromID; } /** * Gets the value of the toID property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the toID property. * * <p> * For example, to add a new item, do as follows: * <pre> * getToID().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ToIDType } * * */ public List<ToIDType> getToID() { if (toID == null) { toID = new ArrayList<ToIDType>(); } return this.toID; } /** * Gets the value of the linkType property. * * @return * possible object is * {@link LinkTypeType } * */ public LinkTypeType getLinkType() { return linkType; } /** * Sets the value of the linkType property. * * @param value * allowed object is * {@link LinkTypeType } * */ public void setLinkType(LinkTypeType value) { this.linkType = value; } /** * Gets the value of the depiction property. * * @return * possible object is * {@link DepictionType } * */ public DepictionType getDepiction() { return depiction; } /** * Sets the value of the depiction property. * * @param value * allowed object is * {@link DepictionType } * */ public void setDepiction(DepictionType value) { this.depiction = value; } /** * Gets the value of the evaluationOrder property. * * @return * possible object is * {@link EvaluationOrderType } * */ public EvaluationOrderType getEvaluationOrder() { return evaluationOrder; } /** * Sets the value of the evaluationOrder property. * * @param value * allowed object is * {@link EvaluationOrderType } * */ public void setEvaluationOrder(EvaluationOrderType value) { this.evaluationOrder = value; } /** * Gets the value of the description property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the description property. * * <p> * For example, to add a new item, do as follows: * <pre> * getDescription().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link DescriptionType } * * */ public List<DescriptionType> getDescription() { if (description == null) { description = new ArrayList<DescriptionType>(); } return this.description; } }
package learn.kidsapp.learnmath.memorygame; import android.widget.ImageView; public class MemoryCard { public int x; public int y; public ImageView button; public MemoryCard(ImageView button, int x, int y) { this.x = x; this.y=y; this.button=button; } }
package com.alfred.codingchallenge.repositories; import com.alfred.codingchallenge.model.Transaction; import org.springframework.data.repository.PagingAndSortingRepository; import org.springframework.data.repository.query.Param; import org.springframework.data.rest.core.annotation.RepositoryRestResource; import java.util.List; @RepositoryRestResource(collectionResourceRel = "transactions", path = "transactions") public interface TransactionRepository extends PagingAndSortingRepository<Transaction, Long> { List<Transaction> findBySourceAccountId(@Param("sourceAccountId") Long sourceAccountId); }
package sampleServiceImpl; public class HampHealthPlanImpl implements HealthPlan { @Override public boolean planProgramLogic(Summary summary) { if (summary instanceof HAMPSummary) { HAMPSummary hampSummary = (HAMPSummary) summary; return checkAndCondition(hampSummary) && checkOrCondition(hampSummary); } return false; } private boolean checkAndCondition(HAMPSummary hampSummary) { return hampSummary.getP10MimpctCost() >=P10M_IMPACTABLE_COSTS_HAMP && CollectionUtils.isEmpty(hampSummary.getMedEx()) && !hampSummary.isHasCostsRelatedToSingleSurgery() && !hampSummary.isInHospice() && hampSummary.isAMemberOfCarleBh(); } private boolean checkOrCondition(HAMPSummary hampSummary) { return hampSummary.isHasDxOfAnxiety() || hampSummary.isHasDxOfDepresion() || hampSummary.isHasDxOfSud() || hampSummary.getRingsSudProbability() >= PROBSUD_HAMP|| hampSummary.getRingsDepressionProbability() >= PROBDEP_HAMP; } }
import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class ThreadTest implements Runnable { static StringBuilder message = new StringBuilder("Hello"); public void methodOne(StringBuilder message) { message.append(" World"); ExecutorService executor = Executors.newSingleThreadExecutor(); executor.execute(this); executor.execute(this); } public void run() { for (int i = 0; i < 2; i++) { try { Thread.sleep(1000); } catch (InterruptedException ex) { } message.append(" " + i); } } public static void main(String args[]) { ThreadTest t = new ThreadTest(); t.methodOne(message); try { Thread.sleep(8000); } catch (InterruptedException ex) { } catch (NumberFormatException ex) { } System.out.println(message); } }
package server.tasks; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import server.externalapi.CurrencyConverter; /** * Automated task to update the FXRates stored in the Database */ @Component public class UpdateFXRateTask { /** * Schedules a task to update the FXRate table at 3AM every morning */ @Scheduled(fixedDelay = 36000000, initialDelay = 10000) public void updateFXRates() { System.out.println("Updating Rates now"); CurrencyConverter.updateRates(); } }
package com.example.hp.above; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.TextView; import org.w3c.dom.Text; public class HashingActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_hashing); getSupportActionBar().setDisplayHomeAsUpEnabled(true); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; } return super.onOptionsItemSelected(item); } public boolean onCreateOptionsMenu(Menu menu) { return true; } public void hash_more(View view) { TextView previewText = (TextView) findViewById(R.id.hash_more); previewText.setText("\n\nComparison of above three:\n" + "\n\nLinear probing has the best cache performance, but suffers from clustering. One more advantage of Linear probing is easy to compute.\n" + "\nQuadratic probing lies between the two in terms of cache performance and clustering.\n" + "\n\nDouble hashing has poor cache performance but no clustering. Double hashing requires more computation time as two hash functions need to be computed.\n" + "\n\nOpen Addressing vs. Separate Chaining\n" + "\n1) Chaining is Simpler to implement.\n" + "\n2) In chaining, Hash table never fills up, we can always add more elements to chain. In open addressing, table may become full.\n" + "\n3) Chaining is Less sensitive to the hash function or load factors.\n" + "\n4) Chaining is mostly used when it is unknown how many and how frequently keys may be inserted or deleted.\n" + "\n5) Open addressing requires extra care for to avoid clustering and load factor.\n" + "\n\nAdvantages of Separate Chaining:\n" + "\n1) Simple to implement.\n" + "\n2) Hash table never fills up, we can always add more elements to chain.\n" + "\n3) Less sensitive to the hash function or load factors.\n" + "\n4) It is mostly used when it is unknown how many and how frequently keys may be inserted or deleted.\n" + "\n\nDisadvantages of Separate Chaining:\n" + "\n1) Cache performance of chaining is not good as keys are stored using linked list. Open addressing provides better cache performance as everything is stored in same table.\n" + "\n2) Wastage of Space (Some Parts of hash table are never used)\n" + "\n3) If the chain becomes long, then search time can become O(n) in worst case.\n" + "\n4) Uses extra space for links.\n" + "\n" + "\n" + "\nPerformance of Chaining:\n" + "\nPerformance of hashing can be evaluated under the assumption that each key is equally likely to be hashed to any slot of table (simple uniform hashing).\n" + "\n m = Number of slots in hash table\n" + "\n n = Number of keys to be inserted in has table\n" + " \n" + "\n Load factor ฮฑ = n/m \n" + " \n" + "\n Expected time to search = O(1 + ฮฑ)\n" + " \n" + "\n Expected time to insert/delete = O(1 + ฮฑ)\n" + "\n" + "\n Time complexity of search insert and delete is \n" + "\n O(1) if ฮฑ is O(1)" + "\nAdvantages of Open Addressing\n" + "\n1) Cache performance of chaining is not good as keys are stored using linked list. Open addressing provides better cache performance as everything is stored in same table.\n" + "\n2) Wastage of Space (Some Parts of hash table in chaining are never used). In Open addressing, a slot can be used even if an input doesnโ€™t map to it.\n" + "\n3) Chaining uses extra space for links.\n" + "\n\nPerformance of Open Addressing:\n" + "\n\nLike Chaining, performance of hashing can be evaluated under the assumption that each key is equally likely to be hashed to any slot of table (simple uniform hashing)\n" + "\n m = Number of slots in hash table\n" + "\n n = Number of keys to be inserted in has table\n" + " \n" + "\n Load factor ฮฑ = n/m ( < 1 )\n" + "\n" + "\n Expected time to search/insert/delete < 1/(1 - ฮฑ) \n" + "\n" + "\n So Search, Insert and Delete take (1/(1 - ฮฑ)) time"); } }
package mop.main.java.backend.utilities; import java.lang.reflect.Method; public class MethodGenerator { public static <T> Method generatePrimaryKeyAccessor(T type) throws NoSuchMethodException { return type.getClass().getMethod("get" + type.getClass().getSimpleName() + "Id"); } }
package org.github.chajian.matchgame.data; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; /** * ็งฏๅˆ† * ไธป้”ฎ ๆธธๆˆid๏ผŒ็”จๆˆทๅ * @author Chajian * */ @Data public class IntegralPO { int id; /*็Žฉๅฎถๅ*/ String playerName; /*ๆธธๆˆไปฃ็ */ String gameId; /*็งฏๅˆ†*/ int score; /*่ƒœๅœบ*/ int wins; /*่ดฅๅœบ*/ int losers; }
package tools.misc.container; import org.apache.commons.io.FileUtils; import java.io.File; import static org.hamcrest.CoreMatchers.is; import static org.junit.Assert.assertThat; /** * User: jiangyixin.stephen * Date: 2013-06-24 11:31 */ public class ReloadableHolderTest { @org.junit.Test public void testPut() throws Exception { ReloadableHolder holder = new ReloadableHolder(); File f = File.createTempFile("test", "txt"); FileUtils.write(f, "test", "UTF-8"); holder.put("test", f); assertThat(new String((byte[])holder.get("test")), is("test")); } @org.junit.Test public void testGet() throws Exception { ReloadableHolder holder = new ReloadableHolder(); File f = File.createTempFile("test", "txt"); FileUtils.write(f, "test", "UTF-8"); holder.put("test", f); assertThat(new String((byte[])holder.get("test")), is("test")); Thread.sleep(100); FileUtils.write(f, "test1", "UTF-8"); assertThat(new String((byte[])holder.get("test")), is("test1")); } }
package com.semantyca.nb.core.service; import com.semantyca.nb.core.dataengine.jpa.IAppEntity; import com.semantyca.nb.core.dataengine.jpa.model.constant.ExistenceState; import com.semantyca.nb.core.rest.outgoing.Outcome; import com.semantyca.nb.core.user.IUser; import com.semantyca.nb.logger.Lg; import javax.ws.rs.*; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.ParameterizedType; public abstract class AbstractReferenceService<T extends IAppEntity> extends AbstractService<T> { @GET @Path("{identifier}") @Produces(MediaType.APPLICATION_JSON) @Consumes(MediaType.APPLICATION_JSON) public Response get(@PathParam("identifier") String identifier) { Outcome outcome = new Outcome(); T entity = null; if ("new".equalsIgnoreCase(identifier)) { entity = composeNew(session.getUser()); } else { try { entity = getDao().findByIdentifier(identifier); outcome.setTitle("Status " + entity.getIdentifier()); } catch (Exception e) { return Response.status(Response.Status.NOT_FOUND).build(); } } outcome.addPayload(entity); return Response.ok(outcome).build(); } protected T composeNew(IUser user) { try { Class<T> entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; T entityInst = entityClass.getConstructor().newInstance(); entityInst.setAuthor(user.getId()); entityInst.setTitle(entityClass.getTypeName()); entityInst.setExistenceState(ExistenceState.NOT_SAVED); return entityInst; } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { Lg.exception(e); } return null; } }
package vmesnik; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; //import java.awt.List; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.util.LinkedList; import javax.swing.JPanel; import igra.Igra; import igra.Igralec; import igra.Lokacija; import igra.Plosca; import igra.Polje; import igra.Poteza; import igra.Stanje; @SuppressWarnings("serial") public class IgralnoPolje extends JPanel implements MouseListener { //ta class bo narisal plos๏ฟฝo in figurice, ograjice, poslu๏ฟฝal kam bo kdo kliknil, //TODO polmer, debelina in stranica se prilagajajo glede na velikost vmesnika, ki jo je izbral uporabnik (sprotno racunanje) protected GlavnoOkno master; protected Color barvaFiguric; protected int polmer; //polmer figuric protected int stranica; //dolzina kvadratka, ki predstavlja polje protected Lokacija izbrana; //v tem razredu potrebujemo izbrano lokacijo, saj jo bomo obarvali in narisali njene mozne premike protected int debelina; // predstavlja debelino crte na eni strani kvadratka /** * konstruktor * @param master */ public IgralnoPolje(GlavnoOkno master) { super(); //konstruktor od JPanel setBackground(Color.white); this.master = master; this.addMouseListener(this); stranica = 100; debelina = stranica / 8; polmer = 5; } /** * Velikost panela vsakic ko odpremo okno. */ @Override public Dimension getPreferredSize() { return new Dimension((master.getDim() + 1) * stranica, (master.getDim() + 1) *stranica); } @Override protected void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2 = (Graphics2D)g; int dim = master.getDim(); // crte g2.setColor(Color.BLACK); for (int i = 0; i < dim + 1; i++) { g2.drawLine(0, i * stranica, stranica * dim, i * stranica); g2.drawLine(i * stranica, 0, i * stranica, stranica * dim); } // krozci in krozci Plosca plosca = master.getPlosca(); if (plosca != null) { for (int i = 0; i < Igra.DIM; i++) { for (int j = 0; j < Igra.DIM; j++) { switch(plosca.getVsa_polja()[i][j]) { case BELO: narisiFigurico(g2, Igralec.BELI, i, j); break; case CRNO: narisiFigurico(g2, Igralec.CRNI, i, j); break; default: break; } } } } //drugace obarvaj izbrano: if (izbrana != null) { narisiFigurico(g2, null, izbrana.getY(), izbrana.getX()); pobarvajMozne(g2, izbrana); } //narisemo ograjice: narisiOgrajice(g2, master.getPlosca().getOgrajiceVod(), master.getPlosca().getOgrajiceNavp()); } private void narisiFigurico(Graphics g, Igralec igralec, int vrstica, int stolpec ) { //narisemo figurico na doloceno polje dolocene barve int polmer = stranica / 2; if (igralec == Igralec.CRNI) { barvaFiguric = new Color(50,50,50); } else if (igralec == Igralec.BELI) { barvaFiguric = new Color(250,250,250); } else{ // to je ko je igralec null - za izbrano barvaFiguric = Color.BLUE; } g.setColor(barvaFiguric); g.fillOval(stolpec * stranica + polmer /2, vrstica * stranica + polmer/2, polmer, polmer); if(igralec == Igralec.BELI) { g.setColor(Color.BLACK); g.drawOval(stolpec * stranica + polmer /2, vrstica * stranica + polmer/2, polmer, polmer); } } private void pobarvajMozne(Graphics g, Lokacija p){ java.util.List<Poteza> mozne = GlavnoOkno.getMozne(p); g.setColor(Color.cyan); for (Poteza l : mozne){ g.fillRect(l.getKoncna().getX()*stranica, l.getKoncna().getY()*stranica, stranica, stranica); } } private void narisiOgrajice(Graphics g, int[][] vodoravne, int [][] navpicne) { for (int i = 0; i < navpicne.length;i++) { int[] vrstica = navpicne[i]; for (int j = 0; j < vrstica.length; j++) { int stOgrajic = vrstica[j]; if(stOgrajic != 0) { if(stOgrajic == 1) { g.setColor(Color.BLUE); g.fillRect(j*stranica - debelina / 2, i*stranica, debelina, stranica); } if(stOgrajic == 2) { g.setColor(Color.BLUE); g.fillRect(j*stranica - debelina / 2, i*stranica, debelina, stranica); g.setColor(Color.RED); g.fillRect(j*stranica - debelina / 4, i*stranica, debelina / 2, stranica); } } } } for (int i = 0; i < vodoravne.length;i++) { int[] vrstica = vodoravne[i]; for (int j = 0; j < vrstica.length; j++) { int stOgrajic = vrstica[j]; if(stOgrajic == 1) { g.setColor(Color.BLUE); g.fillRect(j*stranica, i*stranica - debelina / 2, stranica, debelina); } else if(stOgrajic == 2) { g.setColor(Color.BLUE); g.fillRect(j*stranica, i*stranica - debelina / 2, stranica, debelina); g.setColor(Color.RED); g.fillRect(j*stranica, i*stranica - debelina / 4, stranica, debelina / 2 ); } } } } //@SuppressWarnings("unlikely-arg-type") @Override public void mouseClicked(MouseEvent e) { if (master.getStrateg().uporabljaGUI()) { Lokacija lokacija = null; int x = e.getX(); int y = e.getY(); int i = x / stranica; int j = y /stranica; if (!(x % stranica < debelina || stranica - x % stranica < debelina) && !(y% stranica < debelina || stranica - y % stranica < debelina) ){ //pogoj1: nisi kliknil na ograjico lokacija = new Lokacija(i,j); } if (lokacija != null){ if (izbrana == null) { if((master.getStanje() == Stanje.BELI_NA_POTEZI && master.getPlosca().getVsa_polja()[j][i] == Polje.BELO) || (master.getStanje() == Stanje.CRNI_NA_POTEZI && master.getPlosca().getVsa_polja()[j][i] == Polje.CRNO)) { izbrana = lokacija; } else { izbrana = null; } } else if (izbrana.equals(lokacija)) { izbrana = null; } else { LinkedList<Poteza> mozne = GlavnoOkno.getMozne(izbrana); if (mozne.contains(new Poteza(izbrana, lokacija))){ master.klikniPolje(new Poteza(izbrana, lokacija)); } izbrana = null; } } repaint(); } } @Override public void mouseEntered(MouseEvent e) { } @Override public void mouseExited(MouseEvent e) { } @Override public void mousePressed(MouseEvent e) { } @Override public void mouseReleased(MouseEvent e) { } }
package it.euris.EurisTest.model; public class Costo { private int pence; private int shilling; private int pound; /* * la classe Costo รจ utilizzata per semplificare i calcoli sui prezzi degli articoli * il costruttore prende come parametro una stringa che avrร  come formato "Xp Ys Zd" * con le operazioni effettuate su questa stringa andrร  a inserire i valori nelle proprietร  * */ public Costo(String costo) { super(); String[] temp = costo.split(" "); pound = estraiNumero(temp[0]); shilling = estraiNumero(temp[1]); pence = estraiNumero(temp[2]); } //il metodo estraiNumero rimuove le lettere poste alla fine della stringa in modo da avere solo il valore numerico private int estraiNumero(String string) { return Integer.parseInt(string.substring(0, string.length() - 1)); } //trasforma tutto in pence in modo da effettuare i calcoli su questi private int toPence() { return pound * 240 + shilling * 12 + pence; } //una volta effettuati i calcoli sui pence inserisce i nuovi valori nelle proprietร  di Costo private Costo fromPence(int pence){ shilling = pence / 12; this.pence = pence % 12; pound = shilling / 20; shilling = shilling % 20; return this; } // restituisce una nuova stringa in formato "Xp Ys Zd" public String toString() {; return pound+"p "+shilling+"s "+pence+"d"; } public Costo somma(Costo addendo) { int somma =addendo.toPence() + this.toPence(); Costo ris = fromPence(somma); return ris; } public Costo sottrai (Costo sottraendo) { int sottrazione; //controllo che non venga fatta una sottrazione con risultato negativo if(sottraendo.toPence() > this.toPence()) { sottrazione = sottraendo.toPence() - this.toPence(); } else { sottrazione = this.toPence() +- sottraendo.toPence(); } Costo ris = fromPence(sottrazione); return ris; } public Costo moltiplica (int fattore) { int moltiplicazione = this.toPence() * fattore; Costo ris = fromPence(moltiplicazione); return ris; } public String dividi(int divisore) { Costo ris = fromPence(this.toPence() / divisore); Costo resto = fromPence(this.toPence() % divisore); return ris.toString()+" ("+resto.toString()+")"; } }
package com.nhatdear.sademo.activities; import android.annotation.SuppressLint; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.util.Log; import android.view.KeyEvent; import android.widget.Toast; import com.nhatdear.sademo.R; import com.facebook.AccessToken; import com.facebook.CallbackManager; import com.facebook.FacebookCallback; import com.facebook.FacebookException; import com.facebook.FacebookSdk; import com.facebook.login.LoginManager; import com.facebook.login.LoginResult; import com.google.firebase.auth.AuthCredential; import com.google.firebase.auth.FacebookAuthProvider; import com.google.firebase.auth.FirebaseAuth; import com.google.firebase.auth.FirebaseUser; import com.google.firebase.database.DataSnapshot; import com.google.firebase.database.DatabaseError; import com.google.firebase.database.ValueEventListener; import com.nhatdear.sademo.StashAwayApp; import com.nhatdear.sademo.events.SA_ErrorEvent; import com.nhatdear.sademo.fragments.SA_LoginFragment; import com.nhatdear.sademo.fragments.SA_ResetPasswordFragment; import com.nhatdear.sademo.fragments.SA_SignUpFragment; import com.nhatdear.sademo.fragments.SA_SimpleDialogFragment; import com.nhatdear.sademo.fragments.SA_WelcomeFragment; import com.nhatdear.sademo.helpers.SA_Helper; import com.nhatdear.sademo.models.SA_User; import org.greenrobot.eventbus.EventBus; import java.util.Arrays; import static com.nhatdear.sademo.helpers.SA_Helper.LAST_ACCOUNT; import static com.nhatdear.sademo.helpers.SA_Helper.LAST_USERNAME; public class SA_LoginActivity extends SA_BaseActivity implements SA_LoginFragment.OnFragmentInteractionListener, SA_SignUpFragment.OnFragmentInteractionListener, SA_WelcomeFragment.OnFragmentInteractionListener, SA_ResetPasswordFragment.OnFragmentInteractionListener { private static final String TAG = SA_LoginActivity.class.getSimpleName(); private CallbackManager callbackManager; private boolean firstInit = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); FacebookSdk.sdkInitialize(this.getApplicationContext()); setContentView(R.layout.activity_login); callbackManager = CallbackManager.Factory.create(); LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() { @SuppressLint("CommitTransaction") @Override public void onSuccess(LoginResult loginResult) { getSupportFragmentManager().beginTransaction(); SA_SimpleDialogFragment fragment = SA_SimpleDialogFragment.newInstance(); fragment.addOnBtnOkClickListener(s -> { handleFacebookAccessToken(loginResult.getAccessToken(), s); fragment.dismiss(); }); fragment.addOnBtnCancelClickListener(() -> { Log.d(TAG, "FB Sign out!!!"); LoginManager.getInstance().logOut(); FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction().replace(R.id.fragment_container, SA_WelcomeFragment.newInstance()).addToBackStack("WELCOME"); fragmentTransaction.commit(); fragment.dismiss(); hideProgressDialog(); }); fragment.show(getSupportFragmentManager(), "DIALOG"); } @Override public void onCancel() { hideProgressDialog(); Log.d(TAG, "facebook cancel"); handleFacebookError(new Exception("Cancel by User !!!")); } @Override public void onError(FacebookException exception) { hideProgressDialog(); handleFacebookError(exception); Log.d(TAG, "facebook error " + exception.toString()); } }); // [START initialize_auth] mAuth = FirebaseAuth.getInstance(); // [END initialize_auth] // [START auth_state_listener] mAuthListener = firebaseAuth -> { FirebaseUser user = firebaseAuth.getCurrentUser(); if (user != null) { // User is signed in Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid()); if (firstInit) { goToMain(); } } else { // User is signed out Log.d(TAG, "onAuthStateChanged:signed_out"); } firstInit = false; }; // [END auth_state_listener] // Check last account exist SharedPreferences sharedPreferences = getSharedPreferences(SA_Helper.USER_PREF, MODE_PRIVATE); String lastAccount = sharedPreferences.getString(LAST_ACCOUNT, ""); if (SA_Helper.softCheckValidString(lastAccount)) { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction2 = fragmentManager.beginTransaction().replace(R.id.fragment_container, SA_WelcomeFragment.newInstance()).addToBackStack("WELCOME"); fragmentTransaction2.commit(); fragmentManager.executePendingTransactions(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction().replace(R.id.fragment_container, SA_LoginFragment.newInstance(lastAccount)).addToBackStack("LOGIN"); fragmentTransaction.commit(); } else { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction2 = fragmentManager.beginTransaction().replace(R.id.fragment_container, SA_WelcomeFragment.newInstance()).addToBackStack("WELCOME"); fragmentTransaction2.commit(); fragmentManager.executePendingTransactions(); } } @SuppressWarnings("ConstantConditions") private void goToMain() { showProgressDialog("Loading User Informations"); FirebaseUser user = mAuth.getCurrentUser(); SA_LoginActivity _this = this; ValueEventListener postListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { SA_User sa_user = dataSnapshot.getValue(SA_User.class); StashAwayApp.getInstance().setCurrentUser(sa_user); saveUserInformation(sa_user); SA_Helper.goToMainWithClearFlag(SA_LoginActivity.this); } @Override public void onCancelled(DatabaseError databaseError) { _this.hideProgressDialog(); } }; SA_User.load(user.getUid(),postListener); } @SuppressWarnings("ThrowableResultOfMethodCallIgnored") private void createAccount(String userName, String email, String password) { Log.d(TAG, "createAccount:" + email); showProgressDialog(); // [START create_user_with_email] mAuth.createUserWithEmailAndPassword(email, password) .addOnCompleteListener(this, task -> { Log.d(TAG, "createUserWithEmail:onComplete:" + task.isSuccessful()); // 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()) { //noinspection ConstantConditions Log.e(TAG, task.getException().getMessage()); SA_Helper.showSnackbar(SA_LoginActivity.this.findViewById(R.id.fragment_container), task.getException().getMessage()); hideProgressDialog(); } else { FirebaseUser firebaseUser = mAuth.getCurrentUser(); SA_User user = new SA_User(firebaseUser); user.name = userName; user.nameLowerCase = userName.toLowerCase(); user.save().addOnCompleteListener(saveTask -> signIn(email, password)); } }); // [END create_user_with_email] } private void signIn(String email, String password) { Log.d(TAG, "signIn:" + email); showProgressDialog(); // [START sign_in_with_email] mAuth.signInWithEmailAndPassword(email, password) .addOnCompleteListener(this, task -> { Log.d(TAG, "signInWithEmail:onComplete:" + task.isSuccessful()); // 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()) { Log.w(TAG, "signInWithEmail:failed", task.getException()); Toast.makeText(SA_LoginActivity.this, R.string.auth_failed, Toast.LENGTH_SHORT).show(); } else { goToMain(); } hideProgressDialog(); }); // [END sign_in_with_email] } private void saveUserInformation(SA_User sa_user) { SharedPreferences sharedPreferences = getSharedPreferences(SA_Helper.USER_PREF, MODE_PRIVATE); sharedPreferences.edit().putString(LAST_ACCOUNT, sa_user.getEmail()).apply(); sharedPreferences.edit().putString(LAST_USERNAME, sa_user.getName()).apply(); } @Override public void startLoginWithEmailFragment() { FragmentManager fragmentManager = getSupportFragmentManager(); FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction().replace(R.id.fragment_container, SA_SignUpFragment.newInstance()).addToBackStack("EMAIL_LOGIN"); fragmentTransaction.commit(); } @Override public void startLoginWithFBAction() { showProgressDialog(); LoginManager.getInstance().logInWithReadPermissions(this, Arrays.asList("email", "public_profile")); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); // Pass the activity result back to the Facebook SDK callbackManager.onActivityResult(requestCode, resultCode, data); } // [END on_activity_result] // [START auth_with_facebook] @SuppressWarnings({"ThrowableResultOfMethodCallIgnored", "ConstantConditions"}) private void handleFacebookAccessToken(AccessToken token, String s) { showProgressDialog(); Log.d(TAG, "handleFacebookAccessToken:" + token); AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken()); mAuth.signInWithCredential(credential) .addOnCompleteListener(this, task -> { Log.d(TAG, "signInWithCredential:onComplete:" + task.isSuccessful()); // 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()) { Log.w(TAG, "signInWithCredential", task.getException()); Toast.makeText(SA_LoginActivity.this, "This password is incorrect.", Toast.LENGTH_SHORT).show(); hideProgressDialog(); } else { FirebaseUser firebaseUser = task.getResult().getUser(); SA_User user = new SA_User(firebaseUser); user.name = s; user.nameLowerCase = s.toLowerCase(); user.photoUrl = firebaseUser.getPhotoUrl().toString(); user.save().addOnCompleteListener(saveTask -> { if (saveTask.isSuccessful()) { goToMain(); } else { Log.e(TAG, saveTask.getException().getMessage()); SA_Helper.showSnackbar(SA_LoginActivity.this.findViewById(R.id.fragment_container), saveTask.getException().getMessage()); } hideProgressDialog(); }); } }); } private void handleFacebookError(Exception e) { SA_Helper.showSnackbar(SA_LoginActivity.this.findViewById(R.id.fragment_container), e.getMessage()); } // [END auth_with_facebook] @Override public void onSignUpWithEmail(String userName, String email, String password) { Log.d(TAG, String.format("onSignUpWithEmail %s - %s - %s", userName, email, password)); createAccount(userName, email, password); } @Override public void doLoginWithEmail(String userName, String password) { signIn(userName, password); } @SuppressWarnings({"ThrowableResultOfMethodCallIgnored", "ConstantConditions"}) @Override public void doResetPasswordAction(String email) { showProgressDialog(); mAuth.sendPasswordResetEmail(email) .addOnCompleteListener(task -> { if (task.isSuccessful()) { Log.d(TAG, "Email sent."); getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container, SA_LoginFragment.newInstance("")).addToBackStack("EMAIL_LOGIN").commit(); } else { Log.e(TAG, task.getException().getMessage()); EventBus.getDefault().post(new SA_ErrorEvent("Error in sent email")); } hideProgressDialog(); }); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { if (event.getRepeatCount() == 0) { Log.d(TAG, "onKeyDown Called"); android.support.v4.app.Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.fragment_container); if (fragment != null && fragment instanceof SA_WelcomeFragment) { return false; } } } return super.onKeyDown(keyCode, event); } }
package io.kuoche.share.core.domain; import lombok.AllArgsConstructor; import lombok.Data; import java.time.LocalDateTime; import java.util.List; @Data @AllArgsConstructor public class Activity { private Long id; private String name; private List<Participator> participators; private LocalDateTime startTime; }
package com.example.amitkumarroshan.amaderaninos; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.widget.ProgressBar; public class Splash extends Activity { //Defining the widgets publicily private ProgressBar splash_loader; //Handling the progressBar increment Handler handle_progress = new Handler(){ @Override public void handleMessage(Message msg) { int progress = splash_loader.getProgress(); splash_loader.setProgress(progress+1); } }; //Starting a new Activity Handler start_Activity = new Handler(){ @Override public void handleMessage(Message msg) { Intent i = new Intent(getApplication() ,Login.class); startActivity(i); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); //Referencing the widgets by object creation splash_loader = (ProgressBar) findViewById(R.id.splash_loader); //Isolating the loading progress Thread t = new Thread( new Runnable() { @Override public void run() { for( int i=0 ; i<=100 ; i++){ long futureTime = System.currentTimeMillis() + 50; while(System.currentTimeMillis() < futureTime){ synchronized (this){ try{ wait(futureTime - System.currentTimeMillis()); }catch (Exception e){} } } handle_progress.sendEmptyMessage(0); } start_Activity.sendEmptyMessage(0); } } ); t.start(); } @Override protected void onPause() { super.onPause(); finish(); } }
package com.techlab.lskov; public class Eagle extends Bird { @Override public void fly() { System.out.println("I can fly at small distance like eagle"); } }
package LC0_200.LC150_200; public class LC181_Employees_Earning_More_Than_Their_Managers { // mysql }
package clientApplication; import javafx.geometry.Insets; import javafx.geometry.Pos; import javafx.scene.control.ComboBox; import javafx.scene.control.TextField; import javafx.scene.layout.HBox; import javafx.scene.layout.VBox; // this class contains the clientsView's center content public class ClientsCenter extends VBox{ private TextField searchFld; private ComboBox<String> cityFld; private ClientsList clientsList; //Constructor public ClientsCenter() { //children nodes //search fld searchFld = new TextField(); //Style searchFld.setPromptText("Recherche"); // cityFld cityFld = new ComboBox<String>(); //style cityFld.setPromptText("Ville"); //clientsList clientsList = new ClientsList(); //children containers // search filters HBox searchFilter = new HBox(searchFld,cityFld); //style searchFilter.setSpacing(30); searchFilter.maxWidthProperty().bind(clientsList.widthProperty()); // Adding nodes to layout getChildren().addAll(searchFilter , clientsList); //layout style setPadding(new Insets(20 , 20 , 20 , 100)); setSpacing(30); setAlignment(Pos.CENTER); // setFillWidth(true) ; } }
package com.anibal.educational.rest_service.comps.util; import java.io.File; import java.io.FileInputStream; import java.util.Arrays; import java.util.List; import org.apache.commons.codec.binary.Base64; import org.springframework.web.client.RestTemplate; import com.anibal.educational.rest_service.comps.config.RestServiceConfig; import com.anibal.educational.rest_service.comps.service.mail.MailConfigurator; import com.odhoman.api.utilities.config.AbstractConfig; import com.odhoman.api.utilities.db.DbConnectionManager; public class RestServiceUtil { private static DbConnectionManager dbConnectionMgr = null; private static AbstractConfig config = null; /** Devuelve un DbConnectionManager configurado */ public static DbConnectionManager getDbConnectionMgr() { if (null == dbConnectionMgr) { dbConnectionMgr = new DbConnectionManager(getConfig()); } return dbConnectionMgr; } public static AbstractConfig getConfig() { if(null == config) { setConfig(RestServiceConfig.getInstance()); } return config; } public static void setConfig(AbstractConfig cfg) { config = cfg; } /** Construye el nombre del archivos desde un nombre y la extension del archivo original */ public static String buildFileName(String name, String originalFileName) { String fileName = null; if (originalFileName != null && !originalFileName.isEmpty() && originalFileName.indexOf(".") > 0 && originalFileName.split("\\.").length >= 2) { List<String> list = Arrays.asList(originalFileName.split("\\.")); fileName = name+"."+list.get(list.size()-1); } else { fileName = name; } return fileName; } /** Crea el configurador de mail smtp */ public static MailConfigurator createConfiguratorSmtpMailing(AbstractConfig config){ MailConfigurator conf = new MailConfigurator(); conf.setPropHost(config.getProperty(RestServiceConstant.APP_EMAIL_SMTP_PROPHOST)); conf.setPropStarttlsEnable(config.getProperty(RestServiceConstant.APP_EMAIL_SMTP_PROPSTARTTLSENABLE)); conf.setPropPort(config.getProperty(RestServiceConstant.APP_EMAIL_SMTP_PROPPORT)); conf.setPropPort(config.getProperty(RestServiceConstant.APP_EMAIL_SMTP_PROPPORT)); conf.setPropUser(config.getProperty(RestServiceConstant.APP_EMAIL_SMTP_PROPUSER)); conf.setPropSmtpAuth(config.getProperty(RestServiceConstant.APP_EMAIL_SMTP_PROPSMTPAUTH)); conf.setMessageInternetAdress(config.getProperty(RestServiceConstant.APP_EMAIL_SMTP_MESSAGEINTERNETADRESS)); conf.setTransportProtocl(config.getProperty(RestServiceConstant.APP_EMAIL_SMTP_TRANSPORTPROTOCL)); conf.setTransportUser(config.getProperty(RestServiceConstant.APP_EMAIL_SMTP_TRANSPORTUSER)); conf.setTransportPass(config.getProperty(RestServiceConstant.APP_EMAIL_SMTP_TRANSPORTPASS)); return conf; } @SuppressWarnings("resource") public static String getImageToString(String pathFile) throws Exception { String image = null; File file = new File(pathFile); // Reading a Image file from file system FileInputStream imageInFile = new FileInputStream(file); byte imageData[] = new byte[(int) file.length()]; imageInFile.read(imageData); // Converting Image byte array into Base64 String image = encodeImage(imageData); return image; } public static String encodeImage(byte[] imageByteArray) { return Base64.encodeBase64URLSafeString(imageByteArray); } public static RestTemplate getAppRestTemplate(){ RestTemplate rt = new RestTemplate(); rt.setErrorHandler(new RestServiceErrorHandler(getConfig().getLogger())); return rt; } }
package com.spower.business.itemtype.service; import java.util.List; import com.spower.basesystem.common.command.Page; import com.spower.business.itemtype.command.ItemtypeQueryInfo; /** * @author huangwq *2014ๅนด11ๆœˆ19ๆ—ฅ */ public interface IItemtypeService { Page selectItemtypeList(ItemtypeQueryInfo info); List selectItemtypeTree(); List findSunsId(Integer parentId); }
package com.java.rkp.factory.abs; public class AbstractPlaneFactory { // public void getPlane(); }
package co.lofongi.third; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class Test { @SuppressWarnings("resource") public static void main(String[] args) { ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); ExStudent ex = (ExStudent)context.getBean("stud1"); ExStudent ex2 = (ExStudent)context.getBean("stud2"); System.out.println(ex.toString()); System.out.println(ex2.toString()); //context.close(); } }
package com.app.service.impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.security.core.userdetails.UserDetails; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.core.userdetails.UsernameNotFoundException; import org.springframework.stereotype.Service; import com.app.model.User; import com.app.repo.UserRepo; @Service public class UserDetailsServiceImpl implements UserDetailsService{ @Autowired private UserRepo userRepo; UserDetailsImpl userDetails=null; @Override public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { User user=userRepo.findByUserName(username); userDetails=new UserDetailsImpl(); userDetails.setUser(user); return new org.springframework.security.core.userdetails.User(user.getUserName(),user.getUserPwd(),userDetails.getAuthorities()); } }
package com.dral.Chatter; /** * Chatter - The new chat plugin. * Copyright (C) 2012 Michiel Dral <m.c.dral@Gmail.com> * Copyright (C) 2012 Steven "Drakia" Scott <Drakia@Gmail.com> * Copyright (C) 2012 MiracleM4n <https://github.com/MiracleM4n/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import com.dral.Chatter.configuration.ChatterConfigThing; import com.dral.Chatter.configuration.Configuration; import com.dral.Chatter.formatting.ChatterFormat; import com.dral.Chatter.integration.ChatterCraftIRC; import com.dral.Chatter.listeners.ChatterPlayerListener; import com.dral.Chatter.permissions.ChatterPermissionsHandler; import com.ensifera.animosity.craftirc.CraftIRC; import com.massivecraft.factions.P; import com.onarandombox.MultiverseCore.api.Core; import net.milkbowl.vault.chat.Chat; import net.milkbowl.vault.permission.Permission; import org.bukkit.Server; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.plugin.Plugin; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.RegisteredServiceProvider; import org.bukkit.plugin.java.JavaPlugin; import org.getspout.spoutapi.player.SpoutPlayer; import java.io.File; import java.util.ArrayList; import java.util.List; import java.util.logging.Logger; public class Chatter extends JavaPlugin { private static final Logger log = Logger.getLogger("Minecraft"); public Server server; public static Chat chatinfo = null; // Permissions public static Permission perms = null; PluginManager pm; public Configuration config; Configuration groups; // Config variables public List<String> censorWords = new ArrayList<String>(); public String chatFormat = "[$prefix+group$suffix&f] +name: +message"; public String meFormat = "* +name +message"; public String nameFormat = "[$prefix+group$suffix&f] +name"; public String dateFormat = "HH:mm:ss"; public String deathFormat = "[$prefix+group$suffix&f] +name +message"; public String quitFormat = "[$prefix+group$suffix&f] +name +message"; public String joinFormat = "[$prefix+group$suffix&f] +name +message"; public String kickFormat = "[$prefix+group$suffix&f] +name +message"; public String listNameFormat = "[$prefix] +name"; public boolean textwrapping = true; public String nether_name = "+world nether"; public boolean logEverything = false; public boolean playerlist = false; public boolean stripColor = true; public boolean printDeaths = false; public P factionpluginthing; public boolean factionisEnabled = false; public Core multiversepluginthing; public boolean multiverseisEnabled = false; public SpoutPlayer spoutpluginthing; public boolean spoutisEnabled = false; public boolean craftircenabled = false; public CraftIRC craftirchandler; public ChatterCraftIRC irc; public ChatterFormat format = new ChatterFormat(this); private ChatterConfigThing configThing = new ChatterConfigThing(this); private ChatterPlayerListener pListener = new ChatterPlayerListener(this); public final ChatterPermissionsHandler permhandler = new ChatterPermissionsHandler(this); //private ChatterConfigThong configThong; public void onEnable() { server = getServer(); pm = getServer().getPluginManager(); config = new Configuration(this); Plugin factions = getServer().getPluginManager().getPlugin("Factions"); if (factions != null) { this.factionpluginthing = (P) factions; this.factionisEnabled = true; } Plugin multiverse = getServer().getPluginManager().getPlugin("Multiverse-Core"); if (multiverse != null) { this.multiversepluginthing = (Core) multiverse; this.multiverseisEnabled = true; } Plugin spoutTest = getServer().getPluginManager().getPlugin("Spout"); if (spoutTest != null) { this.spoutisEnabled = true; } Plugin craftirc = getServer().getPluginManager().getPlugin("CraftIRC"); if (craftirc != null) { this.craftirchandler = (CraftIRC) craftirc; this.irc = new ChatterCraftIRC(this); irc.initIRC(); } pm.registerEvents(pListener, this); setupPermissions(); setupChat(); // Create default config if it doesn't exist. if (!(new File(getDataFolder(), "config.yml")).exists()) { configThing.defaultConfig(); } configThing.checkConfig(); configThing.loadConfig(); logIt("Chatter loaded correctly! let's do this!"); } public void onDisable() { //disable things? } public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if (command.getName().equalsIgnoreCase("reloadchatter")) { if (permhandler.checkPermissions((Player) sender, "chatter.reload")) { configThing.loadConfig(); sender.sendMessage("[Chatter] chatter reloaded :)"); } return true; } else if (command.getName().equalsIgnoreCase("chatter")) { sender.sendMessage("[Chatter] the revolutionair chat plugin."); return true; } return false; } private boolean setupPermissions() { RegisteredServiceProvider<Permission> rsp = getServer().getServicesManager().getRegistration(Permission.class); perms = rsp.getProvider(); return perms != null; } private boolean setupChat() { RegisteredServiceProvider<Chat> rsp = getServer().getServicesManager().getRegistration(Chat.class); chatinfo = rsp.getProvider(); return chatinfo != null; } public void logIt(String message) { if (logEverything) { log.info("[Chatter] " + message); } } public void logIt(String message, boolean loganyway) { if (loganyway) { log.info("[Chatter] " + message); } else { logIt(message); } } }
package com.base.crm.common.constants; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.context.event.ContextRefreshedEvent; import org.springframework.stereotype.Component; import com.base.crm.level.entity.Level; import com.base.crm.level.service.LevelService; @Component public class CustomerLevelContainer implements ApplicationListener<ContextRefreshedEvent> { private static final Logger logger = LoggerFactory.getLogger(CustomerLevelContainer.class); public static Map<Integer,String> levelMap = new HashMap<Integer,String>(); public static List<Level> levelList = new ArrayList<Level>(); @Autowired private LevelService levelService; @Override public void onApplicationEvent(ContextRefreshedEvent event) { if(levelMap.size()==0){ levelList = levelService.selectAllForMap(); logger.debug("levelList:{}",levelList); for(Level level : levelList){ levelMap.put(level.getlId(), level.getlName()); } logger.debug("levelMap:{}",levelMap); } } public String get(Integer key){ return levelMap.get(key); } }
/* * @project: (Sh)ower (R)econstructing (A)pplication for (M)obile (P)hones * @version: ShRAMP v0.0 * * @objective: To detect extensive air shower radiation using smartphones * for the scientific study of ultra-high energy cosmic rays * * @institution: University of California, Irvine * @department: Physics and Astronomy * * @author: Eric Albin * @email: Eric.K.Albin@gmail.com * * @updated: 3 May 2019 */ package sci.crayfis.shramp.camera2; import android.annotation.TargetApi; import android.graphics.ImageFormat; import android.hardware.camera2.CameraCharacteristics; import android.hardware.camera2.CameraDevice; import android.hardware.camera2.CameraMetadata; import android.hardware.camera2.CaptureRequest; import android.hardware.camera2.params.StreamConfigurationMap; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.util.Log; import android.util.Range; import android.util.Size; import org.jetbrains.annotations.Contract; import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import sci.crayfis.shramp.GlobalSettings; import sci.crayfis.shramp.MasterController; import sci.crayfis.shramp.camera2.characteristics.CharacteristicsReader; import sci.crayfis.shramp.camera2.requests.RequestMaker; import sci.crayfis.shramp.camera2.util.Parameter; import sci.crayfis.shramp.surfaces.SurfaceController; import sci.crayfis.shramp.util.ArrayToList; import sci.crayfis.shramp.util.NumToString; import sci.crayfis.shramp.util.SizeSortedSet; /** * Encapsulation of CameraDevice, its characteristics, abilities and configuration for capture */ // TODO: figure out who is giving the unchecked warning @SuppressWarnings("unchecked") @TargetApi(21) final class Camera extends CameraDevice.StateCallback{ // Private Instance Fields //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // mBitsPerPixel................................................................................ // Output format bits per pixel private Integer mBitsPerPixel; // mCameraCharacteristics....................................................................... // Encapsulation of camera's features private CameraCharacteristics mCameraCharacteristics; // mCameraDevice................................................................................ // Reference to the camera device hardware private CameraDevice mCameraDevice; // mCameraId.................................................................................... // System-assigned camera ID private String mCameraId; // mCaptureRequestBuilder....................................................................... // Current capture request builder private CaptureRequest.Builder mCaptureRequestBuilder; // mCaptureRequestMap........................................................................... // Current full configuration of camera for capture private LinkedHashMap<CaptureRequest.Key, Parameter> mCaptureRequestMap; // mCaptureRequestTemplate...................................................................... // Camera capture template private Integer mCaptureRequestTemplate; // mCharacteristicsMap.......................................................................... // Encapsulation of all camera abilities and features private LinkedHashMap<CameraCharacteristics.Key, Parameter> mCharacteristicsMap; // mName........................................................................................ // Human-friendly camera name private String mName; // mOutputFormat................................................................................ // Output format (ImageFormat.YUV_420_888 or RAW_SENSOR) private Integer mOutputFormat; // mOutputSize.................................................................................. // Output size (width and height in pixels) private Size mOutputSize; //////////////////////////////////////////////////////////////////////////////////////////////// //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: //////////////////////////////////////////////////////////////////////////////////////////////// // Constructors //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // Camera....................................................................................... /** * Public access disabled */ private Camera() { super(); } // Camera....................................................................................... /** * Create a new Camera * @param name Human-friendly name for camera * @param cameraId System-assigned camera ID * @param cameraCharacteristics Encapsulation of camera features */ Camera(@NonNull String name, @NonNull String cameraId, @NonNull CameraCharacteristics cameraCharacteristics) { this(); Log.e(Thread.currentThread().getName(), " \n\n\t\t\tNew camera created: " + name + " with ID: " + cameraId + "\n "); mName = name; mCameraId = cameraId; mCameraCharacteristics = cameraCharacteristics; mCharacteristicsMap = CharacteristicsReader.read(mCameraCharacteristics); establishOutputFormatting(); } // Private Instance Methods //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // establishOutputFormatting.................................................................... /** * Figure out optimal output format for capture */ private void establishOutputFormatting() { Parameter parameter; parameter = mCharacteristicsMap.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP); if (parameter == null) { // TODO: error Log.e(Thread.currentThread().getName(), "Stream configuration map cannot be null"); MasterController.quitSafely(); return; } StreamConfigurationMap streamConfigurationMap = (StreamConfigurationMap) parameter.getValue(); if (streamConfigurationMap == null) { // TODO: error Log.e(Thread.currentThread().getName(), "Stream configuration map cannot be null"); MasterController.quitSafely(); return; } parameter = mCharacteristicsMap.get(CameraCharacteristics.REQUEST_AVAILABLE_CAPABILITIES); if (parameter == null) { // TODO: error Log.e(Thread.currentThread().getName(), "Available capabilities cannot be null"); MasterController.quitSafely(); return; } Integer[] capabilities = (Integer[]) parameter.getValue(); if (capabilities == null) { // TODO: error Log.e(Thread.currentThread().getName(), "Capabilities cannot be null"); } List<Integer> abilities = ArrayToList.convert(capabilities); if (!GlobalSettings.DISABLE_RAW_OUTPUT && abilities.contains(CameraMetadata.REQUEST_AVAILABLE_CAPABILITIES_RAW)) { mOutputFormat = ImageFormat.RAW_SENSOR; } else { mOutputFormat = ImageFormat.YUV_420_888; } mBitsPerPixel = ImageFormat.getBitsPerPixel(mOutputFormat); // Find the largest output size supported by all output surfaces SizeSortedSet outputSizes = new SizeSortedSet(); Size[] streamOutputSizes = streamConfigurationMap.getOutputSizes(mOutputFormat); Collections.addAll(outputSizes, streamOutputSizes); List<Class> outputClasses = SurfaceController.getOutputSurfaceClasses(); for (Class klass : outputClasses) { Size[] classOutputSizes = streamConfigurationMap.getOutputSizes(klass); if (classOutputSizes == null) { // TODO: error Log.e(Thread.currentThread().getName(), "Class output size cannot be null"); MasterController.quitSafely(); return; } for (Size s : classOutputSizes) { if (!outputSizes.contains(s)) { outputSizes.remove(s); } } } mOutputSize = outputSizes.last(); } // Package-private Instance Methods //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // close........................................................................................ /** * Close this camera */ void close() { Log.e(Thread.currentThread().getName(), "Closing camera: " + mName + " with ID: " + mCameraId); if (mCameraDevice != null) { mCameraDevice.close(); } } //////////////////////////////////////////////////////////////////////////////////////////////// // getAvailableCaptureRequestKeys............................................................... /** * @return Current capture request keys */ @NonNull List<CaptureRequest.Key<?>> getAvailableCaptureRequestKeys() { return mCameraCharacteristics.getAvailableCaptureRequestKeys(); } // getAvailableCharacteristicsKeys.............................................................. /** * @return All camera characteristics and abilities */ @NonNull List<CameraCharacteristics.Key<?>> getAvailableCharacteristicsKeys() { return mCameraCharacteristics.getKeys(); } // getBitsPerPixel.............................................................................. /** * @return Output format bits per pixel */ @Contract(pure = true) @Nullable Integer getBitsPerPixel() { return mBitsPerPixel; } // getCameraDevice.............................................................................. /** * @return Reference to CameraDevice contained by this object */ @Contract(pure = true) @Nullable CameraDevice getCameraDevice() { return mCameraDevice; } // getCameraId.................................................................................. /** * @return Get system-assigned camera ID */ @Contract(pure = true) @NonNull String getCameraId() { return mCameraId; } // getCaptureRequestBuilder..................................................................... /** * @return Current capture request builder */ @Contract(pure = true) @Nullable CaptureRequest.Builder getCaptureRequestBuilder() { return mCaptureRequestBuilder; } // getCharacteristicsMap........................................................................ /** * @return Encapsulation of camera features */ @Contract(pure = true) @NonNull LinkedHashMap<CameraCharacteristics.Key, Parameter> getCharacteristicsMap() { return mCharacteristicsMap; } // getOutputFormat.............................................................................. /** * @return Camera output format (ImageFormat.YUV_420_888 or RAW_SENSOR) */ @Contract(pure = true) @Nullable Integer getOutputFormat() { return mOutputFormat; } // getOutputSize................................................................................ /** * @return Output size (width and height in pixels) */ @Contract(pure = true) @NonNull Size getOutputSize() { return mOutputSize; } //////////////////////////////////////////////////////////////////////////////////////////////// // setCaptureRequestBuilder..................................................................... /** * @param builder Set camera to use CaptureRequest.Builder for capture */ void setCaptureRequestBuilder(@NonNull CaptureRequest.Builder builder) { mCaptureRequestBuilder = builder; } // setCaptureRequestMap......................................................................... /** * @param map Set full camera request mapping */ void setCaptureRequestMap(@NonNull LinkedHashMap<CaptureRequest.Key, Parameter> map) { mCaptureRequestMap = map; } // setCaptureRequestTemplate.................................................................... /** * @param template Set camera request template for capture */ void setCaptureRequestTemplate(@NonNull Integer template) { mCaptureRequestTemplate = template; } //////////////////////////////////////////////////////////////////////////////////////////////// // writeFPS..................................................................................... /** * Display current Camera FPS settings */ void writeFPS() { Log.e(Thread.currentThread().getName(), " \n\n" + mName + ", ID: " + mCameraId); Integer mode = mCaptureRequestBuilder.get(CaptureRequest.CONTROL_AE_MODE); if (mode == null) { // TODO: error Log.e(Thread.currentThread().getName(), "AE mode cannot be null"); MasterController.quitSafely(); return; } if (mOutputFormat == ImageFormat.YUV_420_888) { Log.e(Thread.currentThread().getName(), ">>>>>>>> Output format is YUV_420_888"); } else { // mOutputFormat == ImageFormat.RAW_SENSOR Log.e(Thread.currentThread().getName(), ">>>>>>>> Output format is RAW_SENSOR"); } if (mode == CameraMetadata.CONTROL_AE_MODE_ON) { Range<Integer> fpsRange = mCaptureRequestBuilder.get(CaptureRequest.CONTROL_AE_TARGET_FPS_RANGE); if (fpsRange == null) { // TODO: error Log.e(Thread.currentThread().getName(), "FPS range cannot be null"); MasterController.quitSafely(); return; } Log.e(Thread.currentThread().getName(), ">>>>>>>> FPS Range: " + fpsRange.toString() + " [frames per second]"); } else { Long frameDuration = mCaptureRequestBuilder.get(CaptureRequest.SENSOR_FRAME_DURATION); Long exposureTime = mCaptureRequestBuilder.get(CaptureRequest.SENSOR_EXPOSURE_TIME); if (frameDuration == null || exposureTime == null) { // TODO: error Log.e(Thread.currentThread().getName(), "Sensor exposure time and frame duration cannot be null"); MasterController.quitSafely(); return; } double fps = Math.round(1e9 / (double) frameDuration); Log.e(Thread.currentThread().getName(), ">>>>>>>> Frame Duration: " + NumToString.decimal(fps) + " [frames per second]"); double duty = Math.round(100. * exposureTime / (double) frameDuration); Log.e(Thread.currentThread().getName(), ">>>>>>>> Exposure Duty: " + NumToString.decimal(duty) + " [%]"); } } // writeCharacteristics......................................................................... /** * Display full camera features */ void writeCharacteristics() { String label = mName + ", ID: " + mCameraId; CharacteristicsReader.write(label, mCharacteristicsMap, getAvailableCharacteristicsKeys()); } // writeRequest................................................................................. /** * Display current capture request */ void writeRequest() { String label = mName + ", ID: " + mCameraId; RequestMaker.write(label, mCaptureRequestMap, getAvailableCaptureRequestKeys()); } // Public Overriding Instance Methods //:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::: // onOpened..................................................................................... /** * Called by the system when camera comes online, execution continues in CameraController.cameraHasOpened() * @param camera CameraDevice that has been opened */ @Override public void onOpened(@NonNull CameraDevice camera) { Log.e(Thread.currentThread().getName(), " \n\n\t\tCamera: " + mName + " has opened\n\n"); mCameraDevice = camera; CameraController.cameraHasOpened(this); } // onClosed..................................................................................... /** * Called by the system when the camera is closing. * Execution continues in CameraController.cameraHasClosed() * @param camera CameraDevice that has been closed */ @Override public void onClosed(@NonNull CameraDevice camera) { Log.e(Thread.currentThread().getName(), "Camera: " + mName + " has closed"); CameraController.cameraHasClosed(); } // onDisconnected............................................................................... /** * Called by the system when the camera has been disconnected * @param camera CameraDevice that has been disconnected */ @Override public void onDisconnected(@NonNull CameraDevice camera) { // TODO: error Log.e(Thread.currentThread().getName(), "Camera: " + mName + " has been disconnected"); MasterController.quitSafely(); } // onError...................................................................................... /** * Called by the system when an error occurs with the camera * @param camera CameraDevice that has erred */ @Override public void onError(@NonNull CameraDevice camera, int error) { // TODO: figure out why the compiler says there are missing options for the switch-case String err; switch (error) { case (CameraDevice.StateCallback.ERROR_CAMERA_DEVICE): { err = "ERROR_CAMERA_DEVICE"; break; } case (CameraDevice.StateCallback.ERROR_CAMERA_DISABLED): { err = "ERROR_CAMERA_DISABLED"; break; } case (CameraDevice.StateCallback.ERROR_CAMERA_IN_USE): { err = "ERROR_CAMERA_IN_USE"; break; } case (CameraDevice.StateCallback.ERROR_CAMERA_SERVICE): { err = "ERROR_CAMERA_SERVICE"; break; } case (CameraDevice.StateCallback.ERROR_MAX_CAMERAS_IN_USE): { err = "ERROR_MAX_CAMERAS_IN_USE"; break; } default: { err = "UNKNOWN_ERROR"; } } // TODO: error Log.e(Thread.currentThread().getName(), "Camera error: " + mName + " err: " + err); MasterController.quitSafely(); } }
package switch2019.project.controllerLayer.rest.integration; import org.json.JSONObject; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.transaction.annotation.Transactional; import switch2019.project.AbstractTest; import switch2019.project.DTO.deserializationDTO.CreateGroupInfoDTO; import switch2019.project.utils.customExceptions.ArgumentNotFoundException; import switch2019.project.utils.customExceptions.ResourceAlreadyExistsException; import java.time.LocalDateTime; import java.util.Objects; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @SpringBootTest @Transactional class US002_1CreateGroupControllerRestIntegrationTest extends AbstractTest { @Override @BeforeEach public void setUP(){ super.setUP(); } @Test @DisplayName("Test if an existing person creates a Group and becomes Admin - Main Scenario") void createGroupAndBecomeAdminHappyCase() throws Exception { //Arrange String uriPost = "/groups"; // URI used by the GET String uriGet = "/groups/Online Shopping/"; final String groupDescription = "Online Shopping"; final String personEmail = "1110120@isep.ipp.pt"; CreateGroupInfoDTO createGroupInfoDTO = new CreateGroupInfoDTO (); createGroupInfoDTO.setGroupDescription(groupDescription); createGroupInfoDTO.setPersonEmail(personEmail); String inputJson = super.mapToJson((createGroupInfoDTO)); String expectedLinks = "{\"self\":{\"href\":\"http:\\/\\/localhost\\/groups\\/ONLINE%20SHOPPING\"}}"; // Get before the post MvcResult mvcResultGetBefore = mvc.perform(MockMvcRequestBuilders.get(uriGet) .contentType(MediaType.APPLICATION_JSON)) .andReturn(); int statusGetBefore = mvcResultGetBefore.getResponse().getStatus(); JSONObject getBefore = new JSONObject(mvcResultGetBefore.getResponse().getContentAsString()); // ACT MvcResult mvcResultPost = mvc.perform(MockMvcRequestBuilders.post(uriPost) .contentType(MediaType.APPLICATION_JSON_VALUE) .content(inputJson)) .andExpect(status().isCreated()) .andReturn(); int status = mvcResultPost.getResponse().getStatus(); JSONObject result = new JSONObject(mvcResultPost.getResponse().getContentAsString()); // Get after the post MvcResult mvcResultGetAfter = mvc.perform(MockMvcRequestBuilders.get(uriGet) .contentType(MediaType.APPLICATION_JSON)) .andReturn(); int statusGetAfter = mvcResultGetAfter.getResponse().getStatus(); System.out.println("status: " + statusGetAfter); JSONObject getAfter = new JSONObject(mvcResultGetAfter.getResponse().getContentAsString()); // ASSERT // Assert Get before Post Assertions.assertAll( () -> assertEquals(422, statusGetBefore), () -> assertEquals ("No group found with that description.", getBefore.getString("message")) ); // Assert Post Assertions.assertAll( () -> assertEquals(201, status), () -> assertEquals(groupDescription.toUpperCase(),result.getString("groupDescription")), () -> assertEquals(expectedLinks, result.getString("_links")) ); // Assert Get after Post Assertions.assertAll( () -> assertEquals(200, statusGetAfter), () -> assertEquals(groupDescription.toUpperCase(),getAfter.getString("groupDescription")) ); } @Test @DisplayName("Test if an existing person creates a Group and becomes Admin - person doesn't exist") void createGroupAndBecomeAdminPersonDoesNotExists() throws Exception { //Arrange String uri = "/groups"; final String groupDescriptionStr = "Expenses"; final String personEmail = "qwerty@gmail.com"; CreateGroupInfoDTO createGroupInfoDTO = new CreateGroupInfoDTO(); createGroupInfoDTO.setGroupDescription(groupDescriptionStr); createGroupInfoDTO.setPersonEmail(personEmail); String inputJson = super.mapToJson((createGroupInfoDTO)); String expectedResolvedException = new ArgumentNotFoundException("No person found with that email.").toString(); //Act MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post(uri) .contentType(MediaType.APPLICATION_JSON_VALUE) .content(inputJson)) .andExpect(status().isUnprocessableEntity()) .andReturn(); int status = mvcResult.getResponse().getStatus(); JSONObject result = new JSONObject(mvcResult.getResponse().getContentAsString()); String realResolvedException = Objects.requireNonNull(mvcResult.getResolvedException()).toString(); //Assert Assertions.assertAll( () -> assertEquals(422, status), () -> assertEquals(LocalDateTime.now().withNano(0).withSecond(0).toString(),result.getString("timestamp")), () -> assertEquals("422", result.getString("statusCode")), () -> assertEquals("UNPROCESSABLE_ENTITY", result.getString("status")), () -> assertEquals ("This resource was not found.", result.getString("error")), () -> assertEquals ("No person found with that email.", result.getString("message")), () -> assertEquals(expectedResolvedException, realResolvedException) ); } @Test @DisplayName("Test if an existing person creates a Group and becomes Admin - group Already Exists") void createGroupAndBecomeAdminGroupAlreadyExists() throws Exception { //Arrange String uri = "/groups"; final String groupDescriptionStr = "SWitCH"; final String personEmail = "morty@gmail.com"; CreateGroupInfoDTO createGroupInfoDTO = new CreateGroupInfoDTO(); createGroupInfoDTO.setGroupDescription(groupDescriptionStr); createGroupInfoDTO.setPersonEmail(personEmail); String inputJson = super.mapToJson((createGroupInfoDTO)); String expectedResolvedException = new ResourceAlreadyExistsException("This group already exists.").toString(); //Act MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post(uri) .contentType(MediaType.APPLICATION_JSON_VALUE) .content(inputJson)) .andExpect(status().isConflict()) .andReturn(); int status = mvcResult.getResponse().getStatus(); JSONObject result = new JSONObject(mvcResult.getResponse().getContentAsString()); String realResolvedException = Objects.requireNonNull(mvcResult.getResolvedException()).toString(); //Assert Assertions.assertAll( () -> assertEquals(409, status), () -> assertEquals(LocalDateTime.now().withNano(0).withSecond(0).toString(),result.getString("timestamp")), () -> assertEquals("409", result.getString("statusCode")), () -> assertEquals("CONFLICT", result.getString("status")), () -> assertEquals ("This resource already exists.", result.getString("error")), () -> assertEquals ("This group already exists.", result.getString("message")), () -> assertEquals(expectedResolvedException, realResolvedException) ); } @Test @DisplayName("Test if an existing person creates a Group and becomes Admin - invalid email - null") void createGroupAndBecomeAdminInvalidEmailNull() throws Exception { //Arrange String uri = "/groups"; final String groupDescriptionStr = "SWitCH"; final String personEmail = null; CreateGroupInfoDTO createGroupInfoDTO = new CreateGroupInfoDTO(); createGroupInfoDTO.setGroupDescription(groupDescriptionStr); createGroupInfoDTO.setPersonEmail(personEmail); String inputJson = super.mapToJson((createGroupInfoDTO)); String expectedResolvedException = new IllegalArgumentException("The email can't be null.").toString(); //Act MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post(uri) .contentType(MediaType.APPLICATION_JSON_VALUE) .content(inputJson)) .andExpect(status().isUnprocessableEntity()) .andReturn(); int status = mvcResult.getResponse().getStatus(); JSONObject result = new JSONObject(mvcResult.getResponse().getContentAsString()); String realResolvedException = Objects.requireNonNull(mvcResult.getResolvedException()).toString(); //Assert: Assertions.assertAll( () -> assertEquals(422, status), () -> assertEquals(LocalDateTime.now().withNano(0).withSecond(0).toString(),result.getString("timestamp")), () -> assertEquals("422", result.getString("statusCode")), () -> assertEquals("UNPROCESSABLE_ENTITY", result.getString("status")), () -> assertEquals ("One of the parameters is invalid or is missing.", result.getString("error")), () -> assertEquals ("The email can't be null.", result.getString("message")), () -> assertEquals(expectedResolvedException, realResolvedException) ); } @Test @DisplayName("Test if an existing person creates a Group and becomes Admin - invalid email - empty") void createGroupAndBecomeAdminInvalidEmailEmpty() throws Exception { //Arrange String uri = "/groups"; final String groupDescriptionStr = "SWitCH"; final String personEmail = ""; CreateGroupInfoDTO createGroupInfoDTO = new CreateGroupInfoDTO(); createGroupInfoDTO.setGroupDescription(groupDescriptionStr); createGroupInfoDTO.setPersonEmail(personEmail); String inputJson = super.mapToJson((createGroupInfoDTO)); String expectedResolvedException = new IllegalArgumentException("The email is not valid.").toString(); //Act MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post(uri) .contentType(MediaType.APPLICATION_JSON_VALUE) .content(inputJson)) .andExpect(status().isUnprocessableEntity()) .andReturn(); int status = mvcResult.getResponse().getStatus(); JSONObject result = new JSONObject(mvcResult.getResponse().getContentAsString()); String realResolvedException = Objects.requireNonNull(mvcResult.getResolvedException()).toString(); //Assert: Assertions.assertAll( () -> assertEquals(422, status), () -> assertEquals(LocalDateTime.now().withNano(0).withSecond(0).toString(),result.getString("timestamp")), () -> assertEquals("422", result.getString("statusCode")), () -> assertEquals("UNPROCESSABLE_ENTITY", result.getString("status")), () -> assertEquals ("One of the parameters is invalid or is missing.", result.getString("error")), () -> assertEquals ("The email is not valid.", result.getString("message")), () -> assertEquals(expectedResolvedException, realResolvedException) ); } @Test @DisplayName("Test if an existing person creates a Group and becomes Admin - invalid email - invalid format") void createGroupAndBecomeAdminInvalidEmailFormat() throws Exception { //Arrange String uri = "/groups"; final String groupDescriptionStr = "SWitCH"; final String personEmail = "morty@@gmail.com"; CreateGroupInfoDTO createGroupInfoDTO = new CreateGroupInfoDTO(); createGroupInfoDTO.setGroupDescription(groupDescriptionStr); createGroupInfoDTO.setPersonEmail(personEmail); String inputJson = super.mapToJson((createGroupInfoDTO)); String expectedResolvedException = new IllegalArgumentException("The email is not valid.").toString(); //Act MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post(uri) .contentType(MediaType.APPLICATION_JSON_VALUE) .content(inputJson)) .andExpect(status().isUnprocessableEntity()) .andReturn(); int status = mvcResult.getResponse().getStatus(); JSONObject result = new JSONObject(mvcResult.getResponse().getContentAsString()); String realResolvedException = Objects.requireNonNull(mvcResult.getResolvedException()).toString(); //Assert: Assertions.assertAll( () -> assertEquals(422, status), () -> assertEquals(LocalDateTime.now().withNano(0).withSecond(0).toString(),result.getString("timestamp")), () -> assertEquals("422", result.getString("statusCode")), () -> assertEquals("UNPROCESSABLE_ENTITY", result.getString("status")), () -> assertEquals ("One of the parameters is invalid or is missing.", result.getString("error")), () -> assertEquals ("The email is not valid.", result.getString("message")), () -> assertEquals(expectedResolvedException, realResolvedException) ); } @Test @DisplayName("Test if an existing person creates a Group and becomes Admin - invalid groupDescription - null") void createGroupAndBecomeAdminGroupDescriptionNull() throws Exception { //Arrange String uri = "/groups"; final String groupDescriptionStr = null; final String personEmail = "morty@gmail.com"; CreateGroupInfoDTO createGroupInfoDTO = new CreateGroupInfoDTO(); createGroupInfoDTO.setGroupDescription(groupDescriptionStr); createGroupInfoDTO.setPersonEmail(personEmail); String inputJson = super.mapToJson((createGroupInfoDTO)); String expectedResolvedException = new IllegalArgumentException("The description can't be null or empty.").toString(); //Act MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post(uri) .contentType(MediaType.APPLICATION_JSON_VALUE) .content(inputJson)) .andExpect(status().isUnprocessableEntity()) .andReturn(); int status = mvcResult.getResponse().getStatus(); JSONObject result = new JSONObject(mvcResult.getResponse().getContentAsString()); String realResolvedException = Objects.requireNonNull(mvcResult.getResolvedException()).toString(); //Assert Assertions.assertAll( () -> assertEquals(422, status), () -> assertEquals(LocalDateTime.now().withNano(0).withSecond(0).toString(),result.getString("timestamp")), () -> assertEquals("422", result.getString("statusCode")), () -> assertEquals("UNPROCESSABLE_ENTITY", result.getString("status")), () -> assertEquals ("One of the parameters is invalid or is missing.", result.getString("error")), () -> assertEquals ("The description can't be null or empty.", result.getString("message")), () -> assertEquals(expectedResolvedException, realResolvedException) ); } @Test @DisplayName("Test if an existing person creates a Group and becomes Admin - invalid groupDescription - Empty") void createGroupAndBecomeAdminGroupDescriptionEmpty() throws Exception { //Arrange String uri = "/groups"; final String groupDescriptionStr = ""; final String personEmail = "morty@gmail.com"; CreateGroupInfoDTO createGroupInfoDTO = new CreateGroupInfoDTO(); createGroupInfoDTO.setGroupDescription(groupDescriptionStr); createGroupInfoDTO.setPersonEmail(personEmail); String inputJson = super.mapToJson((createGroupInfoDTO)); String expectedResolvedException = new IllegalArgumentException("The description can't be null or empty.").toString(); //Act MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post(uri) .contentType(MediaType.APPLICATION_JSON_VALUE) .content(inputJson)) .andExpect(status().isUnprocessableEntity()) .andReturn(); int status = mvcResult.getResponse().getStatus(); JSONObject result = new JSONObject(mvcResult.getResponse().getContentAsString()); String realResolvedException = Objects.requireNonNull(mvcResult.getResolvedException()).toString(); //Assert Assertions.assertAll( () -> assertEquals(422, status), () -> assertEquals(LocalDateTime.now().withNano(0).withSecond(0).toString(),result.getString("timestamp")), () -> assertEquals("422", result.getString("statusCode")), () -> assertEquals("UNPROCESSABLE_ENTITY", result.getString("status")), () -> assertEquals ("One of the parameters is invalid or is missing.", result.getString("error")), () -> assertEquals ("The description can't be null or empty.", result.getString("message")), () -> assertEquals(expectedResolvedException, realResolvedException) ); } @Test @DisplayName("Test if an existing person creates a Group and becomes Admin - invalid groupDescription - Empty") void createGroupAndBecomeAdminNullJsonInput() throws Exception { //Arrange String uri = "/groups"; String inputJson = super.mapToJson((null)); //Act MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post(uri) .contentType(MediaType.APPLICATION_JSON_VALUE) .content(inputJson)) .andExpect(status().isBadRequest()) .andReturn(); int status = mvcResult.getResponse().getStatus(); JSONObject result = new JSONObject(mvcResult.getResponse().getContentAsString()); //Assert Assertions.assertAll( () -> assertEquals(400, status), () -> assertEquals(LocalDateTime.now().withNano(0).withSecond(0).toString(),result.getString("timestamp")), () -> assertEquals("400", result.getString("statusCode")), () -> assertEquals("BAD_REQUEST", result.getString("status")), () -> assertEquals ("The request body needed to perform the operation is missing.", result.getString("error")), () -> assertEquals ("Required request body is missing.", result.getString("message")) ); } /* * Test if a groupDTO is returned given its description */ @Test @DisplayName("Test if a groupDTO is returned given its description - Happy Case") public void getGroupByDescription() throws Exception { //Arrange String uri = "/groups/Smith Family"; String groupDescription = "SMITH FAMILY"; String expectedLinks = "{\"Admins\":{\"href\":\"http:\\/\\/localhost\\/groups\\/SMITH%20FAMILY\\/admins\"}," + "\"Members\":{\"href\":\"http:\\/\\/localhost\\/groups\\/SMITH%20FAMILY\\/members\"}}"; //Act MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(uri) .contentType(MediaType.APPLICATION_JSON)) .andReturn(); int status = mvcResult.getResponse().getStatus(); JSONObject result = new JSONObject(mvcResult.getResponse().getContentAsString()); //Assert Assertions.assertAll( () -> assertEquals(200, status), () -> assertEquals(groupDescription.toUpperCase(),result.getString("groupDescription")), () -> assertEquals (expectedLinks, result.getString("_links")) ); } @Test @DisplayName("Test if a groupDTO is returned given its description - Not Found") public void getGroupByDescriptionNotFound() throws Exception { //Arrange String uri = "/groups/SuicideSquad"; String expectedResolvedException = new ArgumentNotFoundException("No group found with that description.").toString(); MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.get(uri) .contentType(MediaType.APPLICATION_JSON)) .andReturn(); int status = mvcResult.getResponse().getStatus(); JSONObject result = new JSONObject(mvcResult.getResponse().getContentAsString()); String realResolvedException = Objects.requireNonNull(mvcResult.getResolvedException()).toString(); //Assert Assertions.assertAll( () -> assertEquals(422, status), () -> assertEquals(LocalDateTime.now().withNano(0).withSecond(0).toString(),result.getString("timestamp")), () -> assertEquals("422", result.getString("statusCode")), () -> assertEquals("UNPROCESSABLE_ENTITY", result.getString("status")), () -> assertEquals ("This resource was not found.", result.getString("error")), () -> assertEquals ("No group found with that description.", result.getString("message")), () -> assertEquals(expectedResolvedException, realResolvedException) ); } }
package com.sunbing.demo.mapper; import com.sunbing.demo.entity.Author; import com.baomidou.mybatisplus.core.mapper.BaseMapper; /** * <p> * ไฝœ่€…่กจ Mapper ๆŽฅๅฃ * </p> * * @author sunbing * @since 2021-03-16 */ public interface AuthorMapper extends BaseMapper<Author> { }
package com.qgil.service; import java.util.List; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.qgil.common.pojo.DatatablesView; import com.qgil.pojo.QgilLvcgborrowrecord; import com.qgil.pojo.QgilLvcg; import com.qgil.pojo.QgilUser; @Transactional public interface LvcgService { QgilLvcg getQgilLvcgById(long parseLong); List<QgilLvcg> getQgilLvcgListByParam(QgilLvcg lvcg); DatatablesView<?> getQgilLvcgsByParam(QgilLvcg lvcg); DatatablesView<?> getQgilLvcgsByPagedParam(QgilLvcg lvcg, Integer start, Integer pageSize, String order, String orderby, QgilUser user); int addQgilLvcg(QgilLvcg lvcg); int editQgilLvcg(QgilLvcg lvcg); int borrowQgilLvcg(QgilLvcgborrowrecord record); int givebackQgilLvcg(long id); int removeQgilLvcg(List<Long> ids); int removeAll(); @Transactional(propagation=Propagation.NOT_SUPPORTED) QgilLvcg getQgilLvcgByNameId(long intid); }
/* By: Chester Descallar 978050 In my previous coursework (Last Biscuit), I repeated lines code of twice, one block for the first player copied that and did the same for the second player, this made the code lengthy and more difficult to read and the code was also very inefficient. In this coursework, I have improved this by using classes and methods to ensure that lines of codes are not repeated, instead I have used OOP which means I can make an object from a class and call methods for that object. This makes the program more efficient and readable. A Planets class that contains a constructor that allows the user to set the planet's name, mass and distance and it also contains method doing specific actions */ import java.lang.Math; import java.text.DecimalFormat; public class Planets { //Declaring the fields to be used in this class private String name; private double mass; private double distance; //format that is used to output 'doubles' such as the mass and distance private final DecimalFormat DF = new DecimalFormat("0.0##"); //Constructor to 'make' a planet object public Planets (String name, double mass, double distance) { setPlanet(name, mass, distance); } //Sets the planets using other methods which collects data that can be inputted in the fields public void setPlanet (String name, double mass, double distance) { setName(name); setMass(mass); setDistance(distance); getOrbitalPeriod(); } //Method to set the name of the planet public void setName(String name) { this.name = name; } //Method to get the name of the planet public String getName() { return name; } //Method to set the mass of the planet public void setMass(double mass) { this.mass = mass; } // Method to get the mass of the planet public double getMass() { return mass; } //Method to set the distance of the planet public void setDistance(double distance) { this.distance = distance; } //Method to get the distance of the planet public double getDistance() { return distance; } // Method to get the orbital period of the planet using the distance that is inputted. public double getOrbitalPeriod() { double period = Math.sqrt(distance * distance * distance); return period; } /* toString method that formats the way the class can be outputted when using the method so that it can easily be read.*/ public String toString() { return ("Planet " + getName() + " has a mass of "+ DF.format(getMass()) + " Earths, is " + DF.format(getDistance()) + "AU from its star, " + "and orbits in " + DF.format(getOrbitalPeriod()) + " years: could be habitable? "); } }
package iarfmoose; import java.util.ArrayList; import java.util.List; import com.github.ocraft.s2client.bot.gateway.UnitInPool; import com.github.ocraft.s2client.protocol.spatial.Point; public class Base { private Point expansionLocation; private List<UnitInPool> minerals; private List<UnitInPool> geysers; public Base() { this.expansionLocation = Point.of(0, 0); this.minerals = new ArrayList<UnitInPool>(); this.geysers = new ArrayList<UnitInPool>(); } public Base (Point expansionLocation, List<UnitInPool> minerals, List<UnitInPool> geysers) { this.expansionLocation = expansionLocation; this.minerals = minerals; this.geysers = geysers; } public Point getExpansionLocation() { return expansionLocation; } public List<UnitInPool> getMinerals() { return minerals; } public List<UnitInPool> getGeysers() { return geysers; } }
package com.mei.tododemo.activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.mei.tododemo.R; import com.mei.tododemo.commom.Api; import com.mei.tododemo.model.TodoBean; import com.mei.tododemo.presenter.SQLPersenterImpl; import com.mei.tododemo.tools.Tools; import com.mei.tododemo.view.SQLView; import java.util.List; public class AddToDoActivity extends BaseActivity implements SQLView{ private String TAG ="AddToDoActivity"; private Toolbar addToolbar; private EditText addTitle; private EditText addContent; private SQLPersenterImpl sqlPersenter; private Bundle bundle = null; private final static int ADD=1; private final static int EDITOR=0; private TodoBean todoBean = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_to_do); initView(); init(); } private void init() { bundle = getIntent().getExtras(); if (bundle !=null){ addToolbar.setTitle("EDITOR TODO"); String title = bundle.getString("title"); String content = bundle.getString("content"); String utime = bundle.getString("utime"); String ctime = bundle.getString("ctime"); int id = bundle.getInt("id"); todoBean = new TodoBean(id,title,content,ctime,utime); addTitle.setText(title); addContent.setText(content); addTitle.setFocusable(false); addTitle.setFocusableInTouchMode(false); addContent.setFocusable(false); addContent.setFocusableInTouchMode(false); } sqlPersenter = new SQLPersenterImpl(this, this); } private void initView() { addToolbar = (Toolbar) findViewById(R.id.add_toolbar); addTitle = (EditText) findViewById(R.id.add_title); addContent = (EditText) findViewById(R.id.add_content); setSupportActionBar(addToolbar); addToolbar.setOnMenuItemClickListener(onMenuItemClickListener); addToolbar.setNavigationOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { finish(); } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { if (bundle!=null){ getMenuInflater().inflate(R.menu.edit_menu,menu); }else { getMenuInflater().inflate(R.menu.add_menu,menu); } return super.onCreateOptionsMenu(menu); } Toolbar.OnMenuItemClickListener onMenuItemClickListener = new Toolbar.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem menuItem) { switch (menuItem.getItemId()){ case R.id.add_submit: saveTodo("็กฎๅฎšไฟๅญ˜ไนˆ?",ADD); break; case R.id.editor_manage: Log.d(TAG, "onMenuItemClick: ็ผ–่พ‘"); addTitle.setFocusable(true); addTitle.setFocusableInTouchMode(true); addContent.setFocusable(true); addContent.setFocusableInTouchMode(true); break; case R.id.editor_save: if (addTitle.isFocusable()) { saveTodo("็กฎๅฎšไฟๅญ˜ไนˆ?",EDITOR); } break; } return true; } }; @Override public void refreshUI(List<Object> todoBeans) { } @Override public void showError(String msg) { Log.d(TAG, "showError: "+msg); } private boolean addTodo(){ String title = addTitle.getText().toString().trim(); String content = addContent.getText().toString().trim(); String date = Tools.currentDate(); if (title==null){ Toast.makeText(this,"่ฏทๅกซๅ†™ๆ ‡้ข˜!",Toast.LENGTH_SHORT).show(); return false; } boolean b = sqlPersenter.addTodo(new TodoBean(title, content, date, date)); if (!b) { Toast.makeText(this,"ไฟๅญ˜ๅคฑ่ดฅ!",Toast.LENGTH_SHORT).show(); }else { Intent intent = new Intent(); intent.putExtra("isAdd",0); intent.putExtra("ctime",date); setResult(Api.DATA_REFRESH,intent); finish(); } return b; } private boolean editTodo(){ boolean b = false; String title = addTitle.getText().toString().trim(); String content = addContent.getText().toString().trim(); String udate = Tools.currentDate(); if (todoBean!=null) { todoBean.setContent(content); todoBean.setTitle(title); todoBean.setUtime(udate); b = sqlPersenter.updateTodo(todoBean); } if (!b) { Toast.makeText(this,"ไฟๅญ˜ๅคฑ่ดฅ!",Toast.LENGTH_SHORT).show(); }else { Intent intent = new Intent(); intent.putExtra("isAdd",1); intent.putExtra("id",todoBean.getId()); intent.putExtra("title",todoBean.getTitle()); intent.putExtra("content",todoBean.getContent()); setResult(Api.DATA_REFRESH,intent); finish(); } return false; } private void saveTodo(String msg, final int type){ AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(msg); builder.setNegativeButton("ๅ–ๆถˆ", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { dialogInterface.dismiss(); } }); builder.setPositiveButton("็กฎๅฎš", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { switch (type){ case ADD: addTodo(); break; case EDITOR: editTodo(); break; } dialogInterface.dismiss(); } }); AlertDialog alertDialog = builder.create(); alertDialog.show(); } }
package atm; import java.awt.*; import java.awt.event.*; import java.sql.*; import javax.swing.*; public class signup extends JFrame implements ActionListener{ JLabel lusername=new JLabel("User Name"); JLabel lname=new JLabel(" Name"); JLabel lpassword=new JLabel("Password"); JLabel lEmail=new JLabel("E- mail"); JLabel lDOB=new JLabel("Date Of Birth"); JLabel lbalance=new JLabel("Initial balance"); JTextField tusername= new JTextField(); JTextField tname= new JTextField(); JPasswordField tpassword= new JPasswordField(); JTextField tEmail= new JTextField(); JTextField day= new JTextField("Day"); JTextField month= new JTextField("Month"); JTextField year= new JTextField("Year"); JTextField tbalance= new JTextField(); JButton bsignup = new JButton("Register"); JPanel pane = new JPanel(); Connection cn; Statement st; PreparedStatement ps; ResultSet s; PreparedStatement ps1; public void database() { try{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); cn = DriverManager.getConnection("jdbc:odbc:ATM"); }catch(ClassNotFoundException e) { System.err.println("Failed to load driver"); e.printStackTrace(); }catch(SQLException e){ System.err.println("Unable to connect"); e.printStackTrace(); } } public signup() { setSize(320,350); setVisible(true); setResizable(false); setLocation(400,250); setTitle("Register"); add(pane); pane.setLayout(null); lusername.setBounds(5,50,120,25); pane.add(lusername); tusername.setBounds(125,50,150,25); pane.add(tusername); lname.setBounds(5,85,120,25); pane.add(lname); tname.setBounds(125,85,150,25); pane.add(tname); lpassword.setBounds(5,120,120,25); pane.add(lpassword); tpassword.setBounds(125,120,150,25); pane.add(tpassword); lEmail.setBounds(5,155,120,25); pane.add(lEmail); tEmail.setBounds(125,155,150,25); pane.add(tEmail); lDOB.setBounds(5,190, 120,25); pane.add(lDOB); day.setBounds(125, 190, 50, 25); pane.add(day); month.setBounds(175, 190, 50, 25); pane.add(month); year.setBounds(225, 190, 50, 25); pane.add(year); bsignup.setBounds(130, 300, 75, 20); pane.add(bsignup); lbalance.setBounds(5, 215, 120, 25); pane.add(lbalance); tbalance.setBounds(125, 215, 100, 25); pane.add(tbalance); bsignup.addActionListener(this); database(); } public void actionPerformed(ActionEvent e){ boolean x= true; Object source = e.getSource(); if(source == bsignup) { String us = tusername.getText(); String nm = tname.getText(); String pass = tpassword.getText(); String mail = tEmail.getText(); String d = day.getText(); String m = month.getText(); String y = year.getText(); if(us.length() == 0 || nm.length() == 0 || pass.length() == 0 || mail.length() == 0 || d.length() == 0 || m.length() == 0 || y.length() == 0) { JOptionPane.showMessageDialog(null,"Some Fields are empty"); } else { try{ st= cn.createStatement(); s=st.executeQuery("SELECT * FROM Table1 WHERE username = '" + us + "'"); while(s.next()){ String us1 =s.getString(1); JOptionPane.showMessageDialog(null,"User name exist"); x= false; } st.close(); }catch(SQLException es) { System.out.print(es); } if(x == true) try{ st= cn.createStatement(); ps = cn.prepareStatement("INSERT INTO Table1 " + " (username,name,password,email,day,month,year,balance) " + " VALUES(?,?,?,?,?,?,?,?)"); ps.setString(1,tusername.getText()); ps.setString(2,tname.getText()); ps.setString(3,tpassword.getText()); ps.setString(4,tEmail.getText()); ps.setString(5,day.getText()); ps.setString(6,month.getText()); ps.setString(7,year.getText()); ps.setString(8,tbalance.getText()); ps.executeUpdate(); JOptionPane.showMessageDialog(null,"Your New Account has been successfully Created."); st.close(); login ob1 = new login(); dispose(); }catch(SQLException ess) { System.out.print(ess); } } } } public static void main(String[] args) { signup ob = new signup(); } }
package main; /* OPERATOR -------- Operator digunakan untuk melakukan operasi pada variabel dan nilai. Pada contoh di bawah ini, kami menggunakan + operator untuk menjumlahkan dua nilai: */ public class _05_Operators { public static void main(String[] args) { int x = 900 + 89; System.out.println(x); /* Meskipun +operator sering digunakan untuk menjumlahkan dua nilai, seperti pada contoh di atas, ini juga dapat digunakan untuk menjumlahkan variabel dan nilai, atau variabel dan variabel lain: */ int a = 12; int b = 5; int c = a + b; System.out.println("hasil " + c); /* OPERATOR ARTIMATIKA ------------------- contoh : + : penjumlahan - : pengurangan / : pembagian % : sisa hasil bagi * : perkalian ++ : increment -- : decrement */ /* OPERATOR PENUGASAN ------------------ Operator Example Same As = x = 5 x = 5 += x += 3 x = x + 3 -= x -= 3 x = x - 3 *= x *= 3 x = x * 3 /= x /= 3 x = x / 3 %= x %= 3 x = x % 3 &= x &= 3 x = x & 3 |= x |= 3 x = x | 3 ^= x ^= 3 x = x ^ 3 >>= x >>= 3 x = x >> 3 <<= x <<= 3 x = x << 3 */ /* OPERATOR PERBANDINGAN --------------------- untuk membandingkan 2 nilai : Operator Name Example == Equal to x == y != Not equal x != y > Greater than x > y < Less than x < y >= Greater than or equal to x >= y <= Less than or equal to x <= y */ /* OPERATOR LOGIKA --------------- Operator logika digunakan untuk menentukan logika antara variabel atau nilai: Operator Name Description Example && Logical and Returns true if both statements are true x < 5 && x < 10 || Logical or Returns true if one of the statements is true x < 5 || x < 4 ! Logical not Reverse the result, returns false if the result is true !(x < 5 && x < 10) */ } }
import java.util.Scanner; public class DivideAndConquer_2447 { static char[][] star; static int n; public static void divideAndConquer(int row, int col, int size, boolean blank){ if(blank){ for(int i=row; i < row+size; i++){ for(int j = col; j < col+size; j++){ star[i][j] = ' '; } } return; } if(size==1){ star[row][col] = '*'; return; } int newSize = size / 3; int count=0; for(int i=row; i < row+size; i += newSize){ for(int j = col; j < col+size; j += newSize){ count++; divideAndConquer(i,j,newSize, count == 5); } } } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); n = scanner.nextInt(); star = new char[n][n]; divideAndConquer(0,0,n,false); StringBuilder sb = new StringBuilder(); for(int i=0; i < n; i++){ for(int j=0; j < n; j++){ sb.append(star[i][j]); } sb.append('\n'); } System.out.print(sb); } }