text
stringlengths
10
2.72M
package com.example.hp.dramaapp; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.RelativeLayout; import android.widget.TextView; import com.example.hp.dramaapp.Ayush.ListPlays; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { String[] quest = {"Height", "Weight", "Complexion", "Gender", "Genre", "Age"}; String[][] options = { {"Tall", "Short", "Average"}, {"Fit", "Fat", "Thin"}, {"Fair", "Dark", "Average"}, {"Male", "Female", "Flexible"}, {"Comedy", "Serious", "Flexible"}, {"Child", "Young", "Old"}}; TextView option1, option2, option3, option4, option5, option6, option7, option8, option9, questions; int counter = 0; ImageButton cancel_button_1; ImageButton cancel_button_2; ImageButton cancel_button_3; ImageButton cancel_button_4; ImageButton cancel_button_5; ImageButton cancel_button_6; ArrayList<String> answer_keys = new ArrayList(); Button submit; RelativeLayout relativeLayoutMain, relativelayoutoption1, relativelayoutoption2, relativelayoutoption3, relativelayoutoption4, relativelayoutoption5, relativelayoutoption6, relativelayoutok; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); setContentView(R.layout.activity_main); //int i=0; relativelayoutok = (RelativeLayout) findViewById(R.id.relativeLayoutOk); relativeLayoutMain = (RelativeLayout) findViewById(R.id.relativeLayout1); relativelayoutoption1 = (RelativeLayout) findViewById(R.id.relativeLayoutoption1); relativelayoutoption2 = (RelativeLayout) findViewById(R.id.relativeLayoutoption2); relativelayoutoption3 = (RelativeLayout) findViewById(R.id.relativeLayoutoption3); relativelayoutoption4 = (RelativeLayout) findViewById(R.id.relativeLayoutoption4); relativelayoutoption5 = (RelativeLayout) findViewById(R.id.relativeLayoutoption5); relativelayoutoption6 = (RelativeLayout) findViewById(R.id.relativeLayoutoption6); submit = (Button) findViewById(R.id.submit); visibilty_for_relative_layouts(); option1 = (TextView) findViewById(R.id.option1); option2 = (TextView) findViewById(R.id.option2); option3 = (TextView) findViewById(R.id.option3); option4 = (TextView) findViewById(R.id.answer1); //option4.setVisibility(View.GONE); option5 = (TextView) findViewById(R.id.answer2); //option5.setVisibility(View.GONE); option6 = (TextView) findViewById(R.id.answer3); //option6.setVisibility(View.GONE); option7 = (TextView) findViewById(R.id.answer4); //option7.setVisibility(View.GONE); option8 = (TextView) findViewById(R.id.answer5); //option8.setVisibility(View.GONE); option9 = (TextView) findViewById(R.id.answer6); //option9.setVisibility(View.GONE); cancel_button_1 = (ImageButton) findViewById(R.id.cancelButton1); cancel_button_2 = (ImageButton) findViewById(R.id.cancelButton2); cancel_button_3 = (ImageButton) findViewById(R.id.cancelButton3); cancel_button_4 = (ImageButton) findViewById(R.id.cancelButton4); cancel_button_5 = (ImageButton) findViewById(R.id.cancelButton5); cancel_button_6 = (ImageButton) findViewById(R.id.cancelButton6); questions = (TextView) findViewById(R.id.question); option1.setText(options[counter][0]); option1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int i = 1; features(i); } }); option2.setText(options[counter][1]); option2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int i = 2; features(i); } }); option3.setText(options[counter][2]); option3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { int i = 3; features(i); } }); cancel_button_1.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { answer_keys.clear(); //counter=0; ini(); visibilty_for_relative_layouts(); } }); cancel_button_2.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { counter = 1; remove_keys(1); setQuestion2(); relativelayoutok.setVisibility(View.GONE); relativelayoutoption2.setVisibility(View.GONE); relativelayoutoption3.setVisibility(View.GONE); relativelayoutoption4.setVisibility(View.GONE); relativelayoutoption5.setVisibility(View.GONE); relativelayoutoption6.setVisibility(View.GONE); } }); cancel_button_3.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { counter = 2; remove_keys(2); setQuestion3(); relativelayoutok.setVisibility(View.GONE); relativelayoutoption3.setVisibility(View.GONE); relativelayoutoption4.setVisibility(View.GONE); relativelayoutoption5.setVisibility(View.GONE); relativelayoutoption6.setVisibility(View.GONE); } }); cancel_button_4.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { counter = 3; remove_keys(3); setQuestion4(); relativelayoutok.setVisibility(View.GONE); relativelayoutoption4.setVisibility(View.GONE); relativelayoutoption5.setVisibility(View.GONE); relativelayoutoption6.setVisibility(View.GONE); } }); cancel_button_5.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { counter = 4; remove_keys(4); setQuestion5(); relativelayoutok.setVisibility(View.GONE); relativelayoutoption5.setVisibility(View.GONE); relativelayoutoption6.setVisibility(View.GONE); } }); cancel_button_6.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { counter = 5; remove_keys(5); setQuestion6(); relativelayoutok.setVisibility(View.GONE); relativelayoutoption6.setVisibility(View.GONE); } }); submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { //String choice[]= (String[]) answer_keys.toArray(); String choice1 = ""; // SharedPreferences sp = getSharedPreferences("MM", 0); // String params = sp.getString("KK", ""); //try { // FirebaseDatabase database = FirebaseDatabase.getInstance(); // final DatabaseReference myRef1 = database.getReference(params.replaceAll("[^A-Za-z]", "")); for (String s : answer_keys) { choice1 += "," + s; } //} // catch (Exception e) // { // // } StringBuilder sb = new StringBuilder(choice1); sb.deleteCharAt(0); SharedPreferences sp1 = getSharedPreferences("Choices", 0); SharedPreferences.Editor ed1 = sp1.edit(); ed1.putString("Parameters", sb.toString()); ed1.commit(); Intent intent=new Intent(MainActivity.this, ListPlays.class); startActivity(intent); // Toast.makeText(getApplicationContext(),choice1,Toast.LENGTH_LONG).show(); } }); } public void features(int i) { relativeLayoutMain.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.right_slide_in)); counter++; try { questions.setText(quest[counter]); } catch (Exception e) { questions.setText(quest[counter - 1]); } if (counter == 1) { if (i == 1) option4.setText(option1.getText()); else if (i == 2) option4.setText(option2.getText()); else option4.setText(option3.getText()); //option4.setVisibility(View.VISIBLE); relativelayoutoption1.setVisibility(View.VISIBLE); //relative layout option1 set visibilty true answer_keys.add(option4.getText().toString()); option1.setText(options[counter][0]); option2.setText(options[counter][1]); option3.setText(options[counter][2]); } else if (counter == 2) { // counter++; questions.setText(quest[counter]); if (i == 1) option5.setText(option1.getText()); else if (i == 2) option5.setText(option2.getText()); else option5.setText(option3.getText()); //option5.setVisibility(View.VISIBLE); relativelayoutoption2.setVisibility(View.VISIBLE); //relative layout option2 set visibilty true answer_keys.add(option5.getText().toString()); option1.setText(options[counter][0]); option2.setText(options[counter][1]); option3.setText(options[counter][2]); } else if (counter == 3) { // counter++; questions.setText(quest[counter]); if (i == 1) option6.setText(option1.getText()); else if (i == 2) option6.setText(option2.getText()); else option6.setText(option3.getText()); //option6.setVisibility(View.VISIBLE); relativelayoutoption3.setVisibility(View.VISIBLE); //relative layout option3 set visibilty true answer_keys.add(option6.getText().toString()); option1.setText(options[counter][0]); option2.setText(options[counter][1]); option3.setText(options[counter][2]); } else if (counter == 4) { // counter++; questions.setText(quest[counter]); if (i == 1) option7.setText(option1.getText()); else if (i == 2) option7.setText(option2.getText()); else option7.setText(option3.getText()); // option7.setVisibility(View.VISIBLE); relativelayoutoption4.setVisibility(View.VISIBLE); //relative layout option4 set visibilty true answer_keys.add(option7.getText().toString()); option1.setText(options[counter][0]); option2.setText(options[counter][1]); option3.setText(options[counter][2]); } else if (counter == 5) { // counter++; questions.setText(quest[counter]); if (i == 1) option8.setText(option1.getText()); else if (i == 2) option8.setText(option2.getText()); else option8.setText(option3.getText()); // option8.setVisibility(View.VISIBLE); relativelayoutoption5.setVisibility(View.VISIBLE); //relative layout option5 set visibilty true answer_keys.add(option8.getText().toString()); option1.setText(options[counter][0]); option2.setText(options[counter][1]); option3.setText(options[counter][2]); } else if (counter == 6) { // counter++; counter = -1; //questions.setText(quest[counter]); if (i == 1) option9.setText(option1.getText()); else if (i == 2) option9.setText(option2.getText()); else option9.setText(option3.getText()); // option9.setVisibility(View.VISIBLE); relativelayoutoption6.setVisibility(View.VISIBLE); //relative layout option6 set visibilty true answer_keys.add(option9.getText().toString()); relativelayoutok.setVisibility(View.VISIBLE); relativelayoutok.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.in_middle)); // option1.setText(options[counter][0]); // option2.setText(options[counter][1]); // option3.setText(options[counter][2]); } } public void remove_keys(int j) { for (; j < answer_keys.size(); j++) answer_keys.remove(j); } public void ini() { counter = 0; questions.setText("Height"); option1.setText(options[0][0]); option2.setText(options[0][1]); option3.setText(options[0][2]); } public void visibilty_for_relative_layouts() { relativelayoutoption1.setVisibility(View.GONE); relativelayoutoption2.setVisibility(View.GONE); relativelayoutoption3.setVisibility(View.GONE); relativelayoutoption4.setVisibility(View.GONE); relativelayoutoption5.setVisibility(View.GONE); relativelayoutoption6.setVisibility(View.GONE); relativelayoutok.setVisibility(View.GONE); } public void setQuestion2() { relativeLayoutMain.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.right_slide_in)); questions.setText(quest[1]); option1.setText(options[1][0]); option2.setText(options[1][1]); option3.setText(options[1][2]); } public void setQuestion3() { relativeLayoutMain.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.right_slide_in)); questions.setText(quest[2]); option1.setText(options[2][0]); option2.setText(options[2][1]); option3.setText(options[2][2]); } public void setQuestion4() { relativeLayoutMain.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.right_slide_in)); questions.setText(quest[3]); option1.setText(options[3][0]); option2.setText(options[3][1]); option3.setText(options[3][2]); } public void setQuestion5() { relativeLayoutMain.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.right_slide_in)); questions.setText(quest[4]); option1.setText(options[4][0]); option2.setText(options[4][1]); option3.setText(options[4][2]); } public void setQuestion6() { relativeLayoutMain.startAnimation(AnimationUtils.loadAnimation(getApplicationContext(), R.anim.right_slide_in)); questions.setText(quest[5]); option1.setText(options[5][0]); option2.setText(options[5][1]); option3.setText(options[5][2]); } }
package com.tencent.mm.ui; import android.view.View; import android.view.View.OnClickListener; import com.tencent.mm.sdk.platformtools.x; public abstract class u implements OnClickListener { private long ngz = -1; public abstract void aBU(); public void onClick(View view) { x.i("MicroMsg.MMCustomClickListener", "button onclick"); if (this.ngz != -1) { if ((System.nanoTime() - this.ngz) / 1000000 < 3000) { x.i("MicroMsg.MMCustomClickListener", "click time limited limitetime:%d, delaytime:%d", new Object[]{Long.valueOf((System.nanoTime() - this.ngz) / 1000000), Long.valueOf(3000)}); return; } } this.ngz = System.nanoTime(); aBU(); } }
package br.com.ecommerce.pages.retaguarda.cadastros.cores; import static br.com.ecommerce.config.DriverFactory.getDriver; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.PageFactory; import br.com.ecommerce.config.BasePage; import br.com.ecommerce.util.Log; import br.com.ecommerce.util.Utils; public class PageCores extends BasePage { public PageCores() { PageFactory.initElements(getDriver(), this); } @FindBy(xpath = "//h1") private WebElement titleCoresEstilos; @FindBy(xpath = "//*[@href='https://ecommerce-rails-matheus.herokuapp.com/admin/colors/new']") private WebElement btNovo; @FindBy(xpath = "//th[text()='Tรญtulo']") private WebElement labelTitutlo; @FindBy(xpath = "//th[text()='Cor']") private WebElement labelCor; @FindBy(xpath = "//a[@class='btn btn-default'][contains(.,'Ativar')]") private WebElement btAtivar; @FindBy(xpath = "//tbody//../a[contains(.,'Editar')]") private WebElement btEditar; @FindBy(xpath = "//tbody//../a[contains(.,'Remover')]") private WebElement btRemover; @FindBy(xpath = "//*[@id='main-content']/section/div[2]['ร—']") private WebElement msgSucesso; public void navegarParaPageInclusaoCores() { getDriver().navigate().to(getDriver().getCurrentUrl()+"/new"); } public void validarCorInserida(String cor) { Utils.assertTrue("Cor ["+cor+"] nรฃo estรก sendo exibida na listagem de cores", existsColor(cor)); Log.info("Cor ["+cor+"] inserida com sucesso"); } public void validarCorRemovida(String cor) { Utils.assertFalse("Cor ["+cor+"] ainda estรก sendo exibida na listagem de cores", existsColor(cor)); Log.info("Cor ["+cor+"] removida com sucesso"); } public boolean existsColor(String str){ Log.info("Verificando se cor ["+str+"] estรก cadastrada..."); By cor = By.xpath("//*[@class='table table-striped']//../tr/td[text()='"+str+"']"); exibeRegistroVisivel(cor, btNovo); return isVisibility(cor); } public void removerCor(String cor) { Log.info("Removendo cor ["+cor+"]..."); By by = By.xpath("//*[@class='table table-striped']//../tr/td[text()='"+cor+"']//../td/a[@data-method='delete']"); exibeRegistroVisivel(by, btNovo); WebElement removerCor = getDriver().findElement(by); click(removerCor); confirmarAlerta(); validarMsgSucessoExclusao(); Log.info("Cor ["+cor+"] removida..."); } public void validarMsgSucessoExclusao(){ Log.info("Validando mensagem de feedback de sucesso..."); aguardarElementoVisivel(msgSucesso); Utils.assertEquals(getTextElement(msgSucesso).replace("ร—", "").trim(), "Registro foi apagado com sucesso."); Log.info("Mensagem de feedback validada."); } public void verificarOrtografiaPageCores(){ Log.info("Verificando ortografia da pรกgina cores..."); Utils.assertEquals(getTextElement(titleCoresEstilos), "Cores/Estilos"); Utils.assertEquals(getTextElement(btNovo) , "Novo"); Utils.assertEquals(getTextElement(labelTitutlo) , "Tรญtulo"); Utils.assertEquals(getTextElement(labelCor) , "Cor"); Utils.assertEquals(getTextElement(btAtivar) , "Ativar"); Log.info("Ortografia validada com sucesso."); } }
package ve.com.mastercircuito.objects; public class UserType { private Integer id; private String type; public UserType() { } public UserType(Integer id, String type) { super(); this.id = id; this.type = type; } public UserType(UserType userTypeInfo) { this.id = userTypeInfo.getId(); this.type = userTypeInfo.getType(); } public String getType() { return this.type; } public void setType(String type) { this.type = type; } public Integer getId() { return this.id; } }
package HW7; import java.lang.reflect.Array; import java.util.Arrays; /*changes made : 1) The initialize variable is set to 2 instead of 1. Otherwise if it is 1,the length of array -1 will be be 0 in add function and the check will be false 2) Added the logic to double the size array when it reaches the limit int the add function. 3) Since dividing by zero leads to answer as infinity, an additional check is added to check whether the variable is 0 in the evaluate function 4) In hasnext function the check is modified to return (interatorPosition < filled); instead of return (interatorPosition <= filled); 5) In the contain() function the <= symbol changed to < since it will go out of bounds of the array if an element is not present*/ public class StorageOrder { int initialSize = 2; int filled = 0; Integer[] data = new Integer[initialSize]; Integer[] localData; static int interatorPosition = 0; public StorageOrder() { for (int index = 0; index < data.length - 1; index++) { data[index] = null; } } public void copy(Integer[] to, Integer[] from) { for (int index = 0; index < filled; index++) { to[index] = from[index]; } } public void sort() { if (data.length == 1) return; localData = new Integer[filled]; copy(localData, data); for (int index = 0; index < localData.length - 1; index++) { for (int walker = 0; walker < localData.length - index - 1; walker++) { Integer left = localData[walker]; Integer right = localData[walker + 1]; if (left.compareTo(right) > 0) { Integer tmp = localData[walker]; localData[walker] = localData[walker + 1]; localData[walker + 1] = tmp; } } } copy(data, localData); } public String toInteger() { String result = ""; for (int index = 0; index < data.length - 1; index++) { if (data[index] != null) result = "" + index + ". " + data[index] + ((index == data.length - 1) ? "." : ",\n") + result; } return result; } public boolean add(Integer e) { for (int index = 0; index < data.length-1; index++){ if (data[index] == null) { data[index] = e; filled++; sort(); return true; } } if (filled < data.length) { localData = new Integer[data.length*2]; copy(localData, data); data = localData; return (add(e)); } return false; } public boolean remove(Integer e) { for (int index = 0; index < filled; index++) { if (data[index].compareTo(e) == 0) { data[index] = data[filled - 1]; data[filled - 1] = null; filled--; sort(); return true; } } return false; } public boolean contain(Integer e) { for (int index = 0; index < filled; index++) { if (data[index].compareTo(e) == 0) return true; } return false; } public int size() { return filled - 1; } public void startFromBeginning() { interatorPosition = 0; } public boolean hasNext() { return (interatorPosition < filled); } public Integer next() { return data[interatorPosition++]; } public boolean addAll(StorageOrder c) { while (c.hasNext()) { add(c.next()); } return true; } public double evaluate() { double result = 0; while (hasNext()) { Integer aInteger = next(); // if (aInteger!=0) { result += 1.0 / aInteger; //} } return result; } public static void main(String args[]) { StorageOrder aStorageOrder = new StorageOrder(); aStorageOrder.add(1); aStorageOrder.add(0); aStorageOrder.add(2); System.out.println("aStorageOrder.evaluate(); " + aStorageOrder.evaluate()); System.out.println(aStorageOrder); System.out.println("aStorageOrder.contains(a) " + aStorageOrder.contain(0)); System.out.println("aStorageOrder.contains(f) " + aStorageOrder.contain(4)); System.out.println("aStorageOrder.remove(a) " + aStorageOrder.remove(2)); System.out.println("aStorageOrder.remove(a) " + aStorageOrder.remove(1)); System.out.println(aStorageOrder); aStorageOrder.startFromBeginning(); while ( aStorageOrder.hasNext() ) { System.out.println(" " + aStorageOrder.next() ) ; } } }
// // 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.XmlElements; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for EquipmentElementType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="EquipmentElementType"> * &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="Description" type="{http://www.mesa.org/xml/B2MML-V0600}DescriptionType" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="EquipmentElementType" type="{http://www.mesa.org/xml/B2MML-V0600}EquipmentElementTypeType"/> * &lt;element name="EquipmentElementLevel" type="{http://www.mesa.org/xml/B2MML-V0600}EquipmentElementLevelType"/> * &lt;element name="ClassInstanceAssociation" type="{http://www.mesa.org/xml/B2MML-V0600}ClassInstanceAssociationType" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="Property" type="{http://www.mesa.org/xml/B2MML-V0600}EquipmentElementPropertyType" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="EquipmentProceduralElementClass" type="{http://www.mesa.org/xml/B2MML-V0600}EquipmentProceduralElementClassType" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="EquipmentProceduralElement" type="{http://www.mesa.org/xml/B2MML-V0600}EquipmentProceduralElementType" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="EquipmentConnection" type="{http://www.mesa.org/xml/B2MML-V0600}EquipmentConnectionType" maxOccurs="unbounded" minOccurs="0"/> * &lt;choice maxOccurs="unbounded" minOccurs="0"> * &lt;element name="EquipmentElement" type="{http://www.mesa.org/xml/B2MML-V0600}EquipmentElementType"/> * &lt;element name="EquipmentElementID" type="{http://www.mesa.org/xml/B2MML-V0600}EquipmentElementIDType"/> * &lt;/choice> * &lt;group ref="{http://www.mesa.org/xml/B2MML-V0600-AllExtensions}EquipmentElement" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "EquipmentElementType", propOrder = { "id", "description", "equipmentElementType", "equipmentElementLevel", "classInstanceAssociation", "property", "equipmentProceduralElementClass", "equipmentProceduralElement", "equipmentConnection", "equipmentElementOrEquipmentElementID" }) public class EquipmentElementType { @XmlElement(name = "ID", required = true) protected IDType id; @XmlElement(name = "Description") protected List<DescriptionType> description; @XmlElement(name = "EquipmentElementType", required = true) protected EquipmentElementTypeType equipmentElementType; @XmlElement(name = "EquipmentElementLevel", required = true) protected EquipmentElementLevelType equipmentElementLevel; @XmlElement(name = "ClassInstanceAssociation") protected List<ClassInstanceAssociationType> classInstanceAssociation; @XmlElement(name = "Property") protected List<EquipmentElementPropertyType> property; @XmlElement(name = "EquipmentProceduralElementClass") protected List<EquipmentProceduralElementClassType> equipmentProceduralElementClass; @XmlElement(name = "EquipmentProceduralElement") protected List<EquipmentProceduralElementType> equipmentProceduralElement; @XmlElement(name = "EquipmentConnection") protected List<EquipmentConnectionType> equipmentConnection; @XmlElements({ @XmlElement(name = "EquipmentElement", type = EquipmentElementType.class), @XmlElement(name = "EquipmentElementID", type = EquipmentElementIDType.class) }) protected List<Object> equipmentElementOrEquipmentElementID; /** * 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 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; } /** * Gets the value of the equipmentElementType property. * * @return * possible object is * {@link EquipmentElementTypeType } * */ public EquipmentElementTypeType getEquipmentElementType() { return equipmentElementType; } /** * Sets the value of the equipmentElementType property. * * @param value * allowed object is * {@link EquipmentElementTypeType } * */ public void setEquipmentElementType(EquipmentElementTypeType value) { this.equipmentElementType = value; } /** * Gets the value of the equipmentElementLevel property. * * @return * possible object is * {@link EquipmentElementLevelType } * */ public EquipmentElementLevelType getEquipmentElementLevel() { return equipmentElementLevel; } /** * Sets the value of the equipmentElementLevel property. * * @param value * allowed object is * {@link EquipmentElementLevelType } * */ public void setEquipmentElementLevel(EquipmentElementLevelType value) { this.equipmentElementLevel = value; } /** * Gets the value of the classInstanceAssociation 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 classInstanceAssociation property. * * <p> * For example, to add a new item, do as follows: * <pre> * getClassInstanceAssociation().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link ClassInstanceAssociationType } * * */ public List<ClassInstanceAssociationType> getClassInstanceAssociation() { if (classInstanceAssociation == null) { classInstanceAssociation = new ArrayList<ClassInstanceAssociationType>(); } return this.classInstanceAssociation; } /** * Gets the value of the property 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 property property. * * <p> * For example, to add a new item, do as follows: * <pre> * getProperty().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link EquipmentElementPropertyType } * * */ public List<EquipmentElementPropertyType> getProperty() { if (property == null) { property = new ArrayList<EquipmentElementPropertyType>(); } return this.property; } /** * Gets the value of the equipmentProceduralElementClass 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 equipmentProceduralElementClass property. * * <p> * For example, to add a new item, do as follows: * <pre> * getEquipmentProceduralElementClass().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link EquipmentProceduralElementClassType } * * */ public List<EquipmentProceduralElementClassType> getEquipmentProceduralElementClass() { if (equipmentProceduralElementClass == null) { equipmentProceduralElementClass = new ArrayList<EquipmentProceduralElementClassType>(); } return this.equipmentProceduralElementClass; } /** * Gets the value of the equipmentProceduralElement 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 equipmentProceduralElement property. * * <p> * For example, to add a new item, do as follows: * <pre> * getEquipmentProceduralElement().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link EquipmentProceduralElementType } * * */ public List<EquipmentProceduralElementType> getEquipmentProceduralElement() { if (equipmentProceduralElement == null) { equipmentProceduralElement = new ArrayList<EquipmentProceduralElementType>(); } return this.equipmentProceduralElement; } /** * Gets the value of the equipmentConnection 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 equipmentConnection property. * * <p> * For example, to add a new item, do as follows: * <pre> * getEquipmentConnection().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link EquipmentConnectionType } * * */ public List<EquipmentConnectionType> getEquipmentConnection() { if (equipmentConnection == null) { equipmentConnection = new ArrayList<EquipmentConnectionType>(); } return this.equipmentConnection; } /** * Gets the value of the equipmentElementOrEquipmentElementID 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 equipmentElementOrEquipmentElementID property. * * <p> * For example, to add a new item, do as follows: * <pre> * getEquipmentElementOrEquipmentElementID().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link EquipmentElementType } * {@link EquipmentElementIDType } * * */ public List<Object> getEquipmentElementOrEquipmentElementID() { if (equipmentElementOrEquipmentElementID == null) { equipmentElementOrEquipmentElementID = new ArrayList<Object>(); } return this.equipmentElementOrEquipmentElementID; } }
package com.tt.miniapp.secrecy.ui; import android.app.Application; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.drawable.Drawable; import android.graphics.drawable.GradientDrawable; import android.text.SpannableString; import android.text.TextUtils; import android.text.style.ImageSpan; import android.view.View; import android.view.ViewGroup; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import com.tt.miniapp.secrecy.SecrecyEntity; import com.tt.miniapphost.AppbrandApplication; import com.tt.miniapphost.AppbrandContext; import com.tt.miniapphost.util.CharacterUtils; import com.tt.miniapphost.util.UIUtils; public class MenuItemHelper { private static int TIP_HEIGHT = 28; private static int TIP_IMAGE_SIZE = 16; private static int TIP_MARGIN_V = 26; private static int TIP_PADDING_H = 12; private SecrecyUIHelper mUIHelper; MenuItemHelper(SecrecyUIHelper paramSecrecyUIHelper) { this.mUIHelper = paramSecrecyUIHelper; Application application = AppbrandContext.getInst().getApplicationContext(); TIP_PADDING_H = (int)UIUtils.dip2Px((Context)application, TIP_PADDING_H); TIP_HEIGHT = (int)UIUtils.dip2Px((Context)application, TIP_HEIGHT); TIP_MARGIN_V = (int)UIUtils.dip2Px((Context)application, TIP_MARGIN_V); TIP_IMAGE_SIZE = (int)UIUtils.dip2Px((Context)application, TIP_IMAGE_SIZE); } private CharSequence getTextSuffix(Context paramContext, int paramInt) { String str = getTipStr(paramContext, paramInt); Drawable drawable = paramContext.getDrawable(2097479710); if (TextUtils.isEmpty(str) || drawable == null) return paramContext.getString(2097742025); StringBuilder stringBuilder = new StringBuilder(str); paramInt = (int)UIUtils.dip2Px(paramContext, 11.0F); drawable.setBounds(0, 0, paramInt, paramInt); drawable.setColorFilter(paramContext.getResources().getColor(2097348654), PorterDuff.Mode.SRC_IN); stringBuilder.append(' '); stringBuilder.append('>'); CenterImageSpan centerImageSpan = new CenterImageSpan(drawable, 1); SpannableString spannableString = new SpannableString(stringBuilder); spannableString.setSpan(centerImageSpan, stringBuilder.length() - 1, stringBuilder.length(), 17); return (CharSequence)spannableString; } private Drawable getTipIcon(Context paramContext, int paramInt) { return (12 == paramInt) ? paramContext.getDrawable(2097479782) : ((13 == paramInt) ? paramContext.getDrawable(2097479783) : null); } private String getTipStr(Context paramContext, int paramInt) { int i; if (AppbrandApplication.getInst().getAppInfo().isGame()) { i = 2097741950; } else { i = 2097741949; } String str2 = paramContext.getString(i); String str1 = null; if (12 == paramInt) { str1 = paramContext.getString(2097741924); } else if (13 == paramInt) { str1 = paramContext.getString(2097741831); } return TextUtils.isEmpty(str1) ? CharacterUtils.empty() : paramContext.getString(2097742017, new Object[] { str2, str1 }); } int addSecrecyTip(RelativeLayout paramRelativeLayout, View.OnClickListener paramOnClickListener, int paramInt) { Context context = paramRelativeLayout.getContext(); SecrecyEntity secrecyEntity = this.mUIHelper.getShownEntity(); if (secrecyEntity != null && !this.mUIHelper.isSecrecyNotStarted(secrecyEntity)) { String str = getTipStr(context, secrecyEntity.type); if (!TextUtils.isEmpty(str)) { Drawable drawable = getTipIcon(context, secrecyEntity.type); if (drawable == null) return 0; LinearLayout linearLayout = new LinearLayout(context); linearLayout.setId(paramInt); linearLayout.setOrientation(0); linearLayout.setGravity(16); paramInt = TIP_PADDING_H; linearLayout.setPadding(paramInt, 0, paramInt, 0); linearLayout.setOnClickListener(paramOnClickListener); GradientDrawable gradientDrawable = new GradientDrawable(); gradientDrawable.setShape(0); gradientDrawable.setColor(context.getResources().getColor(2097348680)); gradientDrawable.setCornerRadius(TIP_HEIGHT / 2.0F); linearLayout.setBackground((Drawable)gradientDrawable); ImageView imageView = new ImageView(context); imageView.setImageDrawable(drawable); paramInt = TIP_IMAGE_SIZE; linearLayout.addView((View)imageView, (ViewGroup.LayoutParams)new LinearLayout.LayoutParams(paramInt, paramInt)); TextView textView = new TextView(context); textView.setText(str); textView.setTextSize(12.0F); textView.setIncludeFontPadding(false); textView.setTextColor(-1728053248); LinearLayout.LayoutParams layoutParams1 = new LinearLayout.LayoutParams(-2, -2); layoutParams1.leftMargin = (int)UIUtils.dip2Px(context, 2.0F); linearLayout.addView((View)textView, (ViewGroup.LayoutParams)layoutParams1); RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(-2, TIP_HEIGHT); layoutParams.addRule(10); layoutParams.addRule(14); layoutParams.topMargin = TIP_MARGIN_V; layoutParams.bottomMargin = 0; paramRelativeLayout.addView((View)linearLayout, 0, (ViewGroup.LayoutParams)layoutParams); return TIP_MARGIN_V + TIP_HEIGHT; } } return 0; } void addSecrecyTip(LinearLayout paramLinearLayout, View.OnClickListener paramOnClickListener) { Context context = paramLinearLayout.getContext(); TextView textView = new TextView(context); SecrecyEntity secrecyEntity = this.mUIHelper.getShownEntity(); if (secrecyEntity != null) { if (this.mUIHelper.isSecrecyNotStarted(secrecyEntity)) return; textView.setGravity(17); textView.setText(getTextSuffix(context, secrecyEntity.type)); textView.setTextSize(15.0F); textView.setTextColor(context.getResources().getColor(2097348654)); textView.setOnClickListener(paramOnClickListener); paramLinearLayout.addView((View)textView, 0, (ViewGroup.LayoutParams)new LinearLayout.LayoutParams(-1, (int)UIUtils.dip2Px(context, 44.0F))); } } static class CenterImageSpan extends ImageSpan { CenterImageSpan(Drawable param1Drawable, int param1Int) { super(param1Drawable, param1Int); } public void draw(Canvas param1Canvas, CharSequence param1CharSequence, int param1Int1, int param1Int2, float param1Float, int param1Int3, int param1Int4, int param1Int5, Paint param1Paint) { param1Canvas.save(); Drawable drawable = getDrawable(); Paint.FontMetricsInt fontMetricsInt = param1Paint.getFontMetricsInt(); param1Canvas.translate(param1Float, ((fontMetricsInt.descent + param1Int4 + param1Int4 + fontMetricsInt.ascent) / 2 - (drawable.getBounds()).bottom / 2)); drawable.draw(param1Canvas); param1Canvas.restore(); } } } /* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\secrec\\ui\MenuItemHelper.class * Java compiler version: 6 (50.0) * JD-Core Version: 1.1.3 */
import java.util.List; import interfaces.IMenu; import loader.PluginLoader; public class Configuration implements IMenu { @Override public void goTo(char key){ if ((key == 'c' || key == 'C')) { System.out.println("Configuration"); System.out.println("Difficulty - Press D"); System.out.println("Map - Press M"); System.out.println("Character - Press C"); // boolean validKey = false; // // char key = 'x'; // // while (!validKey) { // key = scanner.next(".").charAt(0); // // List<IConfigurations> configOptions = PluginLoader.load(IConfigurations.class); // for (IConfigurations configOption : configOptions) { // validKey = true; // } // } } }
package br.com.beblue.lojadisco.http.corporesposta; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonProperty; @JsonIgnoreProperties(ignoreUnknown = true) public class CorpoAlbum { @JsonProperty("albums") private Albuns albuns; public Albuns getAlbuns() { return albuns; } public void setAlbuns(Albuns albuns) { this.albuns = albuns; } }
package ru.ibs.intern.entity; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import javax.persistence.*; @Entity @AllArgsConstructor @NoArgsConstructor @Table @Data public class Currency { @Id private String currencyCode; private Double currencyRate; private String currencyName; }
package com.wuyan.masteryi.admin.entity; import lombok.Data; /** * @Author: Zhao Shuqing * @Date: 2021/7/6 10:30 * @Description: */ @Data public class User { private Integer userId; private String userName; private String userPwd; private String userImgUrl; private String address; private String phoneNum; private float consumption; }
/** **************************************************************************** * Copyright (c) The Spray Project. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Spray Dev Team - initial API and implementation **************************************************************************** */ package org.eclipselabs.spray.runtime.graphiti.wizard; import org.apache.log4j.Logger; import org.eclipse.core.resources.IFile; import org.eclipse.swt.widgets.Shell; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPage; import org.eclipse.ui.PartInitException; import org.eclipse.ui.ide.IDE; import org.eclipse.ui.wizards.newresource.BasicNewResourceWizard; import javax.inject.Inject; /** * Copied from org.eclipse.xtext.ui.util in order to avoid dependency on org.eclipse.xtext.ui * Provide some limited but useful utilities when dealing with files that are currently in an intermediate state, e.g. * the builder did not pick up their contents yet. * * @author Michael Clay */ public class FileOpener { private static final Logger logger = Logger.getLogger(FileOpener.class); @Inject private IWorkbench workbench; /** * @param file * the file that should be selected. May be <code>null</code>. */ public void selectAndReveal(IFile file) { BasicNewResourceWizard.selectAndReveal(file, workbench.getActiveWorkbenchWindow()); } /** * @param shell * the parent shell. May not be <code>null</code> * @param file * that should be selected. May not be <code>null</code>. */ public void openFileToEdit(final Shell shell, final IFile file) { shell.getDisplay().asyncExec(new Runnable() { public void run() { final IWorkbenchPage page = workbench.getActiveWorkbenchWindow().getActivePage(); try { IDE.openEditor(page, file, true); } catch (final PartInitException e) { logger.error(e.getMessage(), e); } } }); } }
package br.com.allerp.allbanks.entity.user; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.Inheritance; import javax.persistence.InheritanceType; import javax.persistence.OneToOne; import javax.persistence.Table; import br.com.allerp.allbanks.entity.GenericEntity; import br.com.allerp.allbanks.entity.conta.Titular; import br.com.allerp.allbanks.entity.enums.Perfis; @Entity @Table(name = "USER") // Esta anotaรงรฃo identifica que a estratรฉgia de heranรงa serรก feita atravรฉs de chave estrangeira @Inheritance(strategy = InheritanceType.JOINED) public class User extends GenericEntity { private static final long serialVersionUID = -3417915934417211134L; @Column(nullable = false) private String email; @Column(nullable = false) private String psw; @Column(nullable = false, unique = true, length = 50) private String userAccess; @Column(nullable = false, length = 20) @Enumerated(EnumType.ORDINAL) private Perfis perfil; @OneToOne(mappedBy="user", cascade=CascadeType.REMOVE) private Titular titular; public String getEmail() { if(email == null) { return ""; } return email; } public void setEmail(String email) { this.email = email; } public String getPsw() { if(psw == null) { return ""; } return psw; } public void setPsw(String psw) { this.psw = psw; } public String getUserAccess() { if(userAccess == null) { return ""; } return userAccess; } public void setUserAccess(String userAccess) { this.userAccess = userAccess; } public Perfis getPerfil() { return perfil; } public void setPerfil(Perfis perfil) { this.perfil = perfil; } public Titular getTitular() { if(titular != null) { return titular; } return new Titular(); } }
package com.test.login; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; import com.constants.PathConstants; public class Baseclass { WebDriver driver; @BeforeMethod public void InitDriver(){ System.setProperty("webdriver.chrome.driver", PathConstants.getDriverPath()); driver = new ChromeDriver(); driver.get("http://localhost:3000/"); } @AfterMethod public void QuitDriver(){ driver.quit(); } }
package com.tencent.d.b.f; import android.os.Handler; import android.os.HandlerThread; import android.os.Looper; import com.tencent.d.a.c.c; public class g { private static volatile g vmA = null; private Handler vmB = null; private Handler vmC = null; private g() { HandlerThread handlerThread = new HandlerThread("SoterGenKeyHandlerThreadName"); handlerThread.start(); if (handlerThread.getLooper() != null) { this.vmB = new Handler(handlerThread.getLooper()); } else { c.e("Soter.SoterTaskThread", "soter: task looper is null! use main looper as the task looper", new Object[0]); this.vmB = new Handler(Looper.getMainLooper()); } this.vmC = new Handler(Looper.getMainLooper()); } public static g cGb() { if (vmA != null) { return vmA; } g gVar; synchronized (g.class) { if (vmA == null) { vmA = new g(); } gVar = vmA; } return gVar; } public final void C(Runnable runnable) { this.vmB.post(runnable); } public final void l(Runnable runnable, long j) { this.vmB.postDelayed(runnable, j); } public final void A(Runnable runnable) { this.vmC.post(runnable); } }
package com.edu.design.adapter; public interface Movable { double getSpeed(); }
package fr.clivana.lemansnews.dao; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import fr.clivana.lemansnews.entity.Evenement; import fr.clivana.lemansnews.utils.Formatage; import fr.clivana.lemansnews.utils.Params; import fr.clivana.lemansnews.utils.database.DatabaseLeMansNews; import fr.clivana.lemansnews.utils.database.NomsSQL; public class EventsDAO { private SQLiteDatabase dbClivana; private DatabaseLeMansNews dbClivanaHelper; // constructeur public EventsDAO(Context context) { super(); dbClivanaHelper = new DatabaseLeMansNews(context, NomsSQL.BASE_NOM, null, NomsSQL.BASE_VERSION); } // open et close database public SQLiteDatabase open(){ dbClivana = dbClivanaHelper.getWritableDatabase(); return dbClivana; } public void close(){ dbClivana.close(); } // insertion d'un evenement public void insertEvent(Evenement event){ open(); dbClivana.insert(NomsSQL.TABLE_EVENEMENT, null, eventToContentValues(event)); close(); } // suppression public boolean removeEvent(Evenement event){ open(); boolean del = dbClivana.delete( NomsSQL.TABLE_EVENEMENT, NomsSQL.COLONNE_EVENEMENT_ID + " = " + event.getId(), null) > 0; close(); return del; } public void deleteEvent(long id){ open(); dbClivana.delete( NomsSQL.TABLE_EVENEMENT, NomsSQL.COLONNE_EVENEMENT_ID + " = " + id, null); close(); } // update public boolean updateEvent(Evenement event){ open(); boolean upd = dbClivana.update( NomsSQL.TABLE_EVENEMENT, eventToContentValues(event), NomsSQL.COLONNE_EVENEMENT_ID + " = " + event.getId(), null) > 0; close(); return upd; } // recherche event avec son ID public Evenement getEvenement(long id){ open(); Cursor c = dbClivana.query( NomsSQL.TABLE_EVENEMENT, null, NomsSQL.COLONNE_EVENEMENT_ID + " = " + id, null, null, null, null); if (c.getCount()==0){ return null; }else{ c.moveToFirst(); Evenement event = cursorToEvent(c); c.close(); close(); return event; } } // liste evenement, tri par date croissante, date >= datejour, limit QTE_MAX_EVENTS public List<Evenement> getAllEvents(){ open(); Cursor c = dbClivana.query( NomsSQL.TABLE_EVENEMENT, null, null,//NomsSQL.COLONNE_EVENEMENT_DATETRI +" >= '" + dateTri + "'", null, null, null, NomsSQL.COLONNE_EVENEMENT_DATETRI, Params.QTE_MAX_EVENEMENTS + ""); List<Evenement> evenements = cursorToEventTab(c); return evenements; } public List<Evenement> getFavoriteEvents(){ open(); Cursor c = dbClivana.query( NomsSQL.TABLE_EVENEMENT, null, NomsSQL.COLONNE_EVENEMENT_FAVORIS + " = 1", null, null, null, NomsSQL.COLONNE_EVENEMENT_DATETRI, Params.QTE_MAX_EVENEMENTS + ""); return cursorToEventTab(c); } public void setEvents(List<Evenement> events){ Iterator<Evenement> iter = events.iterator(); Evenement event; while(iter.hasNext()){ event = iter.next(); Evenement oldEvent = getEvenement(event.getId()); if (oldEvent == null){ insertEvent(event); }else{ event.setFavoris(oldEvent.isFavoris()); updateEvent(event); } } } private List<Evenement> cursorToEventTab(Cursor c){ String dateTri = Formatage.datePourTriEvenement(new Date()); List<Evenement> events = new ArrayList<Evenement>(); Evenement event; if (c.getCount()==0){ events.add(Evenement.noEvents()); }else{ while(c.moveToNext()){ event = cursorToEvent(c); if (event.getDateTri().compareTo(dateTri)<0){ }else{ events.add(event); } }; } if (events.size()==0){ events.add(Evenement.noEvents()); } c.close(); close(); return events; } private Evenement cursorToEvent(Cursor c){ boolean notif = c.getInt(NomsSQL.RANG_EVENEMENT_NOTIFICATION) == 1; boolean favoris = c.getInt(NomsSQL.RANG_EVENEMENT_FAVORIS) == 1; Evenement retEvent = new Evenement( c.getLong(NomsSQL.RANG_EVENEMENT_ID), c.getString(NomsSQL.RANG_EVENEMENT_TITRE), c.getString(NomsSQL.RANG_EVENEMENT_CONTENU), c.getString(NomsSQL.RANG_EVENEMENT_ACCROCHE), c.getString(NomsSQL.RANG_EVENEMENT_AUTEUR), c.getString(NomsSQL.RANG_EVENEMENT_LIEU), c.getString(NomsSQL.RANG_EVENEMENT_URLEVENEMENT), c.getString(NomsSQL.RANG_EVENEMENT_DATEHEURE), c.getString(NomsSQL.RANG_EVENEMENT_DATETRI), c.getString(NomsSQL.RANG_EVENEMENT_DATEENREGISTREMENT), c.getString(NomsSQL.RANG_EVENEMENT_NOMIMAGE), c.getString(NomsSQL.RANG_EVENEMENT_NOMIMAGEMOBILE), c.getString(NomsSQL.RANG_EVENEMENT_NOMMINIATURE), c.getString(NomsSQL.RANG_EVENEMENT_MOTSCLEFS), notif, favoris); return retEvent; } private ContentValues eventToContentValues(Evenement event){ ContentValues paramEvent = new ContentValues(); paramEvent.put(NomsSQL.COLONNE_EVENEMENT_ID , event.getId()); paramEvent.put(NomsSQL.COLONNE_EVENEMENT_TITRE , event.getTitre()); paramEvent.put(NomsSQL.COLONNE_EVENEMENT_CONTENU , event.getDetailEvenement()); paramEvent.put(NomsSQL.COLONNE_EVENEMENT_ACCROCHE , event.getAccroche()); paramEvent.put(NomsSQL.COLONNE_EVENEMENT_AUTEUR , event.getAuteur()); paramEvent.put(NomsSQL.COLONNE_EVENEMENT_LIEU, event.getLieu()); paramEvent.put(NomsSQL.COLONNE_EVENEMENT_URLEVENEMENT , event.getUrlEvenement()); paramEvent.put(NomsSQL.COLONNE_EVENEMENT_DATEHEURE, event.getDateHeureEvenement()); paramEvent.put(NomsSQL.COLONNE_EVENEMENT_DATETRI, event.getDateTri()); paramEvent.put(NomsSQL.COLONNE_EVENEMENT_DATEENREGISTREMENT, event.getDateEnregistrement()); paramEvent.put(NomsSQL.COLONNE_EVENEMENT_NOMIMAGE , event.getNomImage()); paramEvent.put(NomsSQL.COLONNE_EVENEMENT_NOMIMAGEMOBILE , event.getNomImageMobile()); paramEvent.put(NomsSQL.COLONNE_EVENEMENT_NOMMINIATURE , event.getNomImageMiniature()); paramEvent.put(NomsSQL.COLONNE_EVENEMENT_MOTSCLEFS , event.getMotsClefs()); paramEvent.put(NomsSQL.COLONNE_EVENEMENT_NOTIFICATION , event.isNotification()); paramEvent.put(NomsSQL.COLONNE_EVENEMENT_FAVORIS , event.isFavoris()); return paramEvent; } }
package com.hqb.patshop.mbg.dao; import com.hqb.patshop.mbg.model.SmsHomeAdvertise; import com.hqb.patshop.mbg.model.SmsHomeHot; import com.hqb.patshop.mbg.model.SmsHomeProductDao; import com.hqb.patshop.mbg.model.PmsProductCategoryDao; import java.util.List; public interface SmsHomeAdvertiseMapper { List<SmsHomeAdvertise> selectHomeAdvertise(); List<PmsProductCategoryDao> selectAllProductCategory(); List<SmsHomeProductDao> selectBidProduct(String categoryName); List<SmsHomeHot> selectAllHomeHot(); }
package com.promuplug.entity; import java.util.Calendar; 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.OneToOne; import javax.persistence.PrePersist; import javax.persistence.PreUpdate; import javax.persistence.Table; @Entity @Table(name = "ad_content") public class AdContent { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="id") private Long id; @Column(name="resource_path",nullable=false) private String resourcePath; @OneToOne(cascade = CascadeType.ALL) private Resource resource; @Column(name = "date_created",nullable=false) private Calendar dateCreated; @Column(name = "last_updated",nullable=false) private Calendar lastUpdated; @PrePersist protected void onCreate() { dateCreated = Calendar.getInstance(); } @PreUpdate protected void onUpdate() { lastUpdated = Calendar.getInstance(); } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getResourcePath() { return resourcePath; } public void setResourcePath(String resourcePath) { this.resourcePath = resourcePath; } public Resource getResource() { return resource; } public void setResource(Resource resource) { this.resource = resource; } public Calendar getDateCreated() { return dateCreated; } public void setDateCreated(Calendar dateCreated) { this.dateCreated = dateCreated; } public Calendar getLastUpdated() { return lastUpdated; } public void setLastUpdated(Calendar lastUpdated) { this.lastUpdated = lastUpdated; } }
import java.math.BigInteger; public class HashResult { private int distance; private byte[] buf; public HashResult(int distance, byte[] buf) { this.distance = distance; this.buf = buf; } public int getDistance() { return this.distance; } public byte[] getBuf() { return this.buf; } public String toString() { String result = new BigInteger(buf).abs().toString(16); return "HashResult{distance="+distance+ " result=\"" + result+"\"}"; } }
package utilities; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import models.Category; import org.junit.Test; import javax.management.ObjectName; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; public class CategorySerializerTest { @Test public void testSerialization() throws IOException { List<Category> rootList = new ArrayList<Category>(); rootList.add( newCategory(1, "cat1", newCategory(11, "cat11", newCategory(111, "cat111"), newCategory(112, "cat112")), newCategory(12, "cat12")) ); rootList.add( newCategory(2, "cat2", newCategory(21, "cat21")) ); rootList.add( newCategory(3, "cat3") ); JsonNode json = CategorySerializer.serialize(rootList); assertJSON(json, "1", "cat1", 2); assertJSON(json, "1.11", "cat11", 2); assertJSON(json, "1.11.111", "cat111", 0); assertJSON(json, "1.11.112", "cat112", 0); assertJSON(json, "1.12", "cat12", 0); assertJSON(json, "2", "cat2", 1); assertJSON(json, "2.21", "cat21", 0); assertJSON(json, "3", "cat3", 0); } private void assertJSON(JsonNode json, String path, String val, Integer childNum) { String[] parts = path.split("[.]"); for (int i = 0; i < parts.length; i++) { json = json.findValue(parts[i]); if (i == parts.length - 1) { if (val != null) { assertEquals(val, json.findValue("name").asText()); } if (childNum != null) { json = json.findValue("subcategories"); if (childNum == 0) { assertNull("Expected no children in node but found 'subcategories'", json); } else { assertEquals((int)childNum, json.size()); } } return; } json = json.findValue("subcategories"); assertNotNull(json); } } private Category newCategory(int id, String name, Category... children) { Category category = new Category(); category.id = id; category.name = name; category.children = Arrays.asList(children); return category; } }
package ru.itis.javalab.config; import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate; import org.springframework.jdbc.core.simple.SimpleJdbcInsert; import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer; import org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver; import ru.itis.javalab.repositories.UsersRepository; import ru.itis.javalab.repositories.UsersRepositoryJdbcTemplateImpl; import ru.itis.javalab.services.UsersService; import ru.itis.javalab.services.UsersServiceImpl; import javax.sql.DataSource; import java.util.Objects; /** * ApplicationConfig * created: 29-11-2020 - 15:11 * project: 08. Spring MVC * * @author dinar * @version v0.1 */ @EnableWebMvc @Configuration @ComponentScan(basePackages = "ru.itis.javalab") @PropertySource("classpath:db.properties") public class ApplicationConfig implements WebMvcConfigurer { private final Environment environment; @Autowired public ApplicationConfig(Environment environment) { this.environment = environment; } @Bean public HikariConfig hikariConfig() { HikariConfig hikariConfig = new HikariConfig(); hikariConfig.setJdbcUrl(environment.getProperty("db.jdbc.url")); hikariConfig.setUsername(environment.getProperty("db.jdbc.username")); hikariConfig.setPassword(environment.getProperty("db.jdbc.password")); hikariConfig.setDriverClassName( environment.getProperty("db.jdbc.driver.classname")); hikariConfig.setMaximumPoolSize(Integer.parseInt( Objects.requireNonNull( environment.getProperty("db.jdbc.hikari.max-pool-size")))); return hikariConfig; } @Bean public FreeMarkerViewResolver freemarkerViewResolver() { FreeMarkerViewResolver resolver = new FreeMarkerViewResolver(); resolver.setCache(true); resolver.setPrefix(""); resolver.setSuffix(".ftlh"); return resolver; } @Bean public FreeMarkerConfigurer freemarkerConfig() { FreeMarkerConfigurer freeMarkerConfigurer = new FreeMarkerConfigurer(); freeMarkerConfigurer.setTemplateLoaderPath("/WEB-INF/views/ftl/"); return freeMarkerConfigurer; } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**") .addResourceLocations("/resources/"); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } @Bean public DataSource dataSource() { return new HikariDataSource(hikariConfig()); } @Bean public JdbcTemplate jdbcTemplate() { return new JdbcTemplate(dataSource()); } @Bean public SimpleJdbcInsert simpleJdbcInsert() { return new SimpleJdbcInsert(dataSource()); } @Bean public NamedParameterJdbcTemplate namedParameterJdbcTemplate() { return new NamedParameterJdbcTemplate(dataSource()); } @Bean public UsersRepository usersRepository() { return new UsersRepositoryJdbcTemplateImpl(jdbcTemplate(), namedParameterJdbcTemplate(), simpleJdbcInsert()); } @Bean public UsersService usersService() { return new UsersServiceImpl(usersRepository(), passwordEncoder()); } }
package org.apache.commons.net.ftp.parser; import java.text.ParsePosition; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.Locale; import java.util.TimeZone; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPFileEntryParserImpl; public class MLSxEntryParser extends FTPFileEntryParserImpl { private static final MLSxEntryParser PARSER = new MLSxEntryParser(); private static final HashMap<String, Integer> TYPE_TO_INT = new HashMap<>(); static { TYPE_TO_INT.put("file", Integer.valueOf(0)); TYPE_TO_INT.put("cdir", Integer.valueOf(1)); TYPE_TO_INT.put("pdir", Integer.valueOf(1)); TYPE_TO_INT.put("dir", Integer.valueOf(1)); } private static int[] UNIX_GROUPS = new int[] { 0, 1, 2 }; private static int[][] UNIX_PERMS = new int[][] { {}, { 2 }, { 1 }, { 2, 1 }, new int[1], { 0, 2 }, { 0, 1 }, { 0, 1, 2 } }; public FTPFile parseFTPEntry(String entry) { if (entry.startsWith(" ")) { if (entry.length() > 1) { FTPFile fTPFile = new FTPFile(); fTPFile.setRawListing(entry); fTPFile.setName(entry.substring(1)); return fTPFile; } return null; } String[] parts = entry.split(" ", 2); if (parts.length != 2 || parts[1].length() == 0) return null; String factList = parts[0]; if (!factList.endsWith(";")) return null; FTPFile file = new FTPFile(); file.setRawListing(entry); file.setName(parts[1]); String[] facts = factList.split(";"); boolean hasUnixMode = parts[0].toLowerCase(Locale.ENGLISH).contains("unix.mode="); byte b; int i; String[] arrayOfString1; for (i = (arrayOfString1 = facts).length, b = 0; b < i; ) { String fact = arrayOfString1[b]; String[] factparts = fact.split("=", -1); if (factparts.length != 2) return null; String factname = factparts[0].toLowerCase(Locale.ENGLISH); String factvalue = factparts[1]; if (factvalue.length() != 0) { String valueLowerCase = factvalue.toLowerCase(Locale.ENGLISH); if ("size".equals(factname)) { file.setSize(Long.parseLong(factvalue)); } else if ("sizd".equals(factname)) { file.setSize(Long.parseLong(factvalue)); } else if ("modify".equals(factname)) { Calendar parsed = parseGMTdateTime(factvalue); if (parsed == null) return null; file.setTimestamp(parsed); } else if ("type".equals(factname)) { Integer intType = TYPE_TO_INT.get(valueLowerCase); if (intType == null) { file.setType(3); } else { file.setType(intType.intValue()); } } else if (factname.startsWith("unix.")) { String unixfact = factname.substring("unix.".length()).toLowerCase(Locale.ENGLISH); if ("group".equals(unixfact)) { file.setGroup(factvalue); } else if ("owner".equals(unixfact)) { file.setUser(factvalue); } else if ("mode".equals(unixfact)) { int off = factvalue.length() - 3; for (int j = 0; j < 3; j++) { int ch = factvalue.charAt(off + j) - 48; if (ch >= 0 && ch <= 7) { byte b1; int k; int[] arrayOfInt; for (k = (arrayOfInt = UNIX_PERMS[ch]).length, b1 = 0; b1 < k; ) { int p = arrayOfInt[b1]; file.setPermission(UNIX_GROUPS[j], p, true); b1++; } } } } } else if (!hasUnixMode && "perm".equals(factname)) { doUnixPerms(file, valueLowerCase); } } b++; } return file; } public static Calendar parseGMTdateTime(String timestamp) { SimpleDateFormat sdf; boolean hasMillis; if (timestamp.contains(".")) { sdf = new SimpleDateFormat("yyyyMMddHHmmss.SSS"); hasMillis = true; } else { sdf = new SimpleDateFormat("yyyyMMddHHmmss"); hasMillis = false; } TimeZone GMT = TimeZone.getTimeZone("GMT"); sdf.setTimeZone(GMT); GregorianCalendar gc = new GregorianCalendar(GMT); ParsePosition pos = new ParsePosition(0); sdf.setLenient(false); Date parsed = sdf.parse(timestamp, pos); if (pos.getIndex() != timestamp.length()) return null; gc.setTime(parsed); if (!hasMillis) gc.clear(14); return gc; } private void doUnixPerms(FTPFile file, String valueLowerCase) { byte b; int i; char[] arrayOfChar; for (i = (arrayOfChar = valueLowerCase.toCharArray()).length, b = 0; b < i; ) { char c = arrayOfChar[b]; switch (c) { case 'a': file.setPermission(0, 1, true); break; case 'c': file.setPermission(0, 1, true); break; case 'd': file.setPermission(0, 1, true); break; case 'e': file.setPermission(0, 0, true); break; case 'l': file.setPermission(0, 2, true); break; case 'm': file.setPermission(0, 1, true); break; case 'p': file.setPermission(0, 1, true); break; case 'r': file.setPermission(0, 0, true); break; case 'w': file.setPermission(0, 1, true); break; } b++; } } public static FTPFile parseEntry(String entry) { return PARSER.parseFTPEntry(entry); } public static MLSxEntryParser getInstance() { return PARSER; } } /* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\org\apache\commons\net\ftp\parser\MLSxEntryParser.class * Java compiler version: 8 (52.0) * JD-Core Version: 1.1.3 */
package TreeGraph; public class _checkBalanced { public boolean isBalanced(TreeNode root) { if (root == null) return true; return false; } }
package main; public class Asimilador extends Extractora { public Asimilador(){ } }
package cn.sharp.android.ncr.display; import java.util.ArrayList; import java.util.List; import com.socialcard.activity.R; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.res.Resources; import android.net.Uri; import android.os.Handler; import android.os.Message; import android.provider.Contacts; import android.text.InputType; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import cn.sharp.android.ncr.MessageId; import cn.sharp.android.ncr.display.domain.Address; import cn.sharp.android.ncr.display.domain.BaseDomain; import cn.sharp.android.ncr.display.domain.Email; import cn.sharp.android.ncr.display.domain.Organization; import cn.sharp.android.ncr.display.domain.Phone; import cn.sharp.android.ncr.display.domain.Url; import cn.sharp.android.ncr.ocr.OCRItems; public class ContactPerson { private final static String TAG = "ContactPerson"; public final static int ITEM_NAME = 1; public final static int ITEM_PHONE = 2; public final static int ITEM_EMAIL = 3; public final static int ITEM_ADDRESS = 4; public final static int ITEM_ORG = 5; public final static int ITEM_URL = 6; public final static int ITEM_NOTE = 7; public final static int TYPE_HOME = 1; public final static int TYPE_WORK = 2; public final static int TYPE_OTHER = 3; public final static int TYPE_PAGER = 4; public final static int TYPE_MOBILE = 5; public final static int TYPE_FAX_HOME = 6; public final static int TYPE_FAX_WORK = 7; private long groupId; private String name; private List<Email> emails; private List<Phone> phones; private List<Organization> orgs; private List<Address> addresses; private List<Url> urls; private String note; public String typeHome, typeWork, typeOther, typePager, typeMobile, typeFaxHome, typeFaxWork; private int[] supportedItemTypes1; private int[] supportedItemTypes2; private int[] supportedItemTypes3; private String[] supportedItemTypeStr1; private String[] supportedItemTypeStr2; private String[] supportedItemTypeStr3; private OnSelectItemType onSelectItemType; private ContentResolver contentResolver; private SelectItemTypeListener onSelectTypeListener; private RemoveItemListener removeItemListener; private EditText nameView, noteView; private ViewGroup phoneViewGroup, emailViewGroup, addressViewGroup, orgViewGroup, urlViewGroup; private Button itemType; private EditText itemValue, itemValue2; private ImageButton removeItem; private LayoutInflater inflater; /** * remove all Context reference, or it will result in memory leak */ public void removeAllContextObject() { onSelectItemType = null; contentResolver = null; onSelectTypeListener = null; removeItemListener = null; nameView = null; noteView = null; phoneViewGroup = emailViewGroup = addressViewGroup = orgViewGroup = urlViewGroup = null; inflater = null; itemType = null; itemValue = null; itemValue2 = null; removeItem = null; } public void registerNewContext(Context context) { init(context); } private void initPrimitiveObj() { groupId = -1; phones = new ArrayList<Phone>(); orgs = new ArrayList<Organization>(); emails = new ArrayList<Email>(); addresses = new ArrayList<Address>(); urls = new ArrayList<Url>(); supportedItemTypes1 = new int[] { TYPE_HOME, TYPE_WORK, TYPE_MOBILE, TYPE_OTHER, TYPE_PAGER, TYPE_FAX_HOME, TYPE_FAX_WORK }; supportedItemTypes2 = new int[] { TYPE_WORK, TYPE_OTHER }; supportedItemTypes3 = new int[] { TYPE_WORK, TYPE_HOME, TYPE_OTHER }; supportedItemTypeStr1 = new String[] { typeHome, typeWork, typeMobile, typeOther, typePager, typeFaxHome, typeFaxWork }; supportedItemTypeStr2 = new String[] { typeWork, typeOther }; supportedItemTypeStr3 = new String[] { typeWork, typeHome, typeOther }; onSelectTypeListener = new SelectItemTypeListener(); removeItemListener = new RemoveItemListener(); } private void init(Context context) { inflater = LayoutInflater.from(context); contentResolver = context.getContentResolver(); Resources resources = context.getResources(); typeHome = resources.getString(R.string.type_home); typeWork = resources.getString(R.string.type_work); typeOther = resources.getString(R.string.type_other); typePager = resources.getString(R.string.type_pager); typeMobile = resources.getString(R.string.type_mobile); typeFaxHome = resources.getString(R.string.type_fax_home); typeFaxWork = resources.getString(R.string.type_fax_work); } public ContactPerson(Context context) { init(context); initPrimitiveObj(); } public ContactPerson(Context context, OCRItems items) { init(context); initPrimitiveObj(); if (items.name != null) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < items.name.length; i++) { sb.append(items.name[i]); } name = sb.toString(); } if (items.fax != null) { for (int i = 0; i < items.fax.length; i++) { Phone phone = new Phone(); phone.type = TYPE_FAX_WORK; phone.value = items.fax[i]; phones.add(phone); } } if (items.telephone != null) { for (int i = 0; i < items.telephone.length; i++) { Phone phone = new Phone(); phone.type = TYPE_MOBILE; phone.value = items.telephone[i]; phones.add(phone); } } if (items.cellphone != null) { for (int i = 0; i < items.cellphone.length; i++) { Phone phone = new Phone(); phone.type = TYPE_MOBILE; phone.value = items.cellphone[i]; phones.add(phone); } } if (items.organization != null) { for (int i = 0; i < items.organization.length; i++) { Organization org = new Organization(); org.company = items.organization[i]; org.type = TYPE_WORK; if (items.department != null && items.department.length > i) { org.company += "," + items.department[i]; } if (items.title != null && items.title.length > i) { org.title = items.title[i]; } else { org.title = ""; } orgs.add(org); } /** * add the remained items.department fields */ if (items.department != null) { for (int i = items.organization.length; i < items.department.length; i++) { Organization org = new Organization(); org.company = items.department[i]; org.type = TYPE_WORK; if (items.title != null && items.title.length > i) { org.title = items.title[i]; } else { org.title = ""; } orgs.add(org); } } } else if (items.department != null) { /** * if items.orgnization==null&&items.department!=null, treat * items.department as org.company value */ for (int i = 0; i < items.department.length; i++) { Organization org = new Organization(); org.company = items.department[i]; org.type = TYPE_WORK; if (items.title != null && items.title.length > i) { org.title = items.title[i]; } else { org.title = ""; } orgs.add(org); } } if (items.email != null) { for (int i = 0; i < items.email.length; i++) { Email email = new Email(); email.type = TYPE_WORK; email.value = items.email[i]; emails.add(email); } } if (items.address != null) { for (int i = 0; i < items.address.length; i++) { Address address = new Address(); address.type = TYPE_WORK; address.value = items.address[i]; addresses.add(address); if (items.postcode != null && items.postcode.length > i) { address.postcode = items.postcode[i]; } else { address.postcode = ""; } } } if (items.url != null) { for (int i = 0; i < items.url.length; i++) { Url url = new Url(); url.type = TYPE_WORK; url.value = items.url[i]; urls.add(url); } } } /** * bind the data to corresponding views * * @param nameView * @param phoneViewGroup * @param orgViewGroup * @param emailViewGroup * @param addressViewGroup * @param urlGroups * @param noteView */ public void bindDataToView() { Log.d(TAG, "org list size:" + orgs.size()); if (nameView != null) { if (name == null) { name = ""; } name = name.trim(); nameView.setText(name); } if (phoneViewGroup != null) { for (int i = 0; i < phones.size(); i++) { addPhoneItem(phones.get(i), false); } } if (emailViewGroup != null) { for (int i = 0; i < emails.size(); i++) { addEmailItem(emails.get(i), false); } } if (addressViewGroup != null) { for (int i = 0; i < addresses.size(); i++) { addAddressItem(addresses.get(i), false); } } if (orgViewGroup != null) { for (int i = 0; i < orgs.size(); i++) { addOrgItem(orgs.get(i), false); } } if (urlViewGroup != null) { for (int i = 0; i < urls.size(); i++) { addUrlItem(urls.get(i), false); } } if (noteView != null) { if (note == null) { note = ""; } note = note.trim(); noteView.setText(note); } } private View inflateViews() { View row = inflater.inflate(R.layout.rec_result_row_single, null); itemType = (Button) row.findViewById(R.id.item_type); itemValue = (EditText) row.findViewById(R.id.item_value); removeItem = (ImageButton) row.findViewById(R.id.btn_remove_item); return row; } private View inflateViews2() { View row = inflater.inflate(R.layout.rec_result_row_twoline, null); itemType = (Button) row.findViewById(R.id.item_type_twoline); itemValue = (EditText) row.findViewById(R.id.item_value_twoline_1); itemValue2 = (EditText) row.findViewById(R.id.item_value_twoline_2); removeItem = (ImageButton) row .findViewById(R.id.btn_remove_item_two_line); return row; } public synchronized void startSave(boolean merge, Handler handler) { Thread thread = new SaveContactThread(merge, handler); thread.start(); } public class SaveContactThread extends Thread { private boolean merge; private Handler handler; public SaveContactThread() { merge = false; } public SaveContactThread(boolean merge) { this.merge = merge; } public SaveContactThread(boolean merge, Handler handler) { this.merge = merge; this.handler = handler; } @Override public void run() { save(merge); Log.d(TAG, "contact add, merge:" + merge); if (handler != null) { Message msg = new Message(); msg.what = MessageId.SAVE_CONTACT_SUCCESS; handler.sendMessage(msg); Log.d(TAG, "send success message"); } } } /** * save the object to system contacts * * @param merge * if true and there's a contact already existed whose name is * the same to this contact's name, the information in this * contact object will be added to the old contact, else a new * contact will be created in the system wide. Remember to update * the values in this of object with the value of binded views */ public synchronized void save(boolean merge) { if (merge) { Log.d(TAG, "begin merge contact"); } else { Log.d(TAG, "begin create new contact"); ContentValues values = new ContentValues(); /** * insert name and notes to Contact.People table */ values.put(Contacts.PeopleColumns.NAME, name); values.put(Contacts.PeopleColumns.NOTES, note); Uri personUrl = contentResolver.insert(Contacts.People.CONTENT_URI, values); long personId = -1; if (personUrl.getLastPathSegment() != null) { try { personId = Long.parseLong(personUrl.getLastPathSegment()); } catch (NumberFormatException e) { Log.e(TAG, "error when parsing newly inserted person id"); } } else { Log .e(TAG, "last path segment of newly inserted person uri is null"); } /** * contact not inserted, saving progress terminated */ if (personId == -1) { return; } Log.d(TAG, "insert person, pserson id:" + personId); /** * insert contact to group membership table */ values.clear(); values.put(Contacts.GroupMembership.GROUP_ID, groupId); values.put(Contacts.GroupMembership.PERSON_ID, personId); Uri resultUri = contentResolver.insert( Contacts.GroupMembership.CONTENT_URI, values); if (resultUri != null) { Log.d(TAG, "add contact to group " + groupId); } else { Log.e(TAG, "cannot add contact to group " + groupId); } /** * insert phones */ for (int i = 0; i < phones.size(); i++) { String phoneStr = phones.get(i).value.trim(); /** * email is empty, ignore this item */ if (phoneStr.length() == 0) continue; values.clear(); values.put(Contacts.PhonesColumns.NUMBER, phoneStr); int type = convertType1(phones.get(i).type); if (type == -1) { Log.i(TAG, "cannot convert phone type " + phones.get(i).type + ", use default value instead"); type = Contacts.PhonesColumns.TYPE_OTHER; } values.put(Contacts.Phones.PERSON_ID, personId); values.put(Contacts.PhonesColumns.TYPE, type); contentResolver.insert(Contacts.Phones.CONTENT_URI, values); Log.d(TAG, "insert phone " + i + ", value:" + phoneStr); } /** * insert emails */ for (int i = 0; i < emails.size(); i++) { String emailStr = emails.get(i).value.trim(); /** * email is empty, ignore this item */ if (emailStr.length() == 0) continue; /** * check email format, not implemented yet */ values.clear(); values.put(Contacts.ContactMethods.PERSON_ID, personId); values.put(Contacts.ContactMethods.DATA, emailStr); int type = convertType3(emails.get(i).type); if (type == -1) { Log.i(TAG, "cannot convert email type " + emails.get(i).type + ", use default value instead"); type = Contacts.PhonesColumns.TYPE_OTHER; } values.put(Contacts.PhonesColumns.TYPE, type); values.put(Contacts.ContactMethods.KIND, Contacts.KIND_EMAIL); contentResolver.insert(Contacts.ContactMethods.CONTENT_URI, values); Log.d(TAG, "insert email " + i); } /** * insert postal address */ for (int i = 0; i < addresses.size(); i++) { String addressStr = addresses.get(i).value.trim(); /** * email is empty, ignore this item */ if (addressStr.length() == 0) continue; /** * check email format, not implemented yet */ values.clear(); values.put(Contacts.ContactMethods.PERSON_ID, personId); values.put(Contacts.ContactMethods.DATA, addressStr); int type = convertType3(addresses.get(i).type); if (type == -1) { Log.i(TAG, "cannot convert email type " + addresses.get(i).type + ", use default value instead"); type = Contacts.PhonesColumns.TYPE_OTHER; } values.put(Contacts.PhonesColumns.TYPE, type); values.put(Contacts.ContactMethods.KIND, Contacts.KIND_POSTAL); contentResolver.insert(Contacts.ContactMethods.CONTENT_URI, values); Log.d(TAG, "insert address " + i); } /** * insert organization */ for (int i = 0; i < orgs.size(); i++) { values.clear(); values.put(Contacts.OrganizationColumns.COMPANY, orgs.get(i).company); values.put(Contacts.OrganizationColumns.TITLE, orgs.get(i).title); values.put(Contacts.OrganizationColumns.PERSON_ID, personId); int type = convertType2(orgs.get(i).type); if (type == -1) { Log.i(TAG, "cannot convert org type " + orgs.get(i).type + ", use default value"); type = Contacts.OrganizationColumns.TYPE_OTHER; } values.put(Contacts.OrganizationColumns.TYPE, type); contentResolver.insert(Contacts.Organizations.CONTENT_URI, values); Log.d(TAG, "insert org " + i); } /** * insert url, temporarily not implemented, because android does not * allow us to insert two rows with the same PERSION_ID field value * and NAME field value into Contacts.Extension table. */ // for (int i = 0; i < urls.size(); i++) { // String urlStr = urls.get(i).value.trim(); // if (urlStr.length() == 0) { // continue; // } // values.clear(); // values.put(Contacts.Extensions.PERSON_ID, personId); // values.put(Contacts.Extensions.NAME, "URL"); // values.put(Contacts.Extensions.VALUE, urlStr); // contentResolver.insert(Contacts.Extensions.CONTENT_URI, values); // Log.d(TAG, "insert url " + i); // } } } /** * Convert type defined in this class to android contact type, ie., * Contact.Phones * * @param myType * @return */ private int convertType1(int myType) { int result = -1; switch (myType) { case TYPE_HOME: result = Contacts.PhonesColumns.TYPE_HOME; break; case TYPE_WORK: result = Contacts.PhonesColumns.TYPE_WORK; break; case TYPE_OTHER: result = Contacts.PhonesColumns.TYPE_OTHER; break; case TYPE_MOBILE: result = Contacts.PhonesColumns.TYPE_MOBILE; break; case TYPE_PAGER: result = Contacts.PhonesColumns.TYPE_PAGER; break; case TYPE_FAX_WORK: result = Contacts.PhonesColumns.TYPE_FAX_WORK; break; case TYPE_FAX_HOME: result = Contacts.PhonesColumns.TYPE_FAX_HOME; break; } return result; } /** * for organization * * @param myType * @return */ private int convertType2(int myType) { int result = -1; switch (myType) { case TYPE_WORK: result = Contacts.OrganizationColumns.TYPE_WORK; break; case TYPE_OTHER: result = Contacts.OrganizationColumns.TYPE_OTHER; break; } return result; } /** * for other items used for Contacts.ContactMethods * * @param myType * @return */ private int convertType3(int myType) { int result = -1; switch (myType) { case TYPE_WORK: result = Contacts.ContactMethodsColumns.TYPE_WORK; break; case TYPE_HOME: result = Contacts.ContactMethodsColumns.TYPE_HOME; break; case TYPE_OTHER: result = Contacts.ContactMethodsColumns.TYPE_OTHER; break; } return result; } public boolean updateItemType(int itemName, int index, int newType) { Log.d(TAG, "update new type, itemName:" + itemName + ", index:" + index + ", newType:" + newType); switch (itemName) { case ITEM_PHONE: if (index >= 0 && index < phones.size()) { if (checkType(itemName, newType)) { phones.get(index).type = newType; return true; } else { Log.e(TAG, "invalid type for item " + itemName + ", type:" + newType); } } else { Log.e(TAG, "invalid index for item " + itemName + " with index " + index); } break; case ITEM_EMAIL: if (index >= 0 && index < emails.size()) { if (checkType(itemName, newType)) { emails.get(index).type = newType; return true; } else { Log.e(TAG, "invalid type for item " + itemName + ", type:" + newType); } } else { Log.e(TAG, "invalid index for item " + itemName + " with index " + index); } break; case ITEM_ADDRESS: if (index >= 0 && index < addresses.size()) { if (checkType(itemName, newType)) { addresses.get(index).type = newType; return true; } else { Log.e(TAG, "invalid type for item " + itemName + ", type:" + newType); } } else { Log.e(TAG, "invalid index for item " + itemName + " with index " + index); } break; case ITEM_ORG: if (index >= 0 && index < orgs.size()) { if (checkType(itemName, newType)) { orgs.get(index).type = newType; return true; } else { Log.e(TAG, "invalid type for item " + itemName + ", type:" + newType); } } else { Log.e(TAG, "invalid index for item " + itemName + " with index " + index); } break; case ITEM_URL: if (index >= 0 && index < urls.size()) { if (checkType(itemName, newType)) { urls.get(index).type = newType; return true; } else { Log.e(TAG, "invalid type for item " + itemName + ", type:" + newType); } } else { Log.e(TAG, "invalid index for item " + itemName + " with index " + index); } break; } return false; } public boolean updateItemValue(int itemName, int index, String value1) { return updateItemValue(itemName, index, value1, null); } public boolean updateItemValue(int itemName, int index, String value1, String value2) { Log.d(TAG, "update item:" + itemName + ", index:" + index + ", value:" + value1); if (value1 == null) { value1 = ""; } if (value2 == null) { value2 = ""; } switch (itemName) { case ITEM_NAME: name = value1; return true; case ITEM_PHONE: if (index >= 0 && index < phones.size()) { phones.get(index).value = value1; return true; } else { Log.e(TAG, "invalid index for item " + itemName + " with index " + index); } break; case ITEM_EMAIL: if (index >= 0 && index < emails.size()) { emails.get(index).value = value1; return true; } else { Log.e(TAG, "invalid index for item " + itemName + " with index " + index); } break; case ITEM_ADDRESS: if (index >= 0 && index < addresses.size()) { addresses.get(index).value = value1; return true; } else { Log.e(TAG, "invalid index for item " + itemName + " with index " + index); } break; case ITEM_ORG: if (index >= 0 && index < orgs.size()) { orgs.get(index).company = value1; orgs.get(index).title = value2; return true; } else { Log.e(TAG, "invalid index for item " + itemName + " with index " + index); } break; case ITEM_URL: if (index >= 0 && index < urls.size()) { urls.get(index).value = value1; return true; } else { Log.e(TAG, "invalid index for item " + itemName + " with index " + index); } break; case ITEM_NOTE: note = value1; break; } return false; } public boolean deleteItem(int itemName, int index) { Log.d(TAG, "delete item:" + itemName + ", index:" + index); return true; } public void add(int itemName, String value) { if (value == null) value = ""; switch (itemName) { case ITEM_PHONE: Phone phone = new Phone(); phone.type = TYPE_WORK; phone.value = value; addPhoneItem(phone); break; case ITEM_EMAIL: Email email = new Email(); email.type = TYPE_WORK; email.value = value; addEmailItem(email); break; case ITEM_ADDRESS: Address address = new Address(); address.type = TYPE_WORK; address.value = value; addAddressItem(address); break; case ITEM_ORG: Organization org = new Organization(); org.company = value; org.type = TYPE_WORK; addOrgItem(org); break; case ITEM_URL: Url url = new Url(); url.type = TYPE_WORK; url.value = value; addUrlItem(url); break; } } private void addPhoneItem(Phone phone) { addPhoneItem(phone, true); } private void addPhoneItem(Phone phone, boolean newItem) { if (phoneViewGroup == null) { Log.e(TAG, "viewGroup==null"); return; } if (phone == null) { Log.e(TAG, "phone==null"); return; } View newView = inflateViews(); phoneViewGroup.addView(newView); ItemIdentifier identifier = new ItemIdentifier(); identifier.itemName = ITEM_PHONE; if (newItem) { phones.add(phone); } identifier.id = phone.getId(); identifier.parent = newView; itemType.setOnClickListener(onSelectTypeListener); itemType.setText(getTypeName(phone.type)); itemType.setTag(identifier); itemValue.setText(phone.value); itemValue.setInputType(InputType.TYPE_CLASS_PHONE); removeItem.setOnClickListener(removeItemListener); removeItem.setTag(identifier); } private void addEmailItem(Email email) { addEmailItem(email, true); } private void addEmailItem(Email email, boolean newItem) { if (emailViewGroup == null) { Log.e(TAG, "emailViewGroup==null"); return; } if (email == null) { Log.e(TAG, "email==null"); return; } View newView = inflateViews(); emailViewGroup.addView(newView); ItemIdentifier identifier = new ItemIdentifier(); identifier.itemName = ITEM_EMAIL; if (newItem) { emails.add(email); } identifier.id = email.getId(); identifier.parent = newView; itemType.setOnClickListener(onSelectTypeListener); itemType.setText(getTypeName(email.type)); itemType.setTag(identifier); itemValue.setText(email.value); removeItem.setOnClickListener(removeItemListener); removeItem.setTag(identifier); } private void addAddressItem(Address address) { addAddressItem(address, true); } private void addAddressItem(Address address, boolean newItem) { if (addressViewGroup == null) { Log.e(TAG, "addressViewGroup==null"); return; } if (address == null) { Log.e(TAG, "address==null"); return; } View newView = inflateViews(); addressViewGroup.addView(newView); ItemIdentifier identifier = new ItemIdentifier(); identifier.itemName = ITEM_ADDRESS; if (newItem) { addresses.add(address); } identifier.id = address.getId(); identifier.parent = newView; itemType.setOnClickListener(onSelectTypeListener); itemType.setText(getTypeName(address.type)); itemType.setTag(identifier); itemValue.setText(address.value); removeItem.setOnClickListener(removeItemListener); removeItem.setTag(identifier); } private void addOrgItem(Organization org) { addOrgItem(org, true); } private void addOrgItem(Organization org, boolean newItem) { if (orgViewGroup == null) { Log.e(TAG, "orgViewGroup==null"); return; } if (org == null) { Log.e(TAG, "org==null"); return; } View newView = inflateViews2(); orgViewGroup.addView(newView); ItemIdentifier identifier = new ItemIdentifier(); identifier.itemName = ITEM_ORG; if (newItem) { orgs.add(org); } identifier.id = org.getId(); identifier.parent = newView; itemType.setOnClickListener(onSelectTypeListener); itemType.setText(getTypeName(org.type)); itemType.setTag(identifier); itemValue.setText(org.company); itemValue2.setText(org.title); removeItem.setOnClickListener(removeItemListener); removeItem.setTag(identifier); } private void addUrlItem(Url url) { addUrlItem(url, true); } private void addUrlItem(Url url, boolean newItem) { if (urlViewGroup == null) { Log.e(TAG, "urlViewGroup==null"); return; } if (url == null) { Log.e(TAG, "url==null"); return; } View newView = inflateViews(); urlViewGroup.addView(newView); ItemIdentifier identifier = new ItemIdentifier(); identifier.itemName = ITEM_URL; if (newItem) { urls.add(url); } identifier.id = url.getId(); identifier.parent = newView; itemType.setOnClickListener(onSelectTypeListener); itemType.setText(getTypeName(url.type)); itemType.setTag(identifier); itemValue.setText(url.value); removeItem.setOnClickListener(removeItemListener); removeItem.setTag(identifier); } public OnSelectItemType getOnSelectItemType() { return onSelectItemType; } public void setOnSelectItemType(OnSelectItemType onSelectItemType) { this.onSelectItemType = onSelectItemType; } public class ItemIdentifier { int itemName; int id; View parent; } public String getTypeName(int type) { switch (type) { case TYPE_HOME: return typeHome; case TYPE_WORK: return typeWork; case TYPE_OTHER: return typeOther; case TYPE_PAGER: return typePager; case TYPE_MOBILE: return typeMobile; case TYPE_FAX_HOME: return typeFaxHome; case TYPE_FAX_WORK: return typeFaxWork; } return ""; } /** * check if the item that itemName specifies supports the type * * @param itemName * @param type * @return */ private boolean checkType(int itemName, int type) { int[] supportedTypes = getSupportedTypes(itemName); if (supportedTypes == null) { return false; } for (int i = 0; i < supportedTypes.length; i++) { if (supportedTypes[i] == type) { return true; } } return false; } public long getGroupId() { return groupId; } public void setGroupId(long groupId) { this.groupId = groupId; } public int[] getSupportedTypes(int itemName) { switch (itemName) { case ITEM_PHONE: return supportedItemTypes1; case ITEM_ORG: return supportedItemTypes2; case ITEM_EMAIL: case ITEM_ADDRESS: case ITEM_URL: return supportedItemTypes3; } return null; } public interface OnSelectItemType { void displayItems(ContactPerson contact, int itemName, int index, int[] types, String[] typeStrs); } public EditText getNameView() { return nameView; } public void setNameView(EditText nameView) { this.nameView = nameView; } public EditText getNoteView() { return noteView; } public void setNoteView(EditText noteView) { this.noteView = noteView; } public ViewGroup getPhoneViewGroup() { return phoneViewGroup; } public void setPhoneViewGroup(ViewGroup phoneViewGroup) { this.phoneViewGroup = phoneViewGroup; } public ViewGroup getEmailViewGroup() { return emailViewGroup; } public void setEmailViewGroup(ViewGroup emailViewGroup) { this.emailViewGroup = emailViewGroup; } public ViewGroup getAddressViewGroup() { return addressViewGroup; } public void setAddressViewGroup(ViewGroup addressViewGroup) { this.addressViewGroup = addressViewGroup; } public ViewGroup getOrgViewGroup() { return orgViewGroup; } public void setOrgViewGroup(ViewGroup orgViewGroup) { this.orgViewGroup = orgViewGroup; } public ViewGroup getUrlViewGroup() { return urlViewGroup; } public void setUrlViewGroup(ViewGroup urlViewGroup) { this.urlViewGroup = urlViewGroup; } private class RemoveItemListener implements OnClickListener { @Override public void onClick(View v) { ItemIdentifier identifier = (ItemIdentifier) v.getTag(); if (identifier != null) { if (identifier.itemName > 0 && identifier.itemName < 8) { switch (identifier.itemName) { case ITEM_PHONE: removeFromList(ITEM_PHONE, identifier.id); phoneViewGroup.removeView(identifier.parent); Log.d(TAG, "remove phone item, id:" + identifier.id); break; case ITEM_EMAIL: removeFromList(ITEM_EMAIL, identifier.id); emailViewGroup.removeView(identifier.parent); Log.d(TAG, "remove email item, id:" + identifier.id); break; case ITEM_ADDRESS: removeFromList(ITEM_ADDRESS, identifier.id); addressViewGroup.removeView(identifier.parent); Log.d(TAG, "remove address item, id:" + identifier.id); break; case ITEM_ORG: removeFromList(ITEM_ORG, identifier.id); orgViewGroup.removeView(identifier.parent); Log.d(TAG, "remove org item, id:" + identifier.id); break; case ITEM_URL: removeFromList(ITEM_URL, identifier.id); urlViewGroup.removeView(identifier.parent); Log.d(TAG, "remove url item, id:" + identifier.id); break; } } } } } private void removeFromList(int itemName, int id) { List list = null; switch (itemName) { case ITEM_PHONE: list = phones; break; case ITEM_EMAIL: list = emails; break; case ITEM_ADDRESS: list = addresses; break; case ITEM_ORG: list = orgs; break; case ITEM_URL: list = urls; break; } if (list != null) { for (int i = 0; i < list.size(); i++) { BaseDomain base = (BaseDomain) list.get(i); if (base.getId() == id) { list.remove(i); Log.d(TAG, "remove item, itemName:" + itemName + ", id=" + id); } } } else { Log.e(TAG, "no match item " + itemName); } } private class SelectItemTypeListener implements OnClickListener { @Override public void onClick(View v) { ItemIdentifier identifier = (ItemIdentifier) v.getTag(); if (identifier != null) { if (identifier.itemName > 0 && identifier.itemName < 8) { Log.v(TAG, "item name:" + identifier.itemName + ", index:" + identifier.id); String[] typesStr = null; int[] types = null; switch (identifier.itemName) { case ITEM_PHONE: types = supportedItemTypes1; typesStr = supportedItemTypeStr1; break; case ITEM_ORG: types = supportedItemTypes2; typesStr = supportedItemTypeStr2; break; case ITEM_EMAIL: case ITEM_ADDRESS: case ITEM_URL: types = supportedItemTypes3; typesStr = supportedItemTypeStr3; break; } if (typesStr != null && onSelectItemType != null) { int index = getItemIndex(identifier.itemName, identifier.id); if (index < 0) { Log.e(TAG, "invalid index for item " + identifier.itemName); } else { onSelectItemType .displayItems(ContactPerson.this, identifier.itemName, index, types, typesStr); } } else { Log.e(TAG, "typeStr==null"); } } else { Log.e(TAG, "unknown type:" + identifier.itemName); } } else { Log.i(TAG, "identifier==null"); } } } private int getItemIndex(int itemName, int id) { List list = null; switch (itemName) { case ITEM_PHONE: list = phones; break; case ITEM_EMAIL: list = emails; break; case ITEM_ADDRESS: list = addresses; break; case ITEM_ORG: list = orgs; break; case ITEM_URL: list = urls; break; } if (list != null) { for (int i = 0; i < list.size(); i++) { BaseDomain base = (BaseDomain) list.get(i); if (base.getId() == id) { return i; } } } return -1; } }
package model; import org.junit.jupiter.api.Test; import persistence.JsonReader; import ui.Account; import java.io.IOException; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.fail; public class JsonReaderTest { @Test void testReaderNonExistentFile() { JsonReader reader = new JsonReader("./data/noSuchFile.json"); try { Account acc = reader.read(); fail("IOException was not thrown."); } catch (IOException e) { // do nothing } } @Test void testReaderInitialArsenal() { JsonReader reader = new JsonReader("./data/testReaderInitialArsenal.json"); try { Account acc = reader.read(); assertEquals("Sebastian", acc.getUsername()); assertEquals("123", acc.getPassword()); assertEquals(1, acc.getWeapons().size()); assertEquals(WeaponType.HANDGUN, acc.getWeapons().get(0).getWeaponType()); assertEquals(100, acc.getHighScore()); assertEquals(69, acc.getCurrentScore()); assertEquals(100, acc.getPlayer().getHealth()); assertEquals(0, acc.getPlayer().getKills()); } catch (IOException e) { fail("IOException was thrown and caught when it shouldn't have."); } } @Test void testReaderFullArsenal() { JsonReader reader = new JsonReader("./data/testReaderFullArsenal.json"); try { Account acc = reader.read(); assertEquals("Sebastian", acc.getUsername()); assertEquals("123", acc.getPassword()); assertEquals(5, acc.getWeapons().size()); assertEquals(WeaponType.HANDGUN, acc.getWeapons().get(0).getWeaponType()); assertEquals(WeaponType.SHOTGUN, acc.getWeapons().get(1).getWeaponType()); assertEquals(WeaponType.UZI, acc.getWeapons().get(2).getWeaponType()); assertEquals(WeaponType.LAUNCHER, acc.getWeapons().get(3).getWeaponType()); assertEquals(WeaponType.MINE, acc.getWeapons().get(4).getWeaponType()); assertEquals(0, acc.getHighScore()); assertEquals(0, acc.getCurrentScore()); assertEquals(100, acc.getPlayer().getHealth()); assertEquals(0, acc.getPlayer().getKills()); } catch (IOException e) { fail("IOException was thrown and caught when it shouldn't have."); } } @Test void testReaderGeneralArsenal() { JsonReader reader = new JsonReader("./data/testReaderGeneralArsenal.json"); try { Account acc = reader.read(); assertEquals("Sebastian", acc.getUsername()); assertEquals("123", acc.getPassword()); assertEquals(2, acc.getWeapons().size()); assertEquals(WeaponType.HANDGUN, acc.getWeapons().get(0).getWeaponType()); assertEquals(WeaponType.WALL, acc.getWeapons().get(1).getWeaponType()); assertEquals(0, acc.getHighScore()); assertEquals(0, acc.getCurrentScore()); assertEquals(100, acc.getPlayer().getHealth()); assertEquals(0, acc.getPlayer().getKills()); } catch (IOException e) { fail("IOException was thrown and caught when it shouldn't have."); } } }
package com.tencent.mm.plugin.product.ui; import android.widget.TextView; class i$a { public TextView lTt = null; public MaxGridView lTu = null; public j lTv = null; final /* synthetic */ i lTw; i$a(i iVar) { this.lTw = iVar; } }
/* * Copyright (c) 2018, Lawrence Livermore National Security, LLC. Produced at the Lawrence Livermore National Laboratory * CODE-743439. * All rights reserved. * This file is part of CCT. For details, see https://github.com/LLNL/coda-calibration-tool. * * Licensed under the Apache License, Version 2.0 (the โ€œLicenseeโ€); you may not use this file except in compliance with the License. You may obtain a copy of the License at: * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an โ€œAS ISโ€ BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and limitations under the license. * * This work was performed under the auspices of the U.S. Department of Energy * by Lawrence Livermore National Laboratory under Contract DE-AC52-07NA27344. */ package llnl.gnem.core.gui.plotting; import java.awt.Color; import java.awt.Graphics; /** * A type-safe enum to represent the paint mode of objects drawn in the axis. * * @author Doug Dodge */ public class PaintMode { private final String name; private PaintMode(String name) { this.name = name; } /** * Return a String description of this type. * * @return The String description */ public String toString() { return name; } /** * Sets the graphics PaintMode based on the PaintMode type * * @param g * The graphics context to be operated on. */ public void setGraphicsPaintMode(Graphics g) { if (name.equals("Copy")) g.setPaintMode(); else g.setXORMode(Color.white); } /** * PaintMode for doing SRCCOPY */ public final static PaintMode COPY = new PaintMode("Copy"); /** * PaintMode for doing XOR */ public final static PaintMode XOR = new PaintMode("Xor"); }
package app; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.io.UnsupportedEncodingException; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import model.FileManager; import model.Graph; import model.Tweet; import model.Util; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonToken; public class Main { private static Graph graph = new Graph(); public static void main(String[] args) { try { //create file variable and inputstream InputStreamReader in = FileManager.createTwitInput(); JsonReader reader = new JsonReader(in); reader.setLenient(true); extract(reader); //close old streams FileManager.closeTwitInput(); } catch (Exception e) { System.err.println("Error with file processing. Please checkout your files" + "/n" + e.toString()); } } private static void extract(JsonReader reader) throws IOException, ParseException { PrintWriter writer = FileManager.createFirstFeatOut(); while(true) { if(reader.peek().equals(JsonToken.BEGIN_OBJECT)) { reader.beginObject(); } String created_at = null; String text = null; List<String> tagList = null; while (reader.hasNext()) { String name = reader.nextName(); if(name.equalsIgnoreCase("created_at")) { created_at = reader.nextString(); } else if(name.equalsIgnoreCase("text")) { text = Util.clean(reader.nextString()); } else if(name.equalsIgnoreCase("entities")) { tagList = getHashTags(reader); } else { reader.skipValue(); } } //FEATURE 1. format string and save to file if(text != null && created_at != null) { String formatedStr = text + " (timestamp " + created_at + ")" ; writer.println(formatedStr); } //FEATURE 2. Add tweets to graph and build it on the go if(tagList != null && tagList.size() > 1) { parseTweet(text, created_at, tagList); } reader.endObject(); if(reader.peek().equals(JsonToken.BEGIN_OBJECT)) continue; reader.close(); writer.println(Util.getCount() + " tweets contained unicode"); FileManager.closeFirstFeatOutput(); FileManager.closeSecondFeatOutput(); return; } } private static List<String> getHashTags(JsonReader reader) throws IOException { List<String> tagList = new ArrayList<String>(); reader.beginObject(); while(reader.hasNext()) { String entityName = reader.nextName(); if(entityName.equalsIgnoreCase("hashtags")) { reader.beginArray(); while(reader.hasNext()) { reader.beginObject(); while(reader.hasNext()) { String tagName = reader.nextName(); if(tagName.equalsIgnoreCase("text")) { tagList.add(reader.nextString()); } else { reader.skipValue(); } } reader.endObject(); } reader.endArray(); } else { reader.skipValue(); } } reader.endObject(); return tagList; } private static void parseTweet(String utf8tweet, String createdDateStr, List<String> tagList) throws ParseException, IOException { //parse date DateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy", Locale.ENGLISH); Date date = format.parse(createdDateStr); Tweet newTwt = new Tweet(utf8tweet, date, tagList); graph.add(newTwt); } }
import java.util.Scanner; public class main_pg8_4 { public static void main(String[] args) { Scanner keyboard = new Scanner(System.in); System.out.println("Enter initial price."); double price= keyboard.nextDouble(); // price = 500;System.out.println("500"); double oj_price = price; int month; double total_balance_owed; double down_payment = .10 * price;//System.out.println("down payment : "+ down_payment); price = price - down_payment;//System.out.println("price"+ price); // System.out.printf("%-10s%,10.2f\n", "Price", 10000.5); // System.out.printf("%10d%14d\n", 45, 632); // System.out.printf("%10d%14d", 4545, 63278987); int x = 1; double principle = 0; //money accumulated from intetst rate; double interest = .01; double payment = .05 * (oj_price - down_payment); // payment due for month; double balance; //money after everything is paid System.out.printf("%-5s%14s%16s%16s%19s%19s\n", "Month", "balance owed", "Interest owed", "Principle due", "Payment for month", "balance remaining" ); while(price > 0){ principle = (principle)+((price + principle) * interest); System.out.printf("%-5d%,14.2f%,16.2f%,16.2f%,19.2f%,19.2f\n", x, price + principle, 1.01 * (price + principle), price, payment, (price+ principle)-payment ); price = (price+ principle)-payment; principle = 0; x++; if(price < 0){ System.out.println("Transaction finsiehd, thank you for the money"); } } } }
package com.leetcode.oj; // 152 https://leetcode.com/problems/maximum-product-subarray/ public class MaximumProductSubarray_152 { public int maxProduct(int[] nums){ if(nums==null||nums.length==0){ return Integer.MIN_VALUE; } int maxEnd = nums[0]; int minEnd = nums[0]; int maxSofar = nums[0]; for(int i=1;i<nums.length;i++){ int tmin = Math.min(minEnd*nums[i], nums[i]); tmin = Math.min(maxEnd*nums[i], tmin); int tmax = Math.max(minEnd*nums[i], nums[i]); tmax = Math.max(maxEnd*nums[i], tmax); minEnd = tmin; maxEnd = tmax; if(maxSofar < maxEnd){ maxSofar = maxEnd; } } return maxSofar; } public static void main(String[] args) { // TODO Auto-generated method stub } }
package com.example.SBNZ.mappers; import com.example.SBNZ.enums.diet.Goal; import org.springframework.stereotype.Component; import java.util.ArrayList; import java.util.List; @Component public class GoalMapper implements MapperInterface<Goal, String>{ @Override public Goal toEntity(String dto) { return Goal.valueOf(dto); } @Override public String toDTO(Goal entity) { return entity.toString(); } @Override public List<Goal> toEntityList(List<String> dtos) { List<Goal> goals = new ArrayList<>(); for (String dto: dtos) { goals.add(this.toEntity(dto)); } return goals; } @Override public List<String> toDTOList(List<Goal> entities) { List<String> dtos = new ArrayList<>(); for (Goal goal: entities) { dtos.add(this.toDTO(goal)); } return dtos; } }
package controller; import model.Acao; import model.Dificuldade; public class GameControl { public static void main(String[] args) { MapaDoJogo m = MapaDoJogo.getInstance(3, Dificuldade.MEDIO); m.alteraJogador(0, Acao.ATACAR, true); m.alteraJogador(1, Acao.DEFENDER, false); m.alteraJogador(2, Acao.ATACAR, true); m.alteraOponente(0, Acao.ATACAR, false); m.alteraOponente(1, Acao.ATACAR, true); m.alteraOponente(2, Acao.DEFENDER, false); int indexRodada = 1; while (m.rodada(indexRodada)) { System.out.println("=============================================================="); m.printVidas(); indexRodada++; } m.printVidas(); if (m.isGameOver()) { System.out.println("GAME OVER!"); } else { System.out.println("VOCรŠ VENCEU!"); } } }
package eu.randomcrap.explosivetraps; import org.bukkit.Server; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; import org.bukkit.plugin.PluginManager; import org.bukkit.plugin.java.JavaPlugin; import com.sk89q.worldguard.bukkit.WorldGuardPlugin; import com.tommytony.war.War; public class ExplosiveTraps extends JavaPlugin { War warplugin; Traps traps; WorldGuardPlugin wgplugin; final static int[] lowBlocks = new int[] { 0, 6, 8, 9, 10, 11, 18, 26, 27, 28, 29, 30, 31, 32, 37, 38, 39, 40, 44, 50, 51, 55, 59, 65, 66, 69, 70, 72, 75, 76, 77, 78, 83, 90, 92, 93, 94, 96, 104, 105, 106, 111, 115, 119, 126, 127, 131, 132, 140, 141, 142, 143, 147, 148, 149, 150, 151, 157, 171, 175 }; final static int[] interactiveBlocks = new int[] { 54, 69, 58, 77, 61, 23, 62, 63, 145, 143, 26, 64, 68, 93, 94, 96, 107, 116, 117, 138, 146, 149, 150, 158, 137, 130, 154 }; @Override public void onEnable() { saveDefaultConfig(); final Server server = getServer(); final PluginManager pm = server.getPluginManager(); warplugin = (War) pm.getPlugin("War"); wgplugin = (WorldGuardPlugin) pm.getPlugin("WorldGuard"); traps = new Traps(this); pm.registerEvents(traps, this); return; } @Override public void onDisable() { getServer().getScheduler().cancelTasks(this); } @Override public boolean onCommand(final CommandSender sender, final Command cmd, final String label, final String[] args) { if (cmd.getName().equalsIgnoreCase("setTrapBlock") && args.length > 0) { int item; try { item = Integer.parseInt(args[0]); } catch (final Exception e) { return false; } if (!new ItemStack(item).getType().isBlock()) return false; getConfig().set("trapBlock", item); traps.proximityTrapBlock = item; traps.lowBlock = isLowBlock(item); sender.sendMessage("TrapBlock set to " + item); saveConfig(); return true; } else if (cmd.getName().equalsIgnoreCase("setPlacingItem") && args.length > 0) { int item; try { item = Integer.parseInt(args[0]); } catch (final Exception e) { return false; } getConfig().set("placingItem", item); traps.proximityPlacingItem = item; sender.sendMessage("PlacingItem set to " + item); saveConfig(); return true; } else if (cmd.getName().equalsIgnoreCase("getProximityTrap") && args.length > 0) { if (sender instanceof Player) { int amount; try { amount = Integer.parseInt(args[0]); } catch (final Exception e) { return false; } if (amount <= 0) return false; final Player player = (Player) sender; final ItemStack proximityTrap = new ItemStack( traps.proximityPlacingItem, amount, (short) traps.proximityPlacingItemDurability); traps.nameStack(proximityTrap, "Proximity Trap", "Explosive Trap"); player.getInventory().addItem(proximityTrap); return true; } } else if (cmd.getName().equalsIgnoreCase("getRemoteTrap") && args.length > 0) { if (sender instanceof Player) { int amount; try { amount = Integer.parseInt(args[0]); } catch (final Exception e) { return false; } if (amount <= 0) return false; final Player player = (Player) sender; final ItemStack remoteTrap = new ItemStack( traps.remotePlacingItem, amount, (short) traps.remotePlacingItemDurability); traps.nameStack(remoteTrap, "Remote Detonator Trap", "Explosive Trap"); player.getInventory().addItem(remoteTrap); return true; } } return false; } boolean isLowBlock(final int itemId) { for (final int lowBlock : lowBlocks) { if (itemId == lowBlock) return true; } return false; } boolean isInteractiveBlock(final int itemId) { for (final int interactiveBlock : interactiveBlocks) { if (itemId == interactiveBlock) return true; } return false; } }
package com.app.pojos; import javax.persistence.Column; import javax.persistence.Embeddable; @Embeddable public class Address { @Column(name="addr_1") private String addr; @Column(name="city") private String city; @Column(name="state") private String state; @Column(name="landmark") private String landmark; @Column(name="zipcode") private String zipcode; public Address() {} public Address(String addr, String city, String state, String zipcode, String landmark) { super(); this.addr = addr; this.city = city; this.state = state; this.zipcode = zipcode; this.landmark = landmark; } public String getAddr() { return addr; } public void setAddr(String addr) { this.addr = addr; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getZipcode() { return zipcode; } public void setZipcode(String zipcode) { this.zipcode = zipcode; } public String getLandmark() { return landmark; } public void setLandmark(String landmark) { this.landmark = landmark; } public String getAddressString() { String addr ; addr = this.addr+", "+this.city+", "+this.landmark+","+this.state+", "+this.zipcode; return addr; } @Override public String toString() { return "Address [addr=" + addr + ", city=" + city + ", state=" + state + ", zipcode=" + zipcode + "]"; } }
package com.gin.pixivmanager.controller; import com.gin.pixivmanager.service.DataManager; import com.gin.pixivmanager.service.NgaPostServ; import com.gin.pixivmanager.service.UserInfo; import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.Arrays; import java.util.Map; @Slf4j @RestController @RequestMapping("nga") public class NgaController { final NgaPostServ ngaPostServ; final DataManager dataManager; final UserInfo userInfo; public NgaController(NgaPostServ ngaPostServ, DataManager dataManager, UserInfo userInfo) { this.ngaPostServ = ngaPostServ; this.dataManager = dataManager; this.userInfo = userInfo; } @RequestMapping("repost") public void repost(HttpServletResponse response, String f, String t, String... name) throws IOException { log.info("่ฝฌๅ‘ๆ–‡ไปถ {} {}",name.length,Arrays.asList(name)); String repost = ngaPostServ.repost(f, t, name); response.sendRedirect(repost); } @RequestMapping("getInfo") public Map<String, Object> getInfo() { return userInfo.getInfos(); } }
package com.coda.visitors; import org.springframework.web.bind.annotation.*; import java.sql.SQLException; import java.util.List; @RestController public class VisitorController { VisitorRepo repo = new VisitorRepo(); @RequestMapping("/") public String helloWorld() { return "helloWorld"; } @PostMapping("/createvisitor") public VisitorModel createVisitor(@RequestBody VisitorModel visitor) throws SQLException { repo.createVisitor(visitor); return visitor; } @PutMapping("/exitvisitor") public VisitorModel2 exitVisitor(@RequestBody VisitorModel2 visitor) throws SQLException { repo.updateOutTime(visitor); return visitor; } @PutMapping("/editvisitor") public VisitorModel2 editVisitor(@RequestBody VisitorModel2 visitor) throws SQLException { repo.editVisitor(visitor); return visitor; } @DeleteMapping ("/deletevisitor/{VisitorId}") public String deletevisitor( Integer VisitorId) throws SQLException { VisitorModel2 visitor = repo.getsinglevisitor(VisitorId); if(visitor.getVisitorId()!= 0) { repo.deleteVisitor(VisitorId); } return "Deleted"; } @GetMapping ("/listallvisitors") public List<VisitorModel2> listallvisitors() throws SQLException { return repo.getvisitor(); } @GetMapping("/getvisitor/{VisitorId}") public VisitorModel2 getSingleVisitor(Integer VisitorId) throws SQLException { return repo.getsinglevisitor(VisitorId); } }
package com.other.updown.domain.jsonkey; public class RecordInfoJsonKey { public final static String RECORD_START_NO = "RecordStartNo"; public final static String RETURN_NUM = "ReturnNum"; public final static String TOTAL_NUM = "TotalNum"; }
/* * [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.cms2.servicelayer.services.impl; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.when; import de.hybris.bootstrap.annotations.UnitTest; import de.hybris.platform.core.model.ItemModel; import de.hybris.platform.core.model.type.AttributeDescriptorModel; import de.hybris.platform.core.model.type.ComposedTypeModel; import de.hybris.platform.servicelayer.type.TypeService; import java.util.Collection; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; @UnitTest @RunWith(MockitoJUnitRunner.class) public class DefaultAttributeDescriptorModelHelperServiceTest { @Mock private TypeService typeService; @InjectMocks private DefaultAttributeDescriptorModelHelperService predicate; @Mock private AttributeDescriptorModel simpleAttributeDescriptor; @Mock private AttributeDescriptorModel collectionAttributeDescriptor; @Mock private ComposedTypeModel enclosingType; @Mock private ComposedTypeModel enclosingTypeThatHasCollection; public static class TestType extends ItemModel { private PropertyType testProperty; public PropertyType getTestProperty() { return testProperty; } } public static class TestTypeThatHasCollection extends ItemModel { private Collection<PropertyType> testProperties; public Collection<PropertyType> getTestProperties() { return testProperties; } } public static class PropertyType { // intentionally left empty } @Before public void setup() { when(simpleAttributeDescriptor.getQualifier()).thenReturn("testProperty"); when(simpleAttributeDescriptor.getDeclaringEnclosingType()).thenReturn(enclosingType); doReturn(TestType.class).when(typeService).getModelClass(enclosingType); when(collectionAttributeDescriptor.getQualifier()).thenReturn("testProperties"); when(collectionAttributeDescriptor.getDeclaringEnclosingType()).thenReturn(enclosingTypeThatHasCollection); doReturn(TestTypeThatHasCollection.class).when(typeService).getModelClass(enclosingTypeThatHasCollection); } @Test public void givenANonCollectionPropertyThenTypeCanBeRetrieved() { assertThat(predicate.getAttributeClass(simpleAttributeDescriptor).equals(PropertyType.class), is(true)); } @Test public void givenACollectionPropertyThenGenericTypeCanBeRetrieved() { assertThat(predicate.getAttributeClass(collectionAttributeDescriptor).equals(PropertyType.class), is(true)); } }
package la.opi.verificacionciudadana.api; import java.util.StringTokenizer; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by Jhordan on 25/02/15. */ public class HttpHelper { private static String token ; public static String regexToken(String html){ String regex = "<meta content=\"([^\\s]+)\" name=\"csrf-token\""; Pattern pattern = Pattern.compile(regex); Matcher match = pattern.matcher(html); String token = ""; if(match.find()){ StringTokenizer st = new StringTokenizer(match.group(0),"\""); st.nextToken(); token = st.nextToken(); } return token; } public static boolean regexLoginSuccess(String html){ boolean success; String regex = "id=\"flash_alert\"([^\\s]+)Correo o contra([^\\s]+)a in([^\\s]+)dos"; Pattern pat = Pattern.compile(regex); Matcher match = pat.matcher(html); success = !match.find(); return success; } }
package org.sodeja.act; public class ActorId { private final ActorManager manager; private boolean running = true; protected ActorId(ActorManager manager) { this.manager = manager; } public ActorId send(Object msg) { if(running) { manager.send(this, msg); } else { throw new RuntimeException("Actor is already death"); } return this; } public void link(ActorId otherId) { if(running) { manager.link(this, otherId); } else { throw new RuntimeException("Actor is already death"); } } protected void stop() { running = false; } }
package com.tmtmmobile.tmtm; import android.app.Activity; import android.app.AlarmManager; import android.app.PendingIntent; import android.app.ProgressDialog; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.fasterxml.jackson.databind.ObjectMapper; import com.tmtmmobile.tmtm.BroadCastReceivers.AlarmBroadCastReceiver; import com.tmtmmobile.tmtm.DataBaseHelper.DbHelper; import com.tmtmmobile.tmtm.dto.JSONMessage; import com.tmtmmobile.tmtm.dto.RepeatTaskDto; import com.tmtmmobile.tmtm.dto.TmtmTaskDto; import com.tmtmmobile.tmtm.dto.UserLogin; import com.tmtmmobile.tmtm.dto.UserSignUp; import com.tmtmmobile.tmtm.dto.userIdDto; import com.tmtmmobile.tmtm.ipaddress.MyIP; import com.tmtmmobile.tmtm.remote.TmTmWebServiceInterfaceLogin; import com.tmtmmobile.tmtm.remote.TmTmWebServiceInterfaceSync; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; import retrofit2.Retrofit; import retrofit2.converter.jackson.JacksonConverterFactory; public class LoginActivity extends AppCompatActivity { EditText emailInput; EditText passwordInput; TextView forgotPassword; TextView signupWithEmail; Button loginButton; DbHelper dbHelper; ProgressDialog progressDialog; Activity activity; UserSignUp mappedUser; SharedPreferences sharedpreferences; ////////////////////////////// ////////////////////////////// //private LoginButton facebookLoginButton; //private CallbackManager callbackManager; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ////////////////////////////// // FacebookSdk.sdkInitialize(getApplicationContext()); // callbackManager = CallbackManager.Factory.create(); ////////////////////////////// setContentView(R.layout.activity_login); activity = this; dbHelper = DbHelper.getInstance(getApplicationContext()); // facebookLoginButton = (LoginButton)findViewById(R.id.login_button); ////////////////////////////// loginButton = (Button) findViewById(R.id.btn_login); emailInput = (EditText) findViewById(R.id.input_email); passwordInput = (EditText) findViewById(R.id.input_password); forgotPassword = (TextView) findViewById(R.id.forgot_password); signupWithEmail = (TextView) findViewById(R.id.signup); ////////////////////////////// //Facebook callbacks // facebookLoginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() { // @Override // public void onSuccess(LoginResult loginResult) { // Log.i("iddddd: ", loginResult.getAccessToken().getUserId()); // //////////////////////////////////////////////////////////////////////////////// // if (AccessToken.getCurrentAccessToken() != null) { // // GraphRequest request = GraphRequest.newMeRequest( // loginResult.getAccessToken(), new GraphRequest.GraphJSONObjectCallback() { // // @Override // public void onCompleted(JSONObject me, GraphResponse response) { // if (AccessToken.getCurrentAccessToken() != null) { // // if (me != null) { // String profileImageUrl = ImageRequest.getProfilePictureUri(me.optString("id"), 500, 500).toString(); // Log.i("imageeeeeee", profileImageUrl); // Log.i("JSON: ", response.toString()); // Log.i("JSON: ", me.toString()); // } // } // } // }); // Bundle parameters = new Bundle(); // parameters.putString("fields", "id,name,first_name,last_name,gender,email"); // request.setParameters(parameters); // request.executeAsync(); // //GraphRequest.executeBatchAsync(request); // } // //////////////////////////////////////////////////////////////////////////////// // } // // @Override // public void onCancel() { // // } // // @Override // public void onError(FacebookException error) { // Log.i("error: ", error.toString()); // } // }); ////////////////////////////// forgotPassword.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(getApplicationContext(), ForgetPasswordActivity.class); startActivity(i); } }); signupWithEmail.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //TODO sign up class Intent i = new Intent(getApplicationContext(), SignUpActivity.class); startActivity(i); } }); loginButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { loginButton.setClickable(false); String email = emailInput.getText().toString(); String password = passwordInput.getText().toString(); if ((!email.equals("") ) && ( !password.equals(""))) { UserLogin userLogin = new UserLogin(); userLogin.setUserEmail(email); userLogin.setUserPassword(password); //call web service checkLoginInfo(userLogin); } else { //Did not enter valid email/password loginButton.setClickable(true); Toast.makeText(getApplicationContext(), "Invalid email/password !", Toast.LENGTH_LONG).show(); } } }); } void checkLoginInfo(UserLogin loginInfo) { //check login info progressDialog = ProgressDialog.show(activity, "Loading", "Please wait...", true); Retrofit retrofit = new Retrofit.Builder() .baseUrl(MyIP.ip + "TmTm.webservices/tmtm/login/") .addConverterFactory(JacksonConverterFactory.create()) .build(); TmTmWebServiceInterfaceLogin loginService = retrofit.create(TmTmWebServiceInterfaceLogin.class); Call<JSONMessage> loginCall = loginService.tmtmUserLogin(loginInfo); final ObjectMapper mapper = new ObjectMapper(); loginCall.enqueue(new Callback<JSONMessage>() { @Override public void onResponse(Call<JSONMessage> call, Response<JSONMessage> response) { //System.out.println(response); if (response.body().isError()) { //map response String userJSON = response.body().getData(); try { mappedUser = mapper.readValue(userJSON, UserSignUp.class); dbHelper.addUser(mappedUser); } catch (IOException e) { e.printStackTrace(); } //shared preferences isLoggedIn = true sharedpreferences = getSharedPreferences("MyPref", 0); SharedPreferences.Editor editor = sharedpreferences.edit(); editor.putBoolean("isLoggedIn", true); editor.putInt("id", mappedUser.getUserId()); editor.commit(); getUserTask(mappedUser.getUserId()); } else { //invalid login loginButton.setClickable(true); progressDialog.dismiss(); Toast.makeText(getApplicationContext(), "Invalid email/password !", Toast.LENGTH_LONG).show(); } } @Override public void onFailure(Call<JSONMessage> call, Throwable t) { //TODO on failure case loginButton.setClickable(true); progressDialog.dismiss(); Toast.makeText(getApplicationContext(), "Check your internet connection", Toast.LENGTH_SHORT).show(); t.printStackTrace(); } }); } @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); } // @Override // protected void onActivityResult(int requestCode, int resultCode, Intent data) { // Log.i("dataaaaaaaa:", data.toString()); // super.onActivityResult(requestCode, resultCode, data); // callbackManager.onActivityResult(requestCode, resultCode, data); // } void getUserTask(final int userId) { Retrofit retrofit = new Retrofit.Builder() .baseUrl(MyIP.ip + "TmTm.webservices/tmtm/sync/") .addConverterFactory(JacksonConverterFactory.create()) .build(); TmTmWebServiceInterfaceSync backUpService = retrofit.create(TmTmWebServiceInterfaceSync.class); userIdDto userIdClass = new userIdDto(); userIdClass.setUserId(userId); Call<JSONMessage> backUpCall = backUpService.backUpTasks(userIdClass); final ObjectMapper mapper = new ObjectMapper(); backUpCall.enqueue(new Callback<JSONMessage>() { @Override public void onResponse(Call<JSONMessage> call, Response<JSONMessage> response) { System.out.println(response); if (response != null && response.body().isError()) { //map response String tasksJSON = response.body().getData(); try { TmtmTaskDto[] tasks = mapper.readValue(tasksJSON, TmtmTaskDto[].class); dbHelper.deleteUserTasks(userId); for (int i = 0; i < tasks.length; i++) { if (tasks[i].getTaskStartTime() > System.currentTimeMillis()) { int id = dbHelper.addTask(tasks[i]); tasks[i].setTaskId(id); dbHelper.updateStatus(id, "upcoming"); setStartAlarm(tasks[i]); setEndAlarm(tasks[i]); System.out.println(tasks[i].getTaskName()); } else if (tasks[i].getTaskStartTime() <= System.currentTimeMillis() && tasks[i].getTaskEndTime() > System.currentTimeMillis()) { int id = dbHelper.addTask(tasks[i]); tasks[i].setTaskId(id); if (tasks[i].getTaskState().equals("pending")) { dbHelper.updateStatus(id, "pending"); } else if (tasks[i].getTaskState().equals("running")) { dbHelper.updateStatus(id, "running"); } else if (tasks[i].getTaskState().equals("upcoming")) { dbHelper.updateStatus(id, "pending"); } setEndAlarm(tasks[i]); } else if (tasks[i].getTaskEndTime() <= System.currentTimeMillis()) { int id = dbHelper.addTask(tasks[i]); tasks[i].setTaskId(id); if (tasks[i].getTaskState().equals("pending") || tasks[i].getTaskState().equals("upcoming")) { dbHelper.updateStatus(id, "missed"); } else if (tasks[i].getTaskState().equals("running")) { dbHelper.updateStatus(id, "finished"); } if (tasks[i].getRepeated().size() > 0 && (tasks[i].getTaskState().equals("pending") || tasks[i].getTaskState().equals("upcoming") || tasks[i].getTaskState().equals("running"))) { Calendar calendar = Calendar.getInstance(); calendar.setTime(new Date(System.currentTimeMillis())); calendar.set(Calendar.HOUR_OF_DAY, 0); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); long dateStartLong = calendar.getTimeInMillis(); ArrayList<RepeatTaskDto> repeatTime = tasks[i].getRepeated(); if (tasks[i].getTaskStartTime() >= dateStartLong) { long min = repeatTime.get(0).getRepeatedDate(); int index = 0; for (int k = 0; k < repeatTime.size(); k++) { if (repeatTime.get(k).getRepeatedDate() < min) { min = repeatTime.get(k).getRepeatedDate(); index = k; } } long differenceInTime = tasks[i].getTaskEndTime() - tasks[i].getTaskStartTime(); tasks[i].setTaskStartTime(min); tasks[i].setTaskEndTime(min + differenceInTime); RepeatTaskDto newRepeat = new RepeatTaskDto(); newRepeat.setRepeatedDate(min + (86400 * 7 * 1000)); tasks[i].getRepeated().set(index, newRepeat); System.out.println("end " + new Date(min + differenceInTime).toString()); System.out.println((new Date(min + (86400 * 7 * 1000))).toString()); int taskId = dbHelper.addTask(tasks[i]); tasks[i].setTaskId(taskId); dbHelper.updateStatus(taskId, "upcoming"); setStartAlarm(tasks[i]); setEndAlarm(tasks[i]); } else { SimpleDateFormat dayFormat = new SimpleDateFormat("EEEE"); ArrayList<RepeatTaskDto> newRepeat = new ArrayList<>(); for (int j = 0; j < repeatTime.size(); j++) { Calendar aDay = Calendar.getInstance(); aDay.setTimeInMillis(tasks[i].getTaskStartTime()); System.out.println("task date " + new Date(tasks[i].getTaskStartTime())); String day = dayFormat.format(repeatTime.get(j).getRepeatedDate()).toString(); if (day.equals("Sunday")) { while (aDay.getTimeInMillis() <= System.currentTimeMillis() + 10000 || aDay.get(Calendar.DAY_OF_WEEK) != Calendar.SUNDAY) { System.out.println("inside sunday"); aDay.add(Calendar.DATE, 1); if (aDay.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY && aDay.getTimeInMillis() > System.currentTimeMillis() + 10000) { break; } } RepeatTaskDto r = new RepeatTaskDto(); r.setRepeatedDate(aDay.getTimeInMillis()); newRepeat.add(r); System.out.println("sunday " + aDay.getTime().toString()); } else if (day.equals("Monday")) { while (aDay.getTimeInMillis() <= System.currentTimeMillis() + 10000 || aDay.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) { aDay.add(Calendar.DATE, 1); if (aDay.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY && aDay.getTimeInMillis() > System.currentTimeMillis() + 10000) { break; } } RepeatTaskDto r = new RepeatTaskDto(); r.setRepeatedDate(aDay.getTimeInMillis()); newRepeat.add(r); System.out.println("monday " + aDay.getTime().toString()); } else if (day.equals("Tuesday")) { while (aDay.getTimeInMillis() <= System.currentTimeMillis() + 10000 || aDay.get(Calendar.DAY_OF_WEEK) != Calendar.TUESDAY) { aDay.add(Calendar.DATE, 1); if (aDay.get(Calendar.DAY_OF_WEEK) == Calendar.TUESDAY && aDay.getTimeInMillis() > System.currentTimeMillis() + 10000) { break; } } RepeatTaskDto r = new RepeatTaskDto(); r.setRepeatedDate(aDay.getTimeInMillis()); newRepeat.add(r); System.out.println("tuesday " + aDay.getTime().toString()); } else if (day.equals("Wednesday")) { while (aDay.getTimeInMillis() <= System.currentTimeMillis() + 10000 || aDay.get(Calendar.DAY_OF_WEEK) != Calendar.WEDNESDAY) { aDay.add(Calendar.DATE, 1); if (aDay.get(Calendar.DAY_OF_WEEK) == Calendar.WEDNESDAY && aDay.getTimeInMillis() > System.currentTimeMillis() + 10000) { break; } } RepeatTaskDto r = new RepeatTaskDto(); r.setRepeatedDate(aDay.getTimeInMillis()); newRepeat.add(r); System.out.println("wednesday " + aDay.getTime().toString()); } else if (day.equals("Thursday")) { while (aDay.getTimeInMillis() <= System.currentTimeMillis() + 10000 || aDay.get(Calendar.DAY_OF_WEEK) != Calendar.THURSDAY) { aDay.add(Calendar.DATE, 1); if (aDay.get(Calendar.DAY_OF_WEEK) == Calendar.THURSDAY && aDay.getTimeInMillis() > System.currentTimeMillis() + 10000) { break; } } RepeatTaskDto r = new RepeatTaskDto(); r.setRepeatedDate(aDay.getTimeInMillis()); newRepeat.add(r); System.out.println("thursday " + aDay.getTime().toString()); } else if (day.equals("Friday")) { while (aDay.getTimeInMillis() <= System.currentTimeMillis() + 10000 || aDay.get(Calendar.DAY_OF_WEEK) != Calendar.FRIDAY) { aDay.add(Calendar.DATE, 1); if (aDay.get(Calendar.DAY_OF_WEEK) == Calendar.FRIDAY && aDay.getTimeInMillis() > System.currentTimeMillis() + 10000) { break; } } RepeatTaskDto r = new RepeatTaskDto(); r.setRepeatedDate(aDay.getTimeInMillis()); newRepeat.add(r); System.out.println("friday " + aDay.getTime().toString()); } else if (day.equals("Saturday")) { while (aDay.getTimeInMillis() <= System.currentTimeMillis() + 10000 || aDay.get(Calendar.DAY_OF_WEEK) != Calendar.SATURDAY) { aDay.add(Calendar.DATE, 1); if (aDay.get(Calendar.DAY_OF_WEEK) == Calendar.SATURDAY && aDay.getTimeInMillis() > System.currentTimeMillis() + 10000) { break; } } RepeatTaskDto r = new RepeatTaskDto(); r.setRepeatedDate(aDay.getTimeInMillis()); newRepeat.add(r); System.out.println("saturday " + aDay.getTime().toString()); } } long min = newRepeat.get(0).getRepeatedDate(); int index = 0; for (int k = 0; k < newRepeat.size(); k++) { if (newRepeat.get(k).getRepeatedDate() < min) { min = newRepeat.get(k).getRepeatedDate(); index = k; } } long differenceInTime = tasks[i].getTaskEndTime() - tasks[i].getTaskStartTime(); tasks[i].setTaskStartTime(min); tasks[i].setTaskEndTime(min + differenceInTime); RepeatTaskDto newRepeatTwo = new RepeatTaskDto(); newRepeatTwo.setRepeatedDate(min + (86400 * 7 * 1000)); newRepeat.set(index, newRepeatTwo); tasks[i].setRepeated(newRepeat); System.out.println("end " + new Date(min + differenceInTime).toString()); System.out.println((new Date(min + (86400 * 7 * 1000))).toString()); int taskId = dbHelper.addTask(tasks[i]); tasks[i].setTaskId(taskId); dbHelper.updateStatus(taskId, "upcoming"); setStartAlarm(tasks[i]); setEndAlarm(tasks[i]); } } } } System.out.println("tasks.size " + tasks.length); } catch (IOException e) { e.printStackTrace(); } } loginButton.setClickable(true); progressDialog.dismiss(); Intent i = new Intent(getApplicationContext(), NavigationDrawerActivity.class); startActivity(i); } @Override public void onFailure(Call<JSONMessage> call, Throwable t) { //TODO on failure case progressDialog.dismiss(); loginButton.setClickable(true); t.printStackTrace(); } }); } private void setStartAlarm(TmtmTaskDto task) { Intent intent = new Intent(this, AlarmBroadCastReceiver.class); intent.putExtra("taskId", task.getTaskId()); PendingIntent pendingIntent = PendingIntent.getBroadcast( this.getApplicationContext(), task.getTaskId(), intent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); alarmManager.setExact(AlarmManager.RTC_WAKEUP, task.getTaskStartTime(), pendingIntent); System.out.println("alarm start time is set"); } private void setEndAlarm(TmtmTaskDto task) { Intent intent = new Intent(this, AlarmBroadCastReceiver.class); intent.putExtra("taskId", -task.getTaskId()); PendingIntent pendingIntent = PendingIntent.getBroadcast( this.getApplicationContext(), -task.getTaskId(), intent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE); alarmManager.setExact(AlarmManager.RTC_WAKEUP, task.getTaskEndTime(), pendingIntent); System.out.println("alarm End time is set"); } }
package gr.hua.dit.ds.ergasia.Rest; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import gr.hua.dit.ds.ergasia.Service.SystemService; import gr.hua.dit.ds.ergasia.entity.Form; @RestController @RequestMapping("/api") public class RestControllerr { @Autowired private SystemService Service; @GetMapping("/forms") public List<Form> getforms(){ return Service.getForms(); } }
package br.usp.memoriavirtual.modelo.fachadas; import java.util.ArrayList; import java.util.Date; import java.util.List; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Query; import br.usp.memoriavirtual.modelo.entidades.Acesso; import br.usp.memoriavirtual.modelo.entidades.Aprovacao; import br.usp.memoriavirtual.modelo.entidades.Grupo; import br.usp.memoriavirtual.modelo.entidades.Usuario; import br.usp.memoriavirtual.modelo.fachadas.remoto.ExcluirUsuarioRemote; @Stateless(mappedName = "ExcluirUsuario") public class ExcluirUsuario implements ExcluirUsuarioRemote { @PersistenceContext(unitName = "memoriavirtual") private EntityManager entityManager; @SuppressWarnings("unchecked") public List<Usuario> listarUsuarios(String parteNome, Usuario requerente, boolean isAdministrador) throws ModeloException { List<Usuario> usuarios = new ArrayList<Usuario>(); if (isAdministrador) { Query query = this.entityManager .createQuery("SELECT u FROM Usuario u WHERE " + "u.ativo = TRUE AND " + "LOWER(u.nomeCompleto) LIKE LOWER(:nome) AND " + "u <> :requerente" + " ORDER BY u.nomeCompleto "); query.setParameter("requerente", requerente); query.setParameter("nome", "%" + parteNome + "%"); try { usuarios = (List<Usuario>) query.getResultList(); } catch (Exception e) { throw new ModeloException(e); } } else { Query query = this.entityManager .createQuery("SELECT b.usuario from Acesso a, Acesso b " + "WHERE a.usuario = :requerente AND a.grupo = :grupo " + "AND b.instituicao = a.instituicao AND b.usuario <> :requerente"); query.setParameter("grupo", new Grupo("GERENTE")); query.setParameter("requerente", requerente); try { usuarios = query.getResultList(); } catch (Exception e) { throw new ModeloException(e); } } return usuarios; } public Usuario recuperarDadosUsuario(String nome) throws ModeloException { Usuario usuario = new Usuario(); try { Query query = entityManager .createQuery("SELECT u FROM Usuario u WHERE u.nomeCompleto = :nome"); query.setParameter("nome", nome); usuario = (Usuario) query.getSingleResult(); } catch (Exception e) { throw new ModeloException(e); } return usuario; } @SuppressWarnings("unchecked") public List<Usuario> listarSemelhantes(String eliminador, Boolean isAdministrador) { List<Usuario> usuarios; Query query; if (isAdministrador) { query = this.entityManager .createQuery("SELECT a FROM Usuario a WHERE a.id <> :eliminador " + "AND a.administrador = TRUE ORDER BY a.id "); query.setParameter("eliminador", eliminador); } else { query = this.entityManager .createQuery("SELECT a FROM Usuario a WHERE a.administrador = FALSE AND " + "LOWER(a.nomeCompleto) LIKE LOWER(:parteNome) " + "ORDER BY a.id "); query.setParameter("eliminador", eliminador); } try { usuarios = (List<Usuario>) query.getResultList(); return usuarios; } catch (Exception e) { e.printStackTrace(); return null; } } public Long registrarAprovacao(Usuario validador, String idExcluido, Date dataValidade) throws ModeloException { Date data = new Date(); Usuario u = entityManager.find(Usuario.class, validador.getId()); Aprovacao aprovacao = new Aprovacao(data, u, dataValidade, idExcluido, Usuario.class.getCanonicalName()); try { this.entityManager.persist(aprovacao); } catch (Exception e) { throw new ModeloException(e); } return aprovacao.getId(); } public void marcarUsuarioExcluido(Usuario usuario, boolean marca, boolean flagAcesso) throws ModeloException { Query query; query = this.entityManager .createQuery("UPDATE Usuario a SET a.ativo = :validade WHERE a.id = :id"); query.setParameter("id", usuario.getId()); query.setParameter("validade", marca); query.executeUpdate(); if (flagAcesso) { query = this.entityManager .createQuery("UPDATE Acesso a SET a.validade = :validade WHERE a.usuario = :usuario"); query.setParameter("usuario", usuario); query.setParameter("validade", marca); query.executeUpdate(); } } @SuppressWarnings("unchecked") @Override public List<Acesso> listarAcessos(Usuario usuario) throws ModeloException { List<Acesso> acessos = new ArrayList<Acesso>(); Query query = this.entityManager .createQuery("SELECT a FROM Acesso a WHERE a.usuario = :usuario"); query.setParameter("usuario", usuario); try { acessos = (List<Acesso>) query.getResultList(); } catch (Exception e) { throw new ModeloException(e); } return acessos; } @SuppressWarnings("unchecked") @Override public List<Usuario> listarAprovadores(Usuario requerente, Usuario usuario) throws ModeloException { List<Acesso> acessos = new ArrayList<Acesso>(); List<Usuario> aprovadores = new ArrayList<Usuario>(); Query listarAcessos = entityManager .createQuery("SELECT a FROM Acesso a WHERE a.usuario = :usuario AND a.validade = TRUE"); listarAcessos.setParameter("usuario", usuario); try { acessos = (List<Acesso>) listarAcessos.getResultList(); } catch (Exception e) { throw new ModeloException(); } Query listarAdministradores = entityManager .createQuery("SELECT u FROM Usuario u WHERE " + "u.ativo = TRUE AND u.administrador = TRUE AND u <> :requerente AND u <> :usuario"); listarAdministradores.setParameter("usuario", usuario); listarAdministradores.setParameter("requerente", requerente); try { aprovadores = listarAdministradores.getResultList(); } catch (Exception e) { throw new ModeloException(); } for (Acesso a : acessos) { Query listarAprovadores = entityManager .createQuery("SELECT a.usuario FROM Acesso a WHERE a.grupo = :grupo " + "AND a.instituicao = :instituicao AND a.validade = TRUE AND a.usuario <> :requerente AND a.usuario <> :usuario"); listarAprovadores.setParameter("grupo", new Grupo("gerente")); listarAprovadores.setParameter("instituicao", a.getInstituicao()); listarAprovadores.setParameter("requerente", requerente); listarAprovadores.setParameter("usuario", usuario); try { List<Usuario> gerentes = listarAprovadores.getResultList(); for (Usuario u : gerentes) { aprovadores.add(u); } } catch (Exception e) { throw new ModeloException(); } } return aprovadores; } @Override public Aprovacao recuperarDadosAprovacao(String id) throws ModeloException { Aprovacao aprovacao = new Aprovacao(); Query query = this.entityManager .createQuery("SELECT a FROM Aprovacao a WHERE a.id = :id"); query.setParameter("id", id); try { aprovacao = (Aprovacao) query.getSingleResult(); } catch (Exception e) { throw new ModeloException(); } return aprovacao; } @Override public void excluirUsuario(String id) throws ModeloException { try { Aprovacao aprovacao = this.entityManager.find(Aprovacao.class, Long.valueOf(id)); Usuario usuario = this.entityManager.find(Usuario.class, aprovacao.getChaveEstrangeira()); Query removerAcessos = this.entityManager .createQuery("DELETE FROM Acesso a WHERE a.usuario = :usuario"); removerAcessos.setParameter("usuario", usuario); removerAcessos.executeUpdate(); Query query = entityManager .createQuery("DELETE FROM ItemAuditoria i WHERE i.autorAcao = :usuario"); query.setParameter("usuario", usuario); query.executeUpdate(); this.entityManager.remove(usuario); Query removerUsuario = this.entityManager .createQuery("DELETE FROM Aprovacao a WHERE a.id = :id"); removerUsuario.setParameter("id", Long.valueOf(id)); removerUsuario.executeUpdate(); } catch (Exception e) { throw new ModeloException(e); } } public Usuario recuperarUsuario(String id) { Query query1 = this.entityManager .createQuery("SELECT u FROM Usuario u WHERE u.id = :usuario"); query1.setParameter("usuario", id); Usuario usuario = null; try { usuario = (Usuario) query1.getSingleResult(); } catch (Exception e) { e.printStackTrace(); } return usuario; } public void excluirAprovacao(Aprovacao aprovacao) { Query query; query = this.entityManager .createQuery("DELETE FROM Aprovacao a WHERE a = :aprovacao "); query.setParameter("aprovacao", aprovacao); query.executeUpdate(); } }
package com.tyss.cg.methods; public class MethodOverloadingEx { //both static and non static methods can be overloaded. //overloading can be done between static and non static methods too. public static void disp() { System.out.println("public static void disp()..."); } public static void disp(String str) { System.out.println("public static void disp(String str)..."); } public void disp(String string, int i) { System.out.println("public void disp(String str,int i)..."); } public void disp(int i, String str) { System.out.println("public void disp(int i, String str)..."); } public static void main(String[] args) { MethodOverloadingEx mole=new MethodOverloadingEx(); MethodOverloadingEx.disp(); disp("AnyString"); mole.disp("mayank", 24); mole.disp(23, "Mayank"); } }
package br.com.gerenciamento.pessoas; import org.junit.jupiter.api.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class GerenciamentoPessoasApplicationTests { @Test void contextLoads() { } }
package rhtn_homework; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.StringTokenizer; public class BOJ_2096_๋‚ด๋ ค๊ฐ€๊ธฐ { private static int N; public static void main(String[] args) throws IOException{ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); StringTokenizer st; N = Integer.parseInt(br.readLine()); // ๋ฉ”๋ชจ๋ฆฌ ์ ˆ์•ฝ์„ ์œ„ํ•ด ๋‹จ ๋‘์ค„๋งŒ ์‚ฌ์šฉ int[][] map = new int[2][3]; int[][] DP = new int[2][3]; int[][] DP2 = new int[2][3]; int ans = 0; int ans2 = Integer.MAX_VALUE; // ์ฒ˜์Œ ์ค„ ์ž…๋ ฅ ๋ฐ›๊ณ  ์ดˆ๊ธฐํ™” ๊ณผ์ • ... st = new StringTokenizer(br.readLine()); for (int c = 0; c < 3; c++) { map[0][c] = Integer.parseInt(st.nextToken()); DP[0][c] = map[0][c]; DP2[0][c] = map[0][c]; } // ๋‹ค์Œ์ค„ ์ž…๋ ฅ ๋ฐ DP ๊ณ„์‚ฐ for (int r = 1; r < N; r++) { st = new StringTokenizer(br.readLine()); for (int c = 0; c < 3; c++) { map[1][c] = Integer.parseInt(st.nextToken()); if(r == 1){ DP2[1][c] = Integer.MAX_VALUE; } } // DP ์ž‘์—… for (int c = 0; c < 3; c++) { for (int i = -1; i < 2; i++) { if(isIn(1,c+i)) { DP[1][c] = Math.max(DP[1][c], DP[0][c+i] + map[1][c]); DP2[1][c] = Math.min(DP2[1][c], DP2[0][c+i] + map[1][c]); } } } // ํ•ด๋‹น ๊ฐ’์„ ์œ„๋กœ ์˜ฎ๊ธฐ๊ณ  ๋ฐ‘์— ๊ฐ’์„ ์ดˆ๊ธฐํ™” for (int c = 0; c < 3; c++) { map[0][c] = map[1][c]; DP[0][c] = DP[1][c]; DP2[0][c] = DP2[1][c]; DP[1][c] = 0; DP2[1][c] = Integer.MAX_VALUE; } } // ์ตœ๋Œ€, ์ตœ์†Œ๊ฐ’ ์ฐพ๊ธฐ for (int c = 0; c < 3; c++) { ans = Math.max(ans, DP[0][c]); ans2 = Math.min(ans2, DP2[0][c]); } System.out.println(ans + " " + ans2); } private static boolean isIn(int r, int c) { return r>=0 && c>=0 && r < 2 && c< 3; } }
package factorycampodebatalha; import campodebatalha.Terreno; public abstract class TerrenoFactory { public static Terreno getTerreno (String terreno) { return null; } }
package com.tencent.mm.ui.transmit; import com.tencent.mm.storage.bd; import com.tencent.mm.y.g.a; class MsgRetransmitUI$12 implements Runnable { final /* synthetic */ String bAd; final /* synthetic */ bd dAB; final /* synthetic */ MsgRetransmitUI uDL; final /* synthetic */ a uDQ; final /* synthetic */ byte[] uDR; MsgRetransmitUI$12(MsgRetransmitUI msgRetransmitUI, String str, a aVar, byte[] bArr, bd bdVar) { this.uDL = msgRetransmitUI; this.bAd = str; this.uDQ = aVar; this.uDR = bArr; this.dAB = bdVar; } public final void run() { MsgRetransmitUI.a(this.uDL, this.bAd, this.uDQ, this.uDR, this.dAB); } }
package com.tencent.mm.plugin.appbrand.ui.recents; import com.tencent.mm.sdk.platformtools.bi; class a$8 implements Runnable { final /* synthetic */ a gyS; final /* synthetic */ i gyY; a$8(a aVar, i iVar) { this.gyS = aVar; this.gyY = iVar; } public final void run() { if (!bi.cX(a.a(this.gyS))) { int size = a.a(this.gyS).size(); a.a(this.gyS).clear(); a.b(this.gyS).aa(0, size); } a.a(this.gyS).addAll(this.gyY); a.b(this.gyS).Z(0, this.gyY.size()); } }
// Decompiled by DJ v3.7.7.81 Copyright 2004 Atanas Neshkov Date: 20/06/2004 11:11:44 p.m. // Home Page : http://members.fortunecity.com/neshkov/dj.html - Check often for new version! // Decompiler options: packimports(3) nonlb // Source File Name: CheckSecurity.java package com.slort.tag; import javax.servlet.http.HttpSession; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.TagSupport; import com.slort.model.security.Users; public class CheckSecurity extends TagSupport { public CheckSecurity() { grupoPermiso = "default"; typeAction = "reqCode"; userKey = "bdbUser"; } public void release() { super.release(); grupoPermiso = "default"; typeAction = "reqCode"; userKey = "bdbUser"; } public int doStartTag() throws JspException { return 0; } public int doEndTag() throws JspException { boolean valid = false; HttpSession session = pageContext.getSession(); if(session != null && session.getAttribute(userKey) != null) { valid = true; } if(valid) return 6; else throw new JspException("NO TIENE PERMISO."); } public String getGrupoPermiso() { return grupoPermiso; } public String getTypeAction() { return typeAction; } public String getUserKey() { return userKey; } public void setGrupoPermiso(String string) { grupoPermiso = string; } public void setTypeAction(String string) { typeAction = string; } public void setUserKey(String string) { userKey = string; } private String grupoPermiso; private String typeAction; private String userKey; }
package com.example.iutassistant.Presenter; import com.example.iutassistant.Model.CourseModel; import com.example.iutassistant.Model.User; import java.util.List; public interface IFirebaseCourseListPresenter { public void useFireBaseCourseModelList(List<CourseModel> courseModelList); }
package com.data.inserter.service.service; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import javax.sql.DataSource; import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import com.data.inserter.service.config.MessagingConfig; import com.data.inserter.service.model.EmailResponse; import lombok.extern.slf4j.Slf4j; @Component @Slf4j public class DataInserterService { @Autowired private DataSource datasource; @RabbitListener(queues = MessagingConfig.OUTPUT_QUEUE) public void consumeMessageFromOutputQueue(EmailResponse emailResponse) throws SQLException { String SQL_INSERT = new String("insert into emailaddressbatch.emailvalidated (input, is_reachable) values (?, ?)"); log.info("Email Response in for data inserter service"+emailResponse.getInput()); try ( Connection connection = datasource.getConnection(); PreparedStatement statement = connection.prepareStatement(SQL_INSERT); ) { statement.setString(1, emailResponse.getInput()); statement.setString(2, emailResponse.getIs_reachable()); statement.addBatch(); statement.executeBatch(); } log.info("Data Inserted successfully in DB"+emailResponse.getInput()); } }
package tachyon; /** * Used to identify StorageDir in hierarchy store. */ public class StorageDirId { static final long UNKNOWN = -1; /** * Generate StorageDirId from given information * * @param level storage level of the StorageTier which contains the StorageDir * @param storageLevelaliasValue StorageLevelAlias value of the StorageTier * @param dirIndex index of the StorageDir * @return StorageDirId generated */ public static long getStorageDirId(int level, int storageLevelAliasValue, int dirIndex) { return (level << 24) + (storageLevelAliasValue << 16) + dirIndex; } /** * Get index of the StorageDir in the StorageTier which contains it * * @param storageDirId Id of the StorageDir * @return index of the StorageDir */ public static int getStorageDirIndex(long storageDirId) { return (int) storageDirId & 0x00ff; } /** * Get storage level of StorageTier which contains the StorageDir * * @param storageDirId Id of the StorageDir * @return storage level of the StorageTier which contains the StorageDir */ public static int getStorageLevel(long storageDirId) { return ((int) storageDirId >> 24) & 0x0f; } /** * Get StorageLevelAlias value from StorageDirId * * @param storageDirId Id of the StorageDir * @return value of StorageLevelAlias */ public static int getStorageLevelAliasValue(long storageDirId) { return ((int) storageDirId >> 16) & 0x0f; } /** * Check whether the value of StorageDirId is UNKNOWN * * @param storageDirId Id of the StorageDir * @return true if StorageDirId is UNKNOWN, false otherwise. */ public static boolean isUnknown(long storageDirId) { return storageDirId == UNKNOWN; } /** * Get unknown value of StorageDirId, which indicates the StorageDir is unknown * * @return UNKNOWN value of StorageDirId */ public static long unknownId() { return UNKNOWN; } private StorageDirId() {} }
package com.hason.dtp.account.dao; import com.hason.dtp.account.entity.User; import org.springframework.data.jpa.repository.JpaRepository; /** * ็”จๆˆทdao * * @author Huanghs * @since 2.0 * @date 2017/10/18 */ public interface UserRepository extends JpaRepository<User, Long> { /** * ๆ นๆฎ็”จๆˆทๅ๏ผŒๆŸฅ่ฏข่ฎฐๅฝ• * * @param username ็”จๆˆทๅ * @return User */ User findByUsername(String username); }
package mx.uv.fiee.iinf.mp3player; import android.app.Activity; import android.content.Intent; import android.database.Cursor; import android.graphics.drawable.Drawable; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.provider.MediaStore; import android.widget.Button; import android.widget.ImageButton; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.io.IOException; import java.util.concurrent.atomic.AtomicReference; public class DetailsActivity extends Activity { public static final String Clv = "mx.uv.fiee.iinf.mp3player.DetailsActivity"; MediaPlayer player; Thread posThread; Uri mediaUri; ImageButton ImgButton; SeekBar sbProgress; int pos; TextView txtArtista, txtArchivo; @Override protected void onCreate (@Nullable Bundle savedInstanceState) { super.onCreate (savedInstanceState); setContentView (R.layout.activity_details); sbProgress= findViewById (R.id.sbProgress); txtArtista = findViewById(R.id.Artista); txtArchivo = findViewById(R.id.Archivo); ImgButton = findViewById(R.id.ImgB); AtomicReference<Drawable> drw = new AtomicReference<>(getResources().getDrawable(R.drawable.ic_pause_black_48dp, getTheme())); ImgButton.setImageDrawable(drw.get()); sbProgress.setOnSeekBarChangeListener (new MySeekBarChangeListener ()); player = new MediaPlayer (); player.setOnPreparedListener (mediaPlayer -> { posThread = new Thread (() -> { try { while (player.isPlaying ()) { Thread.sleep (1000); sbProgress.setProgress (player.getCurrentPosition ()); } } catch (InterruptedException in) { in.printStackTrace (); } }); sbProgress.setMax (mediaPlayer.getDuration ()); if (pos > -1) mediaPlayer.seekTo (pos); mediaPlayer.start (); posThread.start (); }); ImgButton.setOnClickListener(v-> { if(player.isPlaying()){ drw.set(getResources().getDrawable(R.drawable.ic_play_arrow_black_48dp, getTheme())); player.pause(); }else{ drw.set(getResources().getDrawable(R.drawable.ic_pause_black_48dp, getTheme())); player.start(); } ImgButton.setImageDrawable(drw.get()); }); } @Override protected void onSaveInstanceState (@NonNull Bundle outState) { super.onSaveInstanceState (outState); outState.putString ("SONG", mediaUri != null ? mediaUri.toString (): ""); outState.putInt ("PROGRESS", player != null ? player.getCurrentPosition () : -1); outState.putBoolean ("ISPLAYING", player != null && player.isPlaying ()); if (player.isPlaying ()) { posThread.interrupt (); player.stop (); player.seekTo (0); player.release (); player = null; } } @Override protected void onRestoreInstanceState (@NonNull Bundle savedInstanceState) { super.onRestoreInstanceState (savedInstanceState); mediaUri = Uri.parse (savedInstanceState.getString ("SONG")); pos = savedInstanceState.getInt ("PROGRESS"); boolean isPlaying = savedInstanceState.getBoolean ("ISPLAYING"); if (player == null) return; try { player.reset (); player.setDataSource (getBaseContext (), mediaUri); if (isPlaying) player.prepareAsync (); } catch (IOException | IllegalStateException ioex) { ioex.printStackTrace (); } } @Override protected void onDestroy () { super.onDestroy(); // cleanup if (player != null && player.isPlaying ()) { player.stop (); player.release (); } player = null; } @Override protected void onResume() { super.onResume (); if (player.isPlaying ()) { posThread.interrupt (); player.stop (); player.seekTo (0); sbProgress.setProgress (0); pos = -1; } try { player.setDataSource(getBaseContext (), mediaUri); player.prepare (); } catch (IOException ex) { ex.printStackTrace (); } } @Override protected void onStart() { super.onStart (); Intent intent = getIntent (); if (intent != null) { String audio = intent.getStringExtra (Clv); Toast.makeText (getBaseContext(), audio, Toast.LENGTH_LONG).show (); String [] Clums = { MediaStore.Audio.Media.DISPLAY_NAME,MediaStore.Audio.Artists.ARTIST }; Cursor returnCursor = getContentResolver().query(mediaUri,Clums,null,null,null); int NDisplay = returnCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DISPLAY_NAME); int NArtista = returnCursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ARTIST); returnCursor.moveToFirst(); txtArtista.setText(returnCursor.getString(NArtista)); txtArchivo.setText(returnCursor.getString(NDisplay)); } } class MySeekBarChangeListener implements SeekBar.OnSeekBarChangeListener { @Override public void onProgressChanged (SeekBar seekBar, int i, boolean b) { if (b) { boolean Ban = false; if(player.isPlaying()) { player.pause(); Ban=true; } player.seekTo (i); if(Ban) player.start (); } } @Override public void onStartTrackingTouch (SeekBar seekBar) {} @Override public void onStopTrackingTouch (SeekBar seekBar) {} } }
package com.zhouyi.business.core.dao; import java.math.BigDecimal; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Param; import com.zhouyi.business.core.model.ZyConfigInfo; @Mapper public interface ZyConfigInfoMapper extends BaseMapper<ZyConfigInfo, Long>{ int deleteByPrimaryKey(BigDecimal id); int insert(ZyConfigInfo record); int insertSelective(ZyConfigInfo record); ZyConfigInfo selectByPrimaryKey(@Param("id") BigDecimal id); int updateByPrimaryKeySelective(ZyConfigInfo record); int updateByPrimaryKey(ZyConfigInfo record); }
package com.stryksta.swtorcentral.models; public class AddCharacterItem { private int id; private int class_id; private int advanced_class_id; private int race_id; private int gender_id; private int alignment; private int skill_tree_build_id; private int level; private String name; private String legacy; private int crew_skill_id_1; private int crew_skill_id_2; private int crew_skill_id_3; private String description; public AddCharacterItem(){} public AddCharacterItem(int class_id, int advanced_class_id, int race_id, int gender_id, int alignment, int skill_tree_build_id, int level, String name, String legacy, int crew_skill_id_1, int crew_skill_id_2, int crew_skill_id_3, String description) { super(); this.class_id = class_id; this.advanced_class_id = advanced_class_id; this.race_id = race_id; this.gender_id = gender_id; this.alignment = alignment; this.skill_tree_build_id = skill_tree_build_id; this.level = level; this.name = name; this.legacy = legacy; this.crew_skill_id_1 = crew_skill_id_1; this.crew_skill_id_2 = crew_skill_id_2; this.crew_skill_id_3 = crew_skill_id_3; this.description = description; } public int getId() { return id; } public void setId(int id) { this.id = id; } public int getClassId() { return class_id; } public void setClassId(int class_id) { this.class_id = class_id; } public int getAdvancedClassId() { return advanced_class_id; } public void setAdvancedClassId(int advanced_class_id) { this.advanced_class_id = advanced_class_id; } public int getRace() { return race_id; } public void setRace(int race_id) { this.race_id = race_id; } public int getGender() { return gender_id; } public void setGender(int gender_id) { this.gender_id = gender_id; } public int getAlignment() { return alignment; } public void setAlignment(int alignment) { this.alignment = alignment; } public int getSkillTreeBuildId() { return skill_tree_build_id; } public void setSkillTreeBuildId(int skill_tree_build_id) { this.skill_tree_build_id = skill_tree_build_id; } public int getLevel() { return level; } public void setLevel(int level) { this.level = level; } public String getName() { return name; } public void setName(String legacy) { this.legacy = legacy; } public String getLegacy() { return legacy; } public void setLegacy(String name) { this.name = name; } public int getCrewSkillId_1() { return crew_skill_id_1; } public void setCrewSkillId_1(int crew_skill_id_1) { this.crew_skill_id_1 = crew_skill_id_1; } public int getCrewSkillId_2() { return crew_skill_id_2; } public void setCrewSkillId_2(int crew_skill_id_2) { this.crew_skill_id_2 = crew_skill_id_2; } public int getCrewSkillId_3() { return crew_skill_id_3; } public void setCrewSkillId_3(int crew_skill_id_3) { this.crew_skill_id_3 = crew_skill_id_3; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public String toString() { return "Character [id=" + id + ", name=" + name + ", description=" + description + "]"; } }
package com.tencent.mm.plugin.webview.ui.tools; import com.tencent.mm.plugin.webview.ui.tools.WebViewUI.23; class WebViewUI$23$39 implements Runnable { final /* synthetic */ 23 pZM; WebViewUI$23$39(23 23) { this.pZM = 23; } public final void run() { WebViewUI.n(this.pZM.pZJ).startLoading(); } }
package ch.bbw.addressbook; import java.util.List; import javax.enterprise.context.RequestScoped; import javax.inject.Inject; import javax.inject.Named; @Named @RequestScoped public class AddressViewController { @Inject private AddressService addressService; private String firstname; private String lastname; private String number; public void saveAddress() { Address address = new Address(0, firstname, lastname, number); addressService.storeAddress(address); } public List<Address> getAddresses() { return addressService.getAllAddresses(); } public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public String getNumber() { return number; } public void setNumber(String number) { this.number = number; } }
package com.xjf.wemall.AOPService.helloWorld.API; public interface IIntroductionService { public void induct(); }
package github.abstractfactory.shape; import java.awt.Graphics; public class NotFillSquare extends Shape { @Override public void draw(Graphics graphics) { graphics.setColor(getColor()); graphics.drawRect(0, 0, 100, 100); } }
package Annotation; import java.lang.reflect.Method; import java.util.Scanner; public class Test { public static void main(String[] args) throws Exception { Scanner sc = new Scanner(System.in); System.out.println("ร‡รซรŠรครˆรซร€ร รƒรป:"); String className = sc.nextLine(); Class cls = Class.forName(className); Method[] array = cls.getDeclaredMethods(); Object obj = cls.newInstance(); for(Method method:array) { Demo ann = method.getAnnotation(Demo.class); /* System.out.println(method); System.out.println(ann);*/ if(ann!=null) { method.invoke(obj); } } } }
package pl.lstypka.springSecurityOAuth2DistributedSystem.authorizationServer.service; import org.springframework.security.core.GrantedAuthority; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.stereotype.Service; import pl.lstypka.springSecurityOAuth2DistributedSystem.authorizationServer.bo.SecurityUser; import pl.lstypka.springSecurityOAuth2DistributedSystem.authorizationServer.dto.UserDto; import pl.lstypka.springSecurityOAuth2DistributedSystem.authorizationServer.exception.UserNotFoundException; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; @Service("authService") public class AuthService implements UserDetailsService { @Override public SecurityUser loadUserByUsername(String username) { List<GrantedAuthority> authorities = new ArrayList<>(); if("admin".equals(username)) { authorities.add(()-> "ROLE_ADMIN"); return new SecurityUser(1L, username, "s3cr3t", authorities); } if("user".equals(username)) { authorities.add(()-> "ROLE_USER"); return new SecurityUser(2L, username, "s3cr3t", authorities); } throw new UserNotFoundException("User %s not found".format(username)); }; public UserDto getLoggedUser() { SecurityUser securityUser = (SecurityUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); return new UserDto(securityUser.getUserNo(), securityUser.getUsername(), securityUser.getAuthorities().stream().map(x -> x.getAuthority()).collect(Collectors.toList())); }; }
package com.pybeta.daymatter.ui; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.ProgressDialog; import android.content.res.Resources; import android.os.AsyncTask; import android.os.Bundle; import android.support.v4.view.PagerAdapter; import android.support.v4.view.ViewPager; import android.support.v4.view.ViewPager.OnPageChangeListener; import android.view.View; import android.view.View.OnClickListener; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.pybeta.daymatter.BuildConfig; import com.pybeta.daymatter.Config; import com.pybeta.daymatter.DayMatter; import com.pybeta.daymatter.IContants; import com.pybeta.daymatter.R; import com.pybeta.daymatter.adapter.HolidayDetailAdapter; import com.pybeta.daymatter.core.DataManager; import com.pybeta.daymatter.threadcommon.CustomRunnable; import com.pybeta.daymatter.threadcommon.IDataAction; import com.pybeta.daymatter.tool.DateTimeTool; import com.pybeta.daymatter.utils.DateUtils; import com.pybeta.daymatter.utils.UtilityHelper; import com.pybeta.ui.widget.DatePickerContainer; import com.pybeta.ui.widget.LoadingDialog; import com.pybeta.ui.widget.UcTitleBar; import com.pybeta.ui.widget.UcTitleBar.ITitleBarListener; import com.pybeta.util.DMToast; public class HolidayDetailActivity extends BaseActivity{ private List<DayMatter> mDataList = new ArrayList<DayMatter>(); private ViewPager mViewPager = null; private PagerAdapter mAdapter = null; private LinearLayout mLayoutZheZhao = null; private LinearLayout mLayoutCalendarContainer = null; private int currentPage = 0; // private DatePickerContainerDialog mDatePickerDialog = null; private UcTitleBar mTitleBar = null; private List<View> mViewList = new ArrayList<View>(); private List<String> mIdList = new ArrayList<String>(); private MarkHolidayType mMarkHolidayType; private DatePickerContainer mContentContainer = null; private List<String> mCategoryList = null; private List<String> mOldDateList = null; private String mType = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_holiday_detail); Bundle bundle = getIntent().getExtras(); currentPage = bundle.getInt("position"); mType = bundle.getString("type"); if(mType.equals(Config.ALL_TYPE)){ mDataList = HolidayAllPanel.mDayMatterList; mMarkHolidayType = MarkHolidayType.All; }else if(mType.equals(Config.FESTIVAL_TYPE)){ mDataList = HolidayFestivalPanel.mDayMatterList; mMarkHolidayType = MarkHolidayType.Festival; }else if(mType.equals(Config.HOLIDAY_TYPE)){ mDataList = HolidayHolidayPanel.mDayMatterList; mMarkHolidayType = MarkHolidayType.Holiday; }else if(mType.equals(Config.SOLARTERM_TYPE)){ mDataList = HolidaySolartermPanel.mDayMatterList; mMarkHolidayType = MarkHolidayType.Solarterm; } mViewPager = (ViewPager)this.findViewById(R.id.viewpager_holiday_detail); mLayoutCalendarContainer = (LinearLayout)this.findViewById(R.id.layout_ucCalendar_container); mLayoutZheZhao = (LinearLayout)this.findViewById(R.id.viewpager_holiday_detail_zhezhao); mLayoutZheZhao.setOnClickListener(new OnClickListener() {//้ฎ็ฝฉๅฑ‚ๅ‡บ็Žฐ็š„ๆ—ถๅ€™ๅฐ†ๅบ•ๅฑ‚ไบ‹ไปถๅฑ่”ฝ @Override public void onClick(View arg0) { // TODO Auto-generated method stub } }); initView(true); initTitleBar(); } @Override protected void onResume() { // TODO Auto-generated method stub super.onResume(); } private void initTitleBar(){ mTitleBar = (UcTitleBar)this.findViewById(R.id.uc_titlebar); mTitleBar.setTitleText(getResources().getString(R.string.title_activity_holiday_festival)); if(mMarkHolidayType == MarkHolidayType.Holiday){ mTitleBar.setViewVisible(false, true, false, false, true, false, true, false); }else{ mTitleBar.setViewVisible(false, true, false, false, false, false, true, false); } ITitleBarListener listener = new ITitleBarListener() { @Override public void shareClick(Object obj) { // TODO Auto-generated method stub takeScreenshotAndShare(); } @Override public void editClick(Object obj) { // TODO Auto-generated method stub mLayoutCalendarContainer.removeAllViews(); mLayoutCalendarContainer.setVisibility(View.VISIBLE); mContentContainer = new DatePickerContainer(HolidayDetailActivity.this); mContentContainer.setLayoutParams(new android.widget.LinearLayout.LayoutParams(android.widget.LinearLayout.LayoutParams.MATCH_PARENT,android.widget.LinearLayout.LayoutParams.MATCH_PARENT)); mContentContainer.setDate(mIdList.get(currentPage)); mLayoutCalendarContainer.addView(mContentContainer); mLayoutZheZhao.setVisibility(View.VISIBLE); mTitleBar.setViewVisible(false, true, false, false, false, true, true, false); } @Override public void completeClick(Object obj) { // TODO Auto-generated method stub mLayoutCalendarContainer.setVisibility(View.GONE); mLayoutZheZhao.setVisibility(View.GONE); mTitleBar.setViewVisible(false, true, false, false, true, false, true, false); LoadingDialog.showLoadingDialog(HolidayDetailActivity.this,"ไฟฎๆ”นไธญ..." , false); IDataAction runAction = new IDataAction() { @Override public Object actionExecute(Object obj) { // TODO Auto-generated method stub mContentContainer.saveCustomDate(); freshDate(); return null; } }; IDataAction completeAction = new IDataAction() { @Override public Object actionExecute(Object obj) { // TODO Auto-generated method stub initView(false); return null; } }; CustomRunnable run = new CustomRunnable(runAction, completeAction); run.startAction(); } @Override public void backClick(Object obj) { // TODO Auto-generated method stub finish(); } @Override public void menuClick(Object obj) { // TODO Auto-generated method stub } @Override public void feedBackClick(Object obj) { // TODO Auto-generated method stub } @Override public void addClick(Object obj) { // TODO Auto-generated method stub } @Override public void closeClick(Object obj) { // TODO Auto-generated method stub } }; mTitleBar.setListener(listener); } private void initView(boolean isFirstInit){ if(isFirstInit){ LoadingDialog.showLoadingDialog(HolidayDetailActivity.this,"ๅŠชๅŠ›ๅŠ ่ฝฝไธญ..." , false); } IDataAction runAction = new IDataAction() { @Override public Object actionExecute(Object obj) { List<HashMap<String,String>> convertedList = new ArrayList<HashMap<String,String>>(); for(DayMatter dayMatter: mDataList){ Map<String, Integer> mapBetween = DateUtils.getDaysBetween(dayMatter); HashMap<String, String> map = new HashMap<String, String>(); map.put("Uid", dayMatter.getUid()+""); map.put("Title",dayMatter.getMatter()+""); map.put("BetweenDay", mapBetween.get("Days")+""); map.put("TargetDate", DateUtils.getMatterDateString(HolidayDetailActivity.this, dayMatter)); map.put("Category", dayMatter.getCategory()+""); map.put("OldDate", dayMatter.getOldDate()+""); convertedList.add(map); } return convertedList; } }; IDataAction completeAction = new IDataAction() { @Override public Object actionExecute(Object obj) { if(null != mViewPager){ mViewPager.removeAllViews(); mViewList.clear(); mIdList.clear(); mAdapter = null; } List<HashMap<String,String>> convertedList = (List<HashMap<String,String>>)obj; mCategoryList = new ArrayList<String>(); mOldDateList = new ArrayList<String>(); for(HashMap<String,String> map : convertedList){ View view =getLayoutInflater().inflate(R.layout.viewpager_holiday_detail_content, null); TextView tv_title = (TextView)view.findViewById(R.id.holiday_detail_title); TextView tv_days = (TextView)view.findViewById(R.id.holiday_detail_days); TextView tv_date = (TextView)view.findViewById(R.id.holiday_detail_date); // if(mMarkHolidayType != MarkHolidayType.Holiday ){ // View line = (View)view.findViewById(R.id.bottom_line); // line.setVisibility(View.GONE); // } //ๅกซๅ……ๆ•ฐๆฎ tv_title.setText(map.get("Title")+""); tv_days.setText(map.get("BetweenDay")+""); tv_date.setText(map.get("TargetDate")+""); mViewList.add(view); mIdList.add(map.get("Uid")+""); mCategoryList.add(map.get("Category")); mOldDateList.add((map.get("OldDate")+"")); } mAdapter = new HolidayDetailAdapter(mViewList,mIdList,HolidayDetailActivity.this,mMarkHolidayType, mCategoryList, mOldDateList); mViewPager.setAdapter(mAdapter); mViewPager.setCurrentItem(currentPage); if(mCategoryList.get(currentPage).equals("1")){ mTitleBar.setViewVisible(false, true, false, false, true, false, true, false); }else{ mTitleBar.setViewVisible(false, true, false, false, false, false, true, false); } if(Long.parseLong(mOldDateList.get(currentPage))<System.currentTimeMillis()){ mTitleBar.setViewVisible(false, true, false, false, false, false, true, false); } initViewPagerEvent(); LoadingDialog.closeLoadingDialog(); return null; } }; CustomRunnable run = new CustomRunnable(runAction, completeAction); run.startAction(); } private void initViewPagerEvent(){ mViewPager.setOnPageChangeListener(new OnPageChangeListener() { @Override public void onPageSelected(int position) { // TODO Auto-generated method stub currentPage = position; if(mCategoryList.get(currentPage).equals("1")){ mTitleBar.setViewVisible(false, true, false, false, true, false, true, false); }else{ mTitleBar.setViewVisible(false, true, false, false, false, false, true, false); } if(Long.parseLong(mOldDateList.get(position))<System.currentTimeMillis()){ mTitleBar.setViewVisible(false, true, false, false, false, false, true, false); } } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { // TODO Auto-generated method stub } @Override public void onPageScrollStateChanged(int arg0) { // TODO Auto-generated method stub } }); } private void takeScreenshotAndShare() { new ScreenshotShare().execute(); } class ScreenshotShare extends AsyncTask<String, String, String> { private ProgressDialog progressDlg = null; @Override protected void onPreExecute() { Resources res = HolidayDetailActivity.this.getResources(); progressDlg = ProgressDialog.show(HolidayDetailActivity.this, res.getString(R.string.app_name), res.getString(R.string.screen_shot_progress), false, false); super.onPreExecute(); } @Override protected String doInBackground(String... params) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } String pic = UtilityHelper.takeScreenshot(HolidayDetailActivity.this); if (BuildConfig.DEBUG) { System.out.println("screen shot: " + pic); } return pic; } @Override protected void onPostExecute(String result) { if (progressDlg != null) { progressDlg.dismiss(); } String tips = HolidayDetailActivity.this.getString(R.string.screen_shot_save_path); DMToast.makeText(HolidayDetailActivity.this, tips + result, Toast.LENGTH_SHORT).show(); UtilityHelper.share(HolidayDetailActivity.this, getString(R.string.share_intent_subject), "#" + getString(R.string.app_name) + "#", result); super.onPostExecute(result); } } private void freshDate(){ boolean isAllType = false; List<DayMatter> allDayMatterList = DataManager.getInstance(this).getHolidayList(); List<DayMatter> tempMatterList = null; if(mMarkHolidayType == MarkHolidayType.All){ isAllType = true; tempMatterList = HolidayAllPanel.mDayMatterList = allDayMatterList; }else if(mMarkHolidayType == MarkHolidayType.Holiday){ HolidayHolidayPanel.mDayMatterList.clear(); for(DayMatter dayMatter : allDayMatterList){ if(dayMatter.getCategory() == 1){ HolidayHolidayPanel.mDayMatterList.add(dayMatter); } } tempMatterList = HolidayHolidayPanel.mDayMatterList; }else if(mMarkHolidayType == MarkHolidayType.Festival){ HolidayFestivalPanel.mDayMatterList.clear(); for(DayMatter dayMatter : allDayMatterList){ if(dayMatter.getCategory() == 0){ HolidayFestivalPanel.mDayMatterList.add(dayMatter); } } tempMatterList = HolidayFestivalPanel.mDayMatterList; }else if(mMarkHolidayType == MarkHolidayType.Solarterm){ HolidaySolartermPanel.mDayMatterList.clear(); for(DayMatter dayMatter : allDayMatterList){ if(dayMatter.getCategory() == 2){ HolidaySolartermPanel.mDayMatterList.add(dayMatter); } } tempMatterList = HolidaySolartermPanel.mDayMatterList; } for(DayMatter dayMatter : tempMatterList){ dayMatter.setNextRemindTime(dayMatter.getDate()); } if(!isAllType){ mDataList = DataManager.getInstance(this).sortMatters(tempMatterList, IContants.SORT_BY_DATE_AESC); }else{ mDataList = HolidayAllPanel.mDayMatterList = DataManager.getInstance(this).sortMatters(tempMatterList, IContants.SORT_BY_DATE_AESC); } } public enum MarkHolidayType{ All, Holiday, Festival, Solarterm } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); mViewPager.removeAllViews(); mViewPager = null; if(null != mListener){ mListener.closed(mMarkHolidayType); mListener = null; } } public interface ICloseDetailListener{ void closed(MarkHolidayType type); } public static ICloseDetailListener mListener = null; public static void setListener(ICloseDetailListener listener){ mListener = listener; } }
package com.tencent.mm.ui.contact; import android.view.View; import android.view.View.OnClickListener; class ContactRemarkInfoModUI$a implements OnClickListener { final /* synthetic */ ContactRemarkInfoModUI ujh; private ContactRemarkInfoModUI$a(ContactRemarkInfoModUI contactRemarkInfoModUI) { this.ujh = contactRemarkInfoModUI; } /* synthetic */ ContactRemarkInfoModUI$a(ContactRemarkInfoModUI contactRemarkInfoModUI, byte b) { this(contactRemarkInfoModUI); } public final void onClick(View view) { ContactRemarkInfoModUI.c(this.ujh); } }
/** * */ package cc.feefox.wechat.common.util; /** * @author cc * * @date 2018-8-18 * */ public class ObjectUtil { }
package test; import java.text.DecimalFormat; public class test { public static void main(String[] args) { DecimalFormat decimalFormat = new DecimalFormat("0000.0"); System.out.println(decimalFormat.format(10)); String aString = String.format("%07d", 1); System.out.println(aString); String aString2="00121"; int aInt = Integer.parseInt(aString2); System.out.print(aInt); } }
package com.tencent.mm.plugin.sns.ui; import android.content.Intent; import android.view.View; import android.view.View.OnLongClickListener; import com.tencent.mm.kernel.g; import com.tencent.mm.ui.MMActivity; class j$5 implements OnLongClickListener { final /* synthetic */ j nMb; j$5(j jVar) { this.nMb = jVar; } public final boolean onLongClick(View view) { g.Ek(); if (((Boolean) g.Ei().DT().get(7490, Boolean.valueOf(true))).booleanValue()) { j.c(this.nMb).startActivity(new Intent().setClass(j.c(this.nMb), SnsLongMsgUI.class)); g.Ek(); g.Ei().DT().set(7490, Boolean.valueOf(false)); } else { Intent intent = new Intent(); intent.setClass(j.c(this.nMb), SnsCommentUI.class); intent.putExtra("sns_comment_type", 1); ((MMActivity) j.c(this.nMb)).startActivityForResult(intent, 9); } return true; } }
package pizzaml.service; import java.util.List; import pizzaml.entity.Item; public interface ItemService { public abstract ItemDTO getItemDTO(int id); public abstract Item getItem(int id); public abstract List<ItemSizeCostDTO> getItemItemSizeCostDTO(int id); //item id public abstract void createItem(Item item); public abstract void updateItem(Item item); public abstract void deleteItem(int id); }
package org.zacharylavallee.algorithm.scheduling; import org.junit.Test; import java.time.LocalDateTime; import java.time.ZoneOffset; import java.util.Collection; import java.util.List; import static org.junit.Assert.assertEquals; import static org.zacharylavallee.collection.CollectionUtils.toCollection; import static org.zacharylavallee.collection.CollectionUtils.toList; public class ActivitySelectionTest { @Test public void testSchedule() { Activity activity1 = new Activity(LocalDateTime.ofEpochSecond(0L, 0, ZoneOffset.UTC), LocalDateTime.ofEpochSecond(10L, 0, ZoneOffset.UTC)); Activity activity2 = new Activity(LocalDateTime.ofEpochSecond(9L, 0, ZoneOffset.UTC), LocalDateTime.ofEpochSecond(11L, 0, ZoneOffset.UTC)); Activity activity3 = new Activity(LocalDateTime.ofEpochSecond(12L, 0, ZoneOffset.UTC), LocalDateTime.ofEpochSecond(15L, 0, ZoneOffset.UTC)); Activity activity4 = new Activity(LocalDateTime.ofEpochSecond(12L, 0, ZoneOffset.UTC), LocalDateTime.ofEpochSecond(16L, 0, ZoneOffset.UTC)); Activity activity5 = new Activity(LocalDateTime.ofEpochSecond(20L, 0, ZoneOffset.UTC), LocalDateTime.ofEpochSecond(21L, 0, ZoneOffset.UTC)); Collection<Activity> activities = toCollection(activity1, activity2, activity3, activity4, activity5); List<Activity> expected = toList(activity1, activity3, activity5); List<Activity> actual = ActivitySelection.schedule(activities); assertEquals(expected, actual); } }
package com.esp_ota_update.server.dao; import com.esp_ota_update.server.model.Device; import com.esp_ota_update.server.model.DeviceMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.stereotype.Repository; import java.util.List; @SuppressWarnings("SqlResolve") @Repository("H2-Device") public class DeviceDataAccessService implements DeviceDao { private final JdbcTemplate jdbcTemplate; @Autowired public DeviceDataAccessService(JdbcTemplate jdbcTemplate) { this.jdbcTemplate = jdbcTemplate; } @Override public int insertDevice(Device device) { final String sql = "INSERT INTO device (name, mac, software_name_scheme, status, version, last_software_check, " + "last_software_update) VALUES (?, ?, ?, ?, ?, ?, ?)"; return jdbcTemplate.update( sql, device.getName(), device.getMac(), device.getSoftwareNameScheme(), device.getStatus(), device.getVersion(), device.getLastSoftwareCheck(), device.getLastSoftwareUpdate() ); } @Override public List<Device> selectAllDevices() { final String sql = "SELECT id, name, mac, software_name_scheme, status, version, last_software_check, " + "last_software_update FROM device"; return jdbcTemplate.query(sql, new DeviceMapper()); } @Override public List<Device> selectDeviceById(int id) { final String sql = "SELECT id, name, mac, software_name_scheme, status, version, last_software_check, " + "last_software_update FROM device WHERE id = ?"; return jdbcTemplate.query(sql, new DeviceMapper(), id); } @Override public List<Device> selectDeviceBySoftwareName(String softwareName) { final String sql = "SELECT id, name, mac, software_name_scheme, status, version, last_software_check, " + "last_software_update FROM device WHERE software_name_scheme LIKE ?"; return jdbcTemplate.query(sql, new DeviceMapper(), softwareName + "%"); } @Override public List<Device> selectDeviceByMac(String mac){ final String sql = "SELECT id, name, mac, software_name_scheme, status, version, last_software_check, " + "last_software_update FROM device WHERE mac = ?"; return jdbcTemplate.query(sql, new DeviceMapper(), mac); } @Override public int deleteDeviceById(int id) { final String sql = "DELETE FROM device WHERE id = ?"; return jdbcTemplate.update(sql, id); } @Override public int updateDeviceById(Device device) { final String sql = "UPDATE device SET name = ?, mac = ?, software_name_scheme = ?, status = ?, version = ?, " + "last_software_check = ?, last_software_update = ? WHERE ID = ?"; return jdbcTemplate.update( sql, device.getName(), device.getMac(), device.getSoftwareNameScheme(), device.getStatus(), device.getVersion(), device.getLastSoftwareCheck(), device.getLastSoftwareUpdate(), device.getId() ); } }
package JavaSE.OO.IO; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; /* * java.io.OutputStream; * java.io.FileOutputStream;ๆ–‡ไปถๅญ—่Š‚่พ“ๅ‡บๆต * * ๅฐ†่ฎก็ฎ—ๆœบๅ†…ๅญ˜ไธญ็š„ๆ•ฐๆฎๅ†™ๅ…ฅ็กฌ็›˜ๆ–‡ไปถไธญ */ public class FileOutputStreamTest { public static void main(String[] args) { FileOutputStream fos=null; try { //ๅˆ›ๅปบๆ–‡ไปถๅญ—่Š‚่พ“ๅ‡บๆต //fos=new FileOutputStream("E:\\test02.txt");่ฐจๆ…Žไฝฟ็”จ๏ผŒไผšๅฐ†ๅŽŸๆ–‡ไปถๅ†…ๅฎน่ฆ†็›– //ไปฅ่ฟฝๅŠ ็š„ๆ–นๅผๅ†™ๅ…ฅ fos=new FileOutputStream("E:\\test02.txt",true); //ๅผ€ๅง‹ๅ†™ String msg="HelloWord!"; //ๅฐ†String่ฝฌๆขๆˆbyteๆ•ฐ็ป„ byte[] bytes=msg.getBytes(); //ๅฐ†byteๆ•ฐ็ป„ไธญๆ‰€ๆœ‰็š„ๆ•ฐๆฎๅ†™ๅ…ฅ //fos.write(bytes); //ๅฐ†byteๆ•ฐ็ป„ไธ€้ƒจๅˆ†ๅ†™ๅ…ฅ fos.write(bytes,0,3); //ๆŽจ่ๆœ€ๅŽ็š„ๆ—ถๅ€™ไธบไบ†ไฟ่ฏๆ•ฐๆฎๅฎŒๅ…จๅ†™ๅ…ฅ็กฌ็›˜๏ผŒๆ‰€ไปฅ่ฆๅˆทๆ–ฐ fos.flush();//ๅผบๅˆถๅ†™ๅ…ฅ } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { if(fos!=null) { try { fos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
import java.util.HashMap; public class CheckIfWordEqualsSummationOfTwoWords { public static boolean isSumEqual1(String firstWord, String secondWord, String targetWord) { boolean res = false; int target = createWord(targetWord.length(),targetWord); int first = createWord(firstWord.length(),firstWord); int second = createWord(secondWord.length(),secondWord); if (target == (first + second)){ res = true; } return res; } public static int createWord(int lenOfWord,String word){ int res = 0; HashMap<Character,Integer> map = new HashMap<>(); map.put('a',0); map.put('b',1); map.put('c',2); map.put('d',3); map.put('e',4); map.put('f',5); map.put('g',6); map.put('h',7); map.put('i',8); map.put('j',9); String wordConv = ""; for (int i = 0; i< lenOfWord; i++){ if (map.containsKey(word.charAt(i))){ wordConv = wordConv + map.get(word.charAt(i)); } } res = Integer.valueOf(wordConv); return res; } public static boolean isSumEqual2(String firstWord, String secondWord, String targetWord) { boolean res = false; int target = 0; int first = 0; int second = 0; String wordConv = ""; HashMap<Character,Integer> map = new HashMap<>(); map.put('a',0); map.put('b',1); map.put('c',2); map.put('d',3); map.put('e',4); map.put('f',5); map.put('g',6); map.put('h',7); map.put('i',8); map.put('j',9); int lenOfWord = targetWord.length(); for (int i = 0; i< lenOfWord; i++){ if (map.containsKey(targetWord.charAt(i))){ wordConv = wordConv + map.get(targetWord.charAt(i)); } } target = Integer.valueOf(wordConv); wordConv = ""; lenOfWord = firstWord.length(); for (int i = 0; i< lenOfWord; i++){ if (map.containsKey(firstWord.charAt(i))){ wordConv = wordConv + map.get(firstWord.charAt(i)); } } first = Integer.valueOf(wordConv); wordConv = ""; lenOfWord = secondWord.length(); for (int i = 0; i< lenOfWord; i++){ if (map.containsKey(secondWord.charAt(i))){ wordConv = wordConv + map.get(secondWord.charAt(i)); } } second = Integer.valueOf(wordConv); if (target == (first + second)){ res = true; } return res; } public static boolean isSumEqual(String firstWord, String secondWord, String targetWord) { boolean res = false; int target = createWordNew(targetWord.length(),targetWord); int first = createWordNew(firstWord.length(),firstWord); int second = createWordNew(secondWord.length(),secondWord); if (target == (first + second)){ res = true; } return res; } public static int createWordNew(int lenOfWord,String word){ int res = 0; for (int i = 0; i< lenOfWord; i++){ res = (res * 10 + (word.charAt(i)%97)); } return res; } public static void main(String[] args) { System.out.println(isSumEqual("aaa","a","aaaa")); } }
package com.framework.aop.proxy; import java.lang.reflect.Method; import com.framework.aop.annotation.Aspect; import com.framework.aop.annotation.Bean; @Aspect(Bean.class) public class AspectProxyImpl extends AspectProxy { private void after(Class<?> cls, Method method, Object[] params, Object result) { System.out.println("ๆ‰ง่กŒ็ป“ๆŸ"); } private void before(Class<?> cls, Method method, Object[] params) { System.out.println("ๆ‰ง่กŒๅ‡†ๅค‡"); } private void begin() { } }
package org.project; public class BankInter implements FirstIn, I2 { private void eduLoan() { System.out.println("8%"); // TODO Auto-generated method stub } private void homeLoan() { System.out.println("9%"); // TODO Auto-generated method stub } public void saving() { System.out.println("10%"); // TODO Auto-generated method stub } @Override public void bank1() { System.out.println("bank1%"); // TODO Auto-generated method stub } @Override public void bank2() { System.out.println("bank2%"); // TODO Auto-generated method stub } @Override public void bank3() { System.out.println("bank3%"); // TODO Auto-generated method stub } public static void main(String[] args) { BankInter bi= new BankInter(); bi.eduLoan(); bi.homeLoan(); bi.bank1(); bi.bank2(); bi.bank3(); } }
package mathiasschoepke.pojo; import java.io.Serializable; import javax.persistence.Column; import javax.persistence.EmbeddedId; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.MapsId; import javax.persistence.Table; import lombok.Getter; import lombok.Setter; @Entity @Table(name = "rating") @Getter @Setter public class Rating implements Serializable { private static final long serialVersionUID = 1L; // ATTRIBUTES @EmbeddedId RatingKey id; @ManyToOne(fetch = FetchType.EAGER) @MapsId("employee_id") @JoinColumn(name = "employee_id") Employee employee; @ManyToOne(fetch = FetchType.EAGER) @MapsId("skill_id") @JoinColumn(name = "skill_id") Skill skill; @Column(name = "rating") private int rating; // ASSOCIATION // METHODS public Rating() { } public Rating(Employee employee, Skill skill, int rating) { id = new RatingKey(employee.getId(), skill.getId()); this.rating = rating; } @Override public String toString() { return "Rating[" + employee.getName() + ":" + skill.getName() + ":" + rating + "]"; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.net.imap; import static org.junit.jupiter.api.Assertions.assertAll; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertNull; import static org.junit.jupiter.api.Assertions.assertTrue; import java.util.stream.Stream; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.MethodSource; public class IMAPTest { private static Stream<String> mailboxNamesToBeQuoted() { return Stream.of( "", " ", "\"", "\"\"", "\\/ ", "Hello\", ", "\" World!", "Hello\",\" World!" ); } @Test public void checkGenerator() { // This test assumes: // - 26 letters in the generator alphabet // - the generator uses a fixed size tag final IMAP imap = new IMAP(); final String initial = imap.generateCommandID(); int expected = 1; for (int j = 0; j < initial.length(); j++) { expected *= 26; // letters in alphabet } int i = 0; boolean matched = false; while (i <= expected + 10) { // don't loop forever, but allow it to pass go! i++; final String s = imap.generateCommandID(); matched = initial.equals(s); if (matched) { // we've wrapped around completely break; } } assertEquals(expected, i); assertTrue(matched, "Expected to see the original value again"); } @Test public void constructDefaultIMAP() { final IMAP imap = new IMAP(); assertAll( () -> assertEquals(IMAP.DEFAULT_PORT, imap.getDefaultPort()), () -> assertEquals(IMAP.IMAPState.DISCONNECTED_STATE, imap.getState()), () -> assertEquals(0, imap.getReplyStrings().length) ); } @ParameterizedTest(name = "String `{0}` should be quoted") @MethodSource("mailboxNamesToBeQuoted") public void quoteMailboxName(final String input) { final String quotedMailboxName = IMAP.quoteMailboxName(input); assertAll( () -> assertTrue(quotedMailboxName.startsWith("\""), "quoted string should start with quotation mark"), () -> assertTrue(quotedMailboxName.endsWith("\""), "quoted string should end with quotation mark") ); } @Test public void quoteMailboxNameNullInput() { assertNull(IMAP.quoteMailboxName(null)); } @Test public void quoteMailboxNoQuotingIfNoSpacePresent() { final String stringToQuote = "Foobar\""; assertEquals(stringToQuote, IMAP.quoteMailboxName(stringToQuote)); } @Test public void trueChunkListener() { assertTrue(IMAP.TRUE_CHUNK_LISTENER.chunkReceived(new IMAP())); } }
import java.io.*; public class Driver { public static void main(String[] args) { header("Creating new PhoneWordLister"); PhonewordLister l = null; try{ l = new PhonewordLister(); } catch(IOException e) { yell(e); } catch(Exception e) { error("Wrong Exception:" + e); } header("Creating bad PhoneWordLister"); say("should be an IOException here"); PhonewordLister lb = null; try{ lb = new PhonewordLister("foo.txt"); } catch(IOException e) { yell(e); } catch(Exception e) { error("Wrong Exception:" + e); } header("Checking tree"); PrefixTree t = l.getTree(); say("Size should be 5757"); yell(t.getSize()); say("'today' should be true"); yell("today: " + t.contains("today")); say("'happy' should be true"); yell("happy: " + t.contains("happy")); say("'hippo' should be true"); yell("hippo: " + t.contains("hippo")); say("'lazed' should be true"); yell("lazed: " + t.contains("lazed")); say("'ab' should be true"); yell("ab: " + t.contains("ab")); say("'pinot' should be false"); yell("pinot: " + t.contains("pinot")); header("Testing phoneletter map"); char[] digits = new char[] {'2', '3', '4', '5', '6', '7', '8', '9', '*'}; for (char d : digits) { say(d); yell(PhonewordLister.phoneLetters(d).length); for (char p : PhonewordLister.phoneLetters(d)) { yell("\t" + p); } } header("Testing list method"); say("A non-5-character string should return an empty array"); yell(l.list("234").length); say("Invalid characters, likewise"); yell(l.list("3452a").length); say("22222 has only one valid word"); for (String s : l.list("22222")) yell(s); say("25*** should be a pretty big list"); for (String s : l.list("25***")) yell(s); say("26*29 apparently fails"); for (String s : l.list("26*29")) yell(s); header("Testing scrabbleword"); ScrabbleWord swa = new ScrabbleWord("jazzy", 33); ScrabbleWord swb = new ScrabbleWord("trees", 5); say("Testing getWord, shoud be 'jazzy'"); yell(swa.getWord()); say("Testing getScore, should be 33"); yell(swa.getScore()); say("Testing toString"); yell(swb); say("jazzy.compareTo(trees) should be <0"); yell(swa.compareTo(swb)); } //Covenience wrapper around System.out.println public static void say(Object statement) { System.out.println(statement); } //Like say, but green (using ANSI codes - not very portable, but good enough //for most non-Windows users. Maybe look into jansi or Jcurses? public static void yell(Object statement) { System.out.println((char)27 + "[32m" + statement + (char)27 + "[39m"); } //Like say, but red public static void error(Object statement) { System.out.println((char)27 + "[31m" + statement + (char)27 + "[39m"); } //Outputs a String "underlined" with ='s public static void header(Object statement) { say("\n" + statement); for (int i = 0; i < statement.toString().length(); i++) { System.out.print("="); } System.out.print("\n"); } }
package com.javarush.task.task18.task1808; import java.io.*; /* ะ ะฐะทะดะตะปะตะฝะธะต ั„ะฐะนะปะฐ */ public class Solution { public static void main(String[] args) { try(BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); FileInputStream in = new FileInputStream(reader.readLine()); FileOutputStream out1 = new FileOutputStream(reader.readLine()); FileOutputStream out2 = new FileOutputStream(reader.readLine())) { byte[] buff = new byte[in.available()]; if (in.available() > 0) { in.read(buff); } int separationIndex = (buff.length % 2 == 0) ? (buff.length / 2) : (int) (Math.floor(buff.length / 2d + 1 )); out1.write(buff, 0, separationIndex); out2.write(buff, separationIndex, buff.length - separationIndex); } catch (IOException e) { e.printStackTrace(); } } }
package ํด๋ž˜์Šค์ƒ์„ฑ; public class Car { // ์ „์—ญ๋ณ€์ˆ˜(global, ๊ธ€๋กœ๋ฒŒ ๋ณ€์ˆ˜) // ์„ฑ์งˆ -> ๋ณ€์ˆ˜๋กœ ๋งŒ๋“ ๋‹ค ๋ฉค๋ฒ„๋ณ€์ˆ˜ // ์ƒ‰(color), ๋ฐ”ํ€ด์ˆ˜(count) public String color; // ์ž๋™์ดˆ๊ธฐํ™” null public int count; // ์ž๋™์ดˆ๊ธฐํ™” 0 // ๋™์ž‘ -> ๋ฉค๋ฒ„๋ฉ”์„œ๋“œ public void run() { // ๋ฉ”์„œ๋“œ // ํ•จ์ˆ˜์˜ ๊ธฐ๋Šฅ์„ ์ •์˜ System.out.println("๋„ค๋ฐ”ํ€ด๋กœ ๋‹ฌ๋ฆฌ๊ธฐ"); } public void up() { System.out.println("์†๋„๋ฅผ 20์”ฉ ๋นจ๋ผ์ง„๋‹ค"); } }
package Initial; public class CapitalStrategyTermLoan extends CapitalStrategy { }
package com.sibilante.shortner.controller; import javax.ws.rs.Consumes; import javax.ws.rs.GET; import javax.ws.rs.NotFoundException; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; import javax.ws.rs.core.UriInfo; import org.springframework.beans.factory.annotation.Autowired; import com.sibilante.shortner.service.ShortnerService; @Path("shorts") public class ShortnerResource { @Context UriInfo uriInfo; @Autowired ShortnerService shortnerService; @POST @Consumes(MediaType.TEXT_PLAIN) @Produces(MediaType.TEXT_PLAIN) public String post(String url) { return UriBuilder.fromUri(uriInfo.getAbsolutePath()) .path("{shortnedUrl}") .build(shortnerService.urlShorter(url)) .toString(); } @GET @Produces(MediaType.TEXT_PLAIN) @Path("/{shortnedUrl}") public Response get(@PathParam("shortnedUrl") String shortnedUrl) { String result = shortnerService.getOriginalLink(shortnedUrl); if (result == null) { throw new NotFoundException("URL not found"); } return Response.seeOther(UriBuilder.fromPath(result).build()).build(); } }
package com.coda.visitors; public class VisitorModel2 { private Integer visitorId; private String inTime; private String outTime; private String visitorName; private String companyName; private String phoneNum; private String personToContact; private String currentdate; public Integer getVisitorId() { return visitorId; } public void setVisitorId(Integer visitorId) { this.visitorId = visitorId; } public String getInTime(String timeValue) { return inTime; } public void setInTime(String inTime) { this.inTime = inTime; } public String getOutTime(String timeValue) { return outTime; } public void setOutTime(String outTime) { this.outTime = outTime; } public String getVisitorName() { return visitorName; } public void setName(String name) { visitorName = name; } public String getCompanyName() { return companyName; } public void setCompanyName(String companyName) { this.companyName = companyName; } public String getPhoneNum() { return phoneNum; } public void setPhoneNum(String phoneNum) { this.phoneNum = phoneNum; } public String getPersonToContact() { return personToContact; } public void setPersonToContact(String personToContact) { this.personToContact = personToContact; } public String getCurrentdate(String dateValue) { return currentdate; } public void setCurrentdate(String currentdate) { this.currentdate = currentdate; } }
/* * 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 data.core.ui; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.pdf.PdfWriter; import com.itextpdf.tool.xml.XMLWorkerHelper; import data.Constants; import data.PackageFunctions; import data.core.api.ApiFile; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.swing.JFileChooser; import javax.swing.filechooser.FileNameExtensionFilter; /** * * @author Ryno Laptop */ public class UiFileChooser extends PackageFunctions{ //-------------------------------------------------------------------------- //properties //-------------------------------------------------------------------------- private String filename; private File template; private String html; private String defaultDirectory; private JFileChooser saveFile; //-------------------------------------------------------------------------- //constructor //-------------------------------------------------------------------------- public UiFileChooser(File template){ this.template = template; this.filename = ApiFile.getRandomFilename("pdf", Constants.DIR_DOCUMENTS+"/export_"); this.defaultDirectory = Constants.DIR_DOCUMENTS; this.saveFile = new JFileChooser(); } //-------------------------------------------------------------------------- public UiFileChooser(File template, String filename){ this.template = template; this.filename = filename; this.defaultDirectory = Constants.DIR_DOCUMENTS; this.saveFile = new JFileChooser(); } //-------------------------------------------------------------------------- public UiFileChooser(File template, String filename, String defaultDirectory){ this.template = template; this.filename = filename; this.defaultDirectory = defaultDirectory; this.saveFile = new JFileChooser(); } //-------------------------------------------------------------------------- public UiFileChooser(String html){ this.html = html; this.filename = ApiFile.getRandomFilename("pdf", Constants.DIR_DOCUMENTS+"/export_"); this.defaultDirectory = Constants.DIR_DOCUMENTS; this.saveFile = new JFileChooser(); } //-------------------------------------------------------------------------- public UiFileChooser(String html, String filename){ this.html = html; this.filename = filename; this.defaultDirectory = Constants.DIR_DOCUMENTS; this.saveFile = new JFileChooser(); } //-------------------------------------------------------------------------- public UiFileChooser(String html, String filename, String defaultDirectory){ this.html = html; this.filename = filename; this.defaultDirectory = defaultDirectory; this.saveFile = new JFileChooser(); } //-------------------------------------------------------------------------- public void validateProperties(){ if(this.template == null && this.html == null){ System.err.println("No html or file template found"); } } //-------------------------------------------------------------------------- public void setFileChooser(JFileChooser saveFile){ this.saveFile = saveFile; } //-------------------------------------------------------------------------- public JFileChooser getFileChooser(){ return this.saveFile; } //-------------------------------------------------------------------------- public void renderSaveComponent(){ this.validateProperties(); File file = new File(this.filename); this.saveFile.setSelectedFile(file); this.saveFile.setFileFilter(new FileNameExtensionFilter("pdf file","pdf")); if (this.saveFile.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) { String selectedDir = this.saveFile.getCurrentDirectory().toString(); try { try (OutputStream fileStream = new FileOutputStream(new File(selectedDir+"/"+saveFile.getSelectedFile().getName()))) { Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, fileStream); document.open(); if(this.template != null){ XMLWorkerHelper.getInstance().parseXHtml(writer, document, new FileInputStream(this.template)); }else if(this.html != null){ InputStream is = new ByteArrayInputStream(this.html.getBytes()); XMLWorkerHelper.getInstance().parseXHtml(writer, document, is); }else{ System.err.println("No html or file template found in render component"); } document.close(); this.saveFile.setSelectedFile(file); this.saveFile.setCurrentDirectory(file); } } catch (IOException | DocumentException e) { } } } //-------------------------------------------------------------------------- }
import java.util.LinkedHashMap; import java.util.Map; public class mostrepeatedchar { public static void main(String[] args) { String s="civicisclcmc"; char[] ch = s.toCharArray(); Map<Character,Integer> lhm = new LinkedHashMap<>(); for(char c:ch) { if(lhm.containsKey(c)) { lhm.put(c,lhm.get(c)+1); } else { lhm.put(c,1); } } Character ky=' '; Integer i=0; for(Map.Entry<Character,Integer> me:lhm.entrySet()) { if(me.getValue()>i) { ky=me.getKey(); i=me.getValue(); } } System.out.println(ky+"-"+i); } }
package com.shopify.shop; import java.io.Serializable; import java.util.Date; import lombok.Data; @Data public class ShopData implements Serializable { private static final long serialVersionUID = -7690410338487183976L; /** * */ private int shopIdx; private String email; private String id; private String shop; private String shopId; private String shopName; private String appName; private String ecommerce; private String accessToken; private String access_token; private String accessKey; private String scope; private String expiresIn; private String combineYn; private String accountOwner; private String locale; private String domain; private String collaborator; private String useYn; private String activeYn; //YR ์ถ”๊ฐ€ 2020.05.15 private String billingYn; //YR ์ถ”๊ฐ€ 2020.05.15 private String delYn; private String regDate; private String privatechk; private String publicchk; private String eventchk; private String chk_date; private String buyerCountryCode; private int shopCount; private int startRow; private int rowPerPage; private int lastPage; private String encryptKey; private int rankRate; private String rankId; //์ฃผ๋ฌธ๋ณ„ domain์ฒ˜๋ฆฌ ๊ด€๋ จ param private String masterCode; private String[] masterCodeList; private String orderCode; private String orderIdx; private String trackingNo; private String courier; }
package de.jmda.core.mproc.task; import static de.jmda.core.mproc.ProcessingUtilities.asTypeElement; import static de.jmda.core.mproc.ProcessingUtilities.getRootElements; import static de.jmda.core.mproc.ProcessingUtilities.normalizeBinaryClassName; import static de.jmda.core.util.CollectionsUtil.asSet; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.Set; import javax.lang.model.element.Element; import javax.lang.model.element.TypeElement; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.Test; import de.jmda.core.mproc.ProcessingUtilities; import de.jmda.core.util.Properties; import de.jmda.core.util.fileset.FileFilterJavaSourceFilesOnly; import de.jmda.core.util.fileset.FileSetBuilder.RuleSetUpdateMode; /** * Tests basic functionality of {@link AbstractTypeElementsTaskTypes}. * * @author ruu@jmda.de */ public class JUTTypeElementsTaskTypes { private final static Logger LOGGER = LogManager.getLogger(JUTTypeElementsTaskTypes.class); private final static String DIR_SRC_ROOT_KEY = JUTTypeElementsTaskTypes.class.getName() + ".DIR_SRC_ROOT"; private final static String DIR_SRC_ROOT_DEFAULT = "src/test/java"; private final static String DIR_SRC_ROOT = Properties.get(DIR_SRC_ROOT_KEY, DIR_SRC_ROOT_DEFAULT); /** * Test implementation of {@link AbstractTypeElementsTaskTypes}, collects * qualifiedNames of all type elements available via {@link * #getTypeElements()} and {@link ProcessingUtilities#getRootElements()}. */ private class TypeElementsTaskTypes extends AbstractTypeElementsTaskTypes { private List<String> qualifiedNamesTypeElements = new ArrayList<>(); private List<String> qualifiedNamesRootTypeElements = new ArrayList<>(); public TypeElementsTaskTypes(Set<? extends Class<?>> types) { super(types); } @Override public boolean execute() throws TaskException { for (TypeElement type : getTypeElements()) { qualifiedNamesTypeElements.add(type.getQualifiedName().toString()); } for (Element element : getRootElements()) { TypeElement typeElement = asTypeElement(element); if (typeElement != null) { qualifiedNamesRootTypeElements.add(typeElement.getQualifiedName().toString()); } } return false; } } /** * Tests {@link AbstractTypeElementsTaskTypes} with a type only available as a * .class byte code file in a .jar file in the classpath. * * @throws IOException */ @Test public void isTopLevelTypeFromJarInTypeElements() throws IOException { TypeElementsTaskTypes task = new TypeElementsTaskTypes(asSet(String.class)); TaskRunner.run(task); assertTrue( "missing top level type from jar", task.qualifiedNamesTypeElements.get(0).equals(String.class.getName())); assertEquals( "wrong number of top level types from jar", 1, task.qualifiedNamesTypeElements.size()); } /** * Tests {@link AbstractTypeElementsTaskTypes} with a top level type only * available as a .class byte code file in the classpath. * * @throws IOException */ @Test public void isTopLevelTypeFromRuntimeInTypeElements() throws IOException { TypeElementsTaskTypes task = new TypeElementsTaskTypes(asSet(JUTTypeElementsTaskTypes.class)); TaskRunner.run(task); assertTrue( "missing top level type from runtime", task.qualifiedNamesTypeElements.get(0).equals( JUTTypeElementsTaskTypes.class.getName())); assertEquals( "wrong number of top level types from runtime", 1, task.qualifiedNamesTypeElements.size()); } /** * Tests {@link AbstractTypeElementsTaskTypes} with an inner type only * available as a .class byte code file in the classpath. * * @throws IOException */ @Test public void isInnerLevelTypeFromRuntimeInTypeElements() throws IOException { TypeElementsTaskTypes task = new TypeElementsTaskTypes(asSet(TypeElementsTaskTypes.class)); TaskRunner.run(task); assertTrue( "missing inner type from runtime", task.qualifiedNamesTypeElements.get(0).equals( normalizeBinaryClassName(TypeElementsTaskTypes.class))); assertEquals( "wrong number of inner level types from runtime", 1, task.qualifiedNamesTypeElements.size()); } @Test public void testRootElements() throws IOException { TypeElementsTaskTypes task = new TypeElementsTaskTypes(asSet(TypeElementsTaskTypes.class)); task .getCustomJavaSourceFileSetBuilder() .includeDirectoryRecursive(new File(DIR_SRC_ROOT), FileFilterJavaSourceFilesOnly.INSTANCE, RuleSetUpdateMode.ADD_RULE); TaskRunner.run(task); for (String rootTypeName : task.qualifiedNamesRootTypeElements) { LOGGER.debug("root type name: " + rootTypeName); } assertTrue( "too few root type elements " + task.qualifiedNamesRootTypeElements.size(), task.qualifiedNamesRootTypeElements.size() > 1); } }
package com.allen.lightstreamdemo.base; import android.app.Activity; import com.allen.lightstreamdemo.ILightStreamerClientProxy; import com.allen.lightstreamdemo.LightStreamApplication; import com.lightstreamer.client.Subscription; import com.orhanobut.logger.Logger; /** * Created by: allen on 16/8/30. */ public class SubscriptionFragment { private static final String TAG = "SubscriptionFragment"; private Subscription mSubscription; private ILightStreamerClientProxy lsClient; private boolean subscribed = false; private boolean running = false; public synchronized void setSubscription(Subscription subscription) { if (this.mSubscription != null && subscribed) { Logger.d("Replacing subscription"); this.lsClient.removeSubscription(this.mSubscription); } Logger.d( "New Subscription" + subscription); this.mSubscription = subscription; if (running) { this.lsClient.addSubscription(this.mSubscription); } } public synchronized void onResume() { if (this.lsClient != null && this.mSubscription != null) { this.lsClient.addSubscription(this.mSubscription); subscribed = true; } running = true; } public synchronized void onPause() { if (this.lsClient != null && this.mSubscription != null) { this.lsClient.removeSubscription(this.mSubscription); subscribed = false; } running = false; } public synchronized void onAttach(Activity activity) { lsClient = LightStreamApplication.sClientProxy; } }
import javafx.application.Application; import javafx.scene.Scene; import javafx.stage.Stage; public class Main extends Application { private Scene myScene; public static void main(String[] args) { // TODO Auto-generated constructor stub launch(args); } @Override public void start(Stage primaryStage){ // TODO Auto-generated method stub UserInterface newInterface=new UserInterface(); myScene=newInterface.setScene(); primaryStage.setScene(myScene); primaryStage.show(); } }
package com.qunchuang.carmall.repository; import com.qunchuang.carmall.domain.CarInfo; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; /** * @author Curtain * @date 2019/1/15 14:10 */ @Repository public interface CarInfoRepository extends JpaRepository<CarInfo,String>{ boolean existsByModel(String model); CarInfo findByModel(String model); }
package com.zhao.leetcode; import java.util.HashSet; public class CycleList { public class ListNode { int val; ListNode next; ListNode() {} ListNode(int val) { this.val = val; } } //CycleList 141 public boolean hasCycle(ListNode head) { HashSet<ListNode> set = new HashSet<>(); ListNode p =head; while (p!=null){ if (set.contains(p)){ return true; }else { set.add(p); } p=p.next; } return false; } // 022 public ListNode detectCycle(ListNode head) { HashSet<ListNode> set = new HashSet<>(); ListNode p =head; while (p!=null){ if (set.contains(p)){ return p; }else { set.add(p); } p=p.next; } return null; } }
package reprographicsinventorymanager.ScreenControllers; public class LowAndOutOfStockScreen { }
package com.example.harry.cymbyl_3; import android.app.AlarmManager; import android.app.PendingIntent; import android.content.Intent; import android.support.v7.app.AppCompatActivity; 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.example.harry.cymbyl_3.Objects.Notification_reciever; import java.io.BufferedReader; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.Random; public class NotificationActivity extends AppCompatActivity { private static final String FILE_NAME = "script.txt"; private ArrayList<Integer> feq; private String mMessage; TextView display; EditText input; Button enter, reset; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_notification); feq = new ArrayList<Integer>(); mMessage = "ERROR"; display = findViewById(R.id.mantra_display); input = findViewById(R.id.mantra_input); enter = findViewById(R.id.enter); reset = findViewById(R.id.Edit); reset.setVisibility(View.INVISIBLE); load(); enter.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String temp = input.getText().toString(); if(temp.equals(mMessage)){ if(feq.get(0)>0) { save(feq); } display.setText("Congrats! You've solved the puzzle! "); enter.setVisibility(View.INVISIBLE); reset.setVisibility(View.VISIBLE); } else{ input.setError("Uh-oh! Incorrect Mantra!"); input.requestFocus(); } } }); reset.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startMain(); } }); display.setText(shuffle(mMessage)); } private void startMain(){ Intent intent = new Intent(this, MainActivity.class); startActivity(intent); } public void load(){ FileInputStream fis = null; try { fis = openFileInput(FILE_NAME); InputStreamReader isr = new InputStreamReader(fis); BufferedReader br = new BufferedReader(isr); String txt; int count = 0; while((txt = br.readLine())!=null && count < 8){ feq.add(Integer.valueOf(txt)); count++; } mMessage = txt; } catch (FileNotFoundException e) { e.printStackTrace(); Toast.makeText(this, "file not found", Toast.LENGTH_SHORT).show(); } catch (IOException e) { e.printStackTrace(); Toast.makeText(this, "reading error", Toast.LENGTH_SHORT).show(); }finally { if(fis!=null){ try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } } public String shuffle(String str){ if(str == null){ return "ERROR"; } ArrayList<String> words = new ArrayList<>(); while(str.indexOf(' ') != -1){ int x = str.indexOf(' '); String word = str.substring(0, x+1); str = str.substring(x+1); words.add(word); } words.add(str+" "); str = ""; Random rn = new Random(); while(!words.isEmpty()){ int x = Math.abs(rn.nextInt() % words.size()); str = str + words.remove(x); } return str; } public void save(ArrayList<Integer> feq) { feq = changeNextTime(feq); FileOutputStream fos = null; try { fos = openFileOutput(FILE_NAME, MODE_PRIVATE); for(int i = 0; i<8; i++){ fos.write((Integer.toString(feq.get(i))+"\n").getBytes()); } fos.write(mMessage.getBytes()); } catch (FileNotFoundException e) { e.printStackTrace(); Toast.makeText(this,"0",Toast.LENGTH_SHORT).show(); } catch (IOException e) { e.printStackTrace(); Toast.makeText(this,"1",Toast.LENGTH_SHORT).show(); }finally { if(fos!=null){ try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } } public static int[] getCurrentTime() { Date date = new Date(); String strDateFormat = "hh:mm:ss a"; DateFormat dateFormat = new SimpleDateFormat(strDateFormat); String formattedDate= dateFormat.format(date); int[] currentTime = {Integer.valueOf(formattedDate.substring(0,2)), Integer.valueOf(formattedDate.substring(3,5))}; return currentTime; } public ArrayList<Integer> changeNextTime(ArrayList<Integer> feq){ int[] currentTime = getCurrentTime(); int temp = feq.get(1)+currentTime[1]; if(temp >60){ temp = temp % 60; feq.set(6, (currentTime[0]+1)%24); } feq.set(7,temp); if(feq.get(6)>feq.get(4) && feq.get(7)>feq.get(5)){ feq.set(6, feq.get(2)); feq.set(7, feq.get(3)); } feq.set(0,feq.get(0)-1); Calendar nextAlarm = Calendar.getInstance(); nextAlarm.set(Calendar.HOUR_OF_DAY, feq.get(6)); nextAlarm.set(Calendar.MINUTE, feq.get(7)); Intent intent = new Intent(getApplicationContext(), Notification_reciever.class); PendingIntent PI = PendingIntent.getBroadcast(getApplicationContext(),100, intent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager am = (AlarmManager)getSystemService(ALARM_SERVICE); am.set(AlarmManager.RTC_WAKEUP, nextAlarm.getTimeInMillis(), PI); return feq; } }
package com.skilldistillery.gameabstractions; import com.skilldistillery.cards.Card; import com.skilldistillery.cards.Deck; public abstract class Dealer { protected Deck gameDeck; protected String name; protected Hand hand; public Dealer() { name = "Kylo Ren"; gameDeck = new Deck(); } public Dealer(Deck gameDeck) { this.gameDeck = gameDeck; name = "Kylo Ren"; } public Dealer(Deck gameDeck, String name) { this.gameDeck = gameDeck; this.name = name; } public Card dealCard() { Card toReturn = gameDeck.dealCard(); if(toReturn == null) { System.out.println("Dealer " + name + ": I apologize, we're out of cards."); } return toReturn; } public void shuffle() { gameDeck.shuffle(); } }
package com.doomcrow.toadgod.systems; public class DamagedCooldownUpdatingSystem { }
package com.chan.demo.vo; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import lombok.Getter; import lombok.Setter; @Getter @Setter @JsonIgnoreProperties(ignoreUnknown = true) public class chattingVO { private String ch_code; private String ch_name; private String ch_mmcode1; private String ch_mmcode2; private int ch_postnum; public chattingVO(String ch_code, String ch_name, String ch_mmcode1, String ch_mmcode2, int ch_postnum){ super(); this.ch_code = ch_code; this.ch_name = ch_name; this.ch_mmcode1 = ch_mmcode1; this.ch_mmcode2 = ch_mmcode2; this.ch_postnum = ch_postnum; } }
package jpa.project.controller; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import jpa.project.config.security.JwtTokenProvider; import jpa.project.model.dto.member.MemberLoginRequestDto; import jpa.project.model.dto.member.MemberLoginResponseDto; import jpa.project.model.dto.member.MemberRegisterRequestDto; import jpa.project.model.dto.member.MemberRegisterResponseDto; import jpa.project.repository.member.MemberRepository; import jpa.project.response.CommonResult; import jpa.project.response.SingleResult; import jpa.project.service.KakaoService; import jpa.project.service.ResponseService; import jpa.project.service.SignService; import lombok.RequiredArgsConstructor; import org.springframework.web.bind.annotation.*; @Api(tags={"2.Sign"}) @RestController @RequiredArgsConstructor public class SignApiController { private final SignService signService; private final JwtTokenProvider jwtTokenProvider; private final ResponseService responseService; private final KakaoService kakaoService; private final MemberRepository memberRepository; @ApiOperation(value = "๋กœ๊ทธ์ธ",notes = "์•„์ด๋””,๋น„๋ฐ€๋ฒˆํ˜ธ๋กœ ํšŒ์› ๋กœ๊ทธ์ธ์„ ํ•œ๋‹ค") @PostMapping(value = "/signin") public SingleResult<MemberLoginResponseDto> signin(@ModelAttribute MemberLoginRequestDto memberLoginRequestDto) { return responseService.getSingResult(signService.signin(memberLoginRequestDto)); } @ApiOperation(value = "๊ฐ€์ž…",notes = "ํšŒ์›๊ฐ€์ž…") @PostMapping(value = "/signup") public CommonResult signup(@ModelAttribute MemberRegisterRequestDto memberRegisterRequestDto ){ signService.signup(memberRegisterRequestDto); return responseService.getSuccessResult(); } @ApiOperation(value = "์†Œ์…œ ๋กœ๊ทธ์ธ", notes = "์†Œ์…œ ํšŒ์› ๋กœ๊ทธ์ธ์„ ํ•œ๋‹ค.") @PostMapping(value = "/signin/{provider}") public SingleResult<MemberLoginResponseDto> signinByProvider( @ApiParam(value = "์„œ๋น„์Šค ์ œ๊ณต์ž provider", required = true, defaultValue = "kakao") @PathVariable String provider, @ApiParam(value = "์†Œ์…œ access_token", required = true) @RequestParam String accessToken) { return responseService.getSingResult(signService.socialLogin(accessToken,provider)); } @ApiOperation(value = "์†Œ์…œ ๊ณ„์ • ๊ฐ€์ž…", notes = "์†Œ์…œ ๊ณ„์ • ํšŒ์›๊ฐ€์ž…์„ ํ•œ๋‹ค.") @PostMapping(value = "/signup/{provider}") public SingleResult<MemberRegisterResponseDto> signupProvider(@ApiParam(value = "์„œ๋น„์Šค ์ œ๊ณต์ž provider", required = true, defaultValue = "kakao") @PathVariable String provider, @ApiParam(value = "์†Œ์…œ access_token", required = true) @RequestParam String accessToken, @ApiParam(value = "์ด๋ฆ„", required = true) @RequestParam String name) { return responseService.getSingResult( signService.socialSignup(accessToken,provider,name)); } @ApiOperation(value = "๋กœ๊ทธ์•„์›ƒ", notes = "๋กœ๊ทธ์•„์›ƒ์„ ํ•œ๋‹ค") @PostMapping(value = "/logout") public CommonResult logout(@RequestHeader(value="X-AUTH-TOKEN") String token) { signService.logoutMember(token); return responseService.getSuccessResult(); } }
package Exception; public class DanceClass { public static void main(String[] args) { java.util.Scanner input = new java.util.Scanner(System.in); System.out.print("Enter number of male dancer: "); int men = input.nextInt(); System.out.print("Enter number of female dancer: "); int women = input.nextInt(); if(men == 0 && women == 0) { System.out.println("Class is cancelled. No students"); System.exit(0); } else if(men == 0) { System.out.println("Class is cancelled. No men"); System.exit(0); } else if(women == 0) { System.out.println("Class is cancelled. No women"); } if(women >= men) System.out.println("each man must dance with women. "); else System.out.println("Each woman must dance with " + men/(double) women + " men."); System.out.println("Begin the lesson."); } }