text
stringlengths 10
2.72M
|
|---|
package com.awesome.galleryapp;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private ArrayList<GalleryStore> mGallery;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//custom data
initAppData();
//initialize ui
initUi();
}
private void initUi(){
Toolbar actionBar = (Toolbar) findViewById(R.id.actionBar);
setSupportActionBar(actionBar);
getSupportActionBar().setDisplayShowTitleEnabled(false);
// Change status bar color
if(Build.VERSION.SDK_INT >=21)
getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
RecyclerView profileAdapter = (RecyclerView) findViewById(R.id.recyclerView);
RecyclerViewAdapter recyclerViewAdapter = new RecyclerViewAdapter(MainActivity.this, mGallery);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(MainActivity.this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
profileAdapter.setLayoutManager(linearLayoutManager);
profileAdapter.setNestedScrollingEnabled(false);
profileAdapter.setAdapter(recyclerViewAdapter);
}
private void initAppData(){
mGallery = new ArrayList<GalleryStore>();
ArrayList<Integer> mImages = new ArrayList<>(3);
mImages.add(new Integer(R.drawable.download));
mImages.add(new Integer(R.drawable.profile));
mImages.add(new Integer(R.drawable.jdpp));
mGallery.add(new GalleryStore("Landscape",2354,mImages));
mGallery.add(new GalleryStore("People",2354,mImages));
mGallery.add(new GalleryStore("Landscape",2344,mImages));
mGallery.add(new GalleryStore("People",2354,mImages));
mGallery.add(new GalleryStore("Landscape",2354,mImages));
mGallery.add(new GalleryStore("Landscape",2354,mImages));
mGallery.add(new GalleryStore("Landscape",2354,mImages));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
}
|
package com.sda.project.model;
public enum ItemState {
NEW, ACTIVE, RESOLVED, CLOSED;
}
|
package com.nxtlife.mgs.view;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.nxtlife.mgs.ex.ValidationException;
public class Request {
public int countWords(String sentence) {
if (sentence == null || sentence.isEmpty()) {
return 0;
}
String[] words = sentence.split("\\s+");
return words.length;
}
public boolean isValidMobileNumber(String s)
{
// The given argument to compile("(0/91)?[7-9][0-9]{9}") method
// is regular expression. With the help of
// regular expression we can validate mobile
// number.
// 1) Begins with 0 or 91
// 2) Then contains 7 or 8 or 9.
// 3) Then contains 9 digits
Pattern p = Pattern.compile("[7-9][0-9]{9}");
// Pattern class contains matcher() method
// to find matching between given number
// and regular expression
Matcher m = p.matcher(s);
return (m.find() && m.group().equals(s));
}
// Function to check String for only Alphabets
public boolean isStringOnlyAlphabet(String str)
{
return ((str != null)
&& (!str.equals(""))
&& (str.matches("^[a-zA-z]+([\\s][a-zA-Z]+)*$")));
// /^[a-zA-Z ]*$/
}
public boolean emailValidator(String email) {
String emailRegex = "^[a-zA-Z0-9_+&*-]+(?:\\."+
"[a-zA-Z0-9_+&*-]+)*@" +
"(?:[a-zA-Z0-9-]+\\.)+[a-z" +
"A-Z]{2,7}$";
Pattern pat = Pattern.compile(emailRegex);
if (email == null)
return false;
return pat.matcher(email).matches();
}
public void validateMobileNumber(String mobile) {
if(!isValidMobileNumber(mobile))
throw new ValidationException(String.format("Mobile number (%s) is in invalid format, it should be a numeric string with 10 characters only.", mobile));
}
public void validateEmail(String email) {
if(!emailValidator(email))
throw new ValidationException(String.format("Email (%s) is in invalid format.", email));
}
}
|
package com.example.nata.hallimane;
import android.app.Dialog;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.app.Fragment;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static com.example.nata.hallimane.UrlClass.BedType_url;
import static com.example.nata.hallimane.UrlClass.final_booking_url;
import static com.example.nata.hallimane.UrlClass.selected_url;
public class BookFragment extends Fragment {
static final String TAG_TYPE = "type";
static final String TAG_CIN = "cin";
static final String TAG_COUT = "cout";
static final String TAG_ROOMS = "rooms";
static final String TAG_GUESTS = "guests";
static final String TAG_RESULT = "selected";
private Dialog loadingDialog;
static String Retype="",Recin="",Recout="",Rerooms="",Reguests="",ReMail="";
public ListView mainListView;
JSONArray matchFixture = null;
ArrayList<HashMap<String, String>> matchFixtureList = new ArrayList<HashMap<String, String>>();
Spinner BedType;
Button BOOK;
String bEdType="";
Button Book;
GMailSender sender;
private ArrayList<Category> bedTypeArray;
public BookFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_book, container, false);
Book =(Button)view.findViewById(R.id.book);
mainListView =(ListView)view.findViewById(R.id.SelectedList) ;
BedType =(Spinner)view.findViewById(R.id.BookRoomspin);
BOOK =(Button)view.findViewById(R.id.book);
sender =new GMailSender("botsattendance@gmail.com", "natraj31195");
//Obtaining Values from other classes
Retype = RoomAvailabilityFragment.sendType();
Recin =RoomAvailabilityFragment.sendCin();
Recout =RoomAvailabilityFragment.sendCout();
Rerooms = RoomAvailabilityFragment.sendRooms();
Reguests =RoomAvailabilityFragment.sendGuests();
ReMail =RoomAvailabilityFragment.sendMail();
//Toast.makeText(BookFragment.this.getActivity(),Retype+" "+Recin+" "+Recout+" "+Rerooms+" "+Reguests+" "+ReMail+"Hahaha",Toast.LENGTH_SHORT).show();
//End
//To Obtain Selected entries
new GetSelected().execute(Retype,Recin,Recout,Rerooms,Reguests,ReMail);
//End
//Spinner call from Php
bedTypeArray =new ArrayList<Category>();
new GetBedType().execute();
Book.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
bEdType = BedType.getSelectedItem().toString();
if (!bEdType.equals("Select Bed Type")) {
finalBooking(Retype, Recin, Recout, Rerooms, Reguests, ReMail, bEdType);
} else {
Toast.makeText(BookFragment.this.getActivity(), "Please Select Bed Type", Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
/**
* Adding spinner data
*/
private void populateSpinner() {
List<String> lablestype = new ArrayList<String>();
for (int i = 0; i < bedTypeArray.size(); i++) {
lablestype.add(bedTypeArray.get(i).getName());
//Toast.makeText(RoomAvailability.this,"ondu",Toast.LENGTH_SHORT).show();
}
// Creating adapter for spinner
ArrayAdapter<String> spinnerAdaptertype = new ArrayAdapter<String>(BookFragment.this.getActivity(),
android.R.layout.simple_spinner_item, lablestype);
// Drop down layout style - list view with radio button
spinnerAdaptertype.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapter to spinner
BedType.setAdapter(spinnerAdaptertype);
}
public void finalBooking(final String Retype, String Recin, String Recout, final String Rerooms, String Reguests, final String ReMail, String rebedtype) {
class FBookin extends AsyncTask<String, Void, String> {
AlertDialog alertDialog;
private Dialog loadingDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(BookFragment.this.getActivity(), "Room Booking", "Good things takes time...");
alertDialog = new AlertDialog.Builder(BookFragment.this.getActivity()).create();
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
alertDialog.setTitle("Booking");
loadingDialog.dismiss();
if (result.equals("success")) {
Toast.makeText(BookFragment.this.getActivity(), "Room Successfully booked", Toast.LENGTH_SHORT).show();
/*RoomBookedFragment roomBookedFragment = new RoomBookedFragment();
FragmentManager manager = getFragmentManager();
manager.beginTransaction().replace(R.id.content_doddudu,
roomBookedFragment,
roomBookedFragment.getTag()).commit();*/
startActivity(new Intent(BookFragment.this.getActivity(), Doddudu.class));
} else {
alertDialog.setMessage(result);
alertDialog.setCanceledOnTouchOutside(true);
alertDialog.setIcon(android.R.drawable.ic_dialog_alert);
alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, "Okay", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
alertDialog.show();
}
}
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
protected String doInBackground(String... params) {
String retype = params[0];
String recin = params[1];
String recout = params[2];
String rerooms = params[3];
String reguests = params[4];
String remail = params[5];
String rebedtyp = params[6];
try {
URL url = new URL(final_booking_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String Room_Availability_data = URLEncoder.encode("email", "UTF-8") + "=" + URLEncoder.encode(remail, "UTF-8") + "&" +
URLEncoder.encode("type", "UTF-8") + "=" + URLEncoder.encode(retype, "UTF-8") + "&" +
URLEncoder.encode("from", "UTF-8") + "=" + URLEncoder.encode(recin, "UTF-8") + "&" +
URLEncoder.encode("to", "UTF-8") + "=" + URLEncoder.encode(recout, "UTF-8") + "&" +
URLEncoder.encode("room", "UTF-8") + "=" + URLEncoder.encode(rerooms, "UTF-8") + "&" +
URLEncoder.encode("person", "UTF-8") + "=" + URLEncoder.encode(reguests, "UTF-8") + "&" +
URLEncoder.encode("bedtype", "UTF-8") + "=" + URLEncoder.encode(rebedtyp, "UTF-8");
bufferedWriter.write(Room_Availability_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String response = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
response = line;
}
inputStream.close();
bufferedReader.close();
// Add subject, Body, your mail Id, and receiver mail Id.
String code="Hi!"+System.lineSeparator()+"Your request for "+Rerooms+ " "+Retype+ " room(s) from "
+recin+" to "+ recout+" has been alloted for "+ reguests+ " guest(s)"+System.lineSeparator()+
"For more information ContactUs at reachus@hallimane.com or www.hallimane.com";
sender.sendMail("Room Confirmation",code, "botsattendance@gmail.com",ReMail);
//long lalle = 0 ;
return response;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
catch (Exception ex) {
}
return null;
}
}
FBookin fBookin = new FBookin();
fBookin.execute(Retype, Recin, Recout, Rerooms, Reguests, ReMail, rebedtype);
}
/*
* Get previously selected items using methods from other class and php json code
* */
private class GetSelected extends AsyncTask<String ,Void,String>{
private Dialog dialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
dialog = ProgressDialog.show(BookFragment.this.getActivity(),"Please Wait","Fetching Data...");
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(
BookFragment.this.getActivity(), matchFixtureList,
R.layout.list_selected_book, new String[] {
TAG_TYPE, TAG_CIN,TAG_COUT,TAG_ROOMS,TAG_GUESTS
}
, new int[] {
R.id.selectedType,R.id.selectedCin,
R.id.selectedCout,R.id.selectedRooms,R.id.selectedGuests
}
);
mainListView.setAdapter(adapter);
dialog.dismiss();
}
@Override
protected String doInBackground(String... params) {
String retype = params[0];
String recin = params[1];
String recout = params[2];
String rerooms = params[3];
String reguests = params[4];
String remail = params[5];
// Preparing post params
List<NameValuePair> SelectedItems = new ArrayList<NameValuePair>();
SelectedItems.add(new BasicNameValuePair("type", retype));
SelectedItems.add(new BasicNameValuePair("cin", recin));
SelectedItems.add(new BasicNameValuePair("cout", recout));
SelectedItems.add(new BasicNameValuePair("rooms", rerooms));
SelectedItems.add(new BasicNameValuePair("guests", reguests));
SelectedItems.add(new BasicNameValuePair("email", remail));
ServiceHandler serviceClient = new ServiceHandler();
String json = serviceClient.makeServiceCall(selected_url,
ServiceHandler.POST, SelectedItems);
if (json != null) {
try {
Log.d("try", "in the try");
JSONObject jsonObj = new JSONObject(json);
Log.d("jsonObject", "new json Object");
// Getting JSON Array node
matchFixture = jsonObj.getJSONArray(TAG_RESULT);
Log.d("json aray", "user point array");
int len = matchFixture.length();
Log.d("len", "get array length");
for (int i = 0; i < matchFixture.length(); i++) {
JSONObject c = matchFixture.getJSONObject(i);
String type = c.getString(TAG_TYPE);
type = type.toUpperCase();
String cin = c.getString(TAG_CIN);
String cout = c.getString(TAG_COUT);
String rooms = c.getString(TAG_ROOMS);
String guests = c.getString(TAG_GUESTS);
HashMap<String, String> matchFixture = new HashMap<String, String>();
matchFixture.put(TAG_TYPE, type);
matchFixture.put(TAG_CIN, cin);
matchFixture.put(TAG_COUT, cout);
matchFixture.put(TAG_ROOMS,rooms);
matchFixture.put(TAG_GUESTS,guests);
matchFixtureList.add(matchFixture);
}
}
catch (JSONException e) {
Log.d("catch", "in the catch");
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
}
/*
* Get Bed Type using php json
*
* */
private class GetBedType extends AsyncTask<Void,Void,Void>{
private Dialog loadingDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(BookFragment.this.getActivity(),"Please wait","Fetching Data...");
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
populateSpinner();
loadingDialog.dismiss();
}
@Override
protected Void doInBackground(Void... params) {
ServiceHandler jsonParser = new ServiceHandler();
String json = jsonParser.makeServiceCall(BedType_url, ServiceHandler.GET);
Log.e("Response: ", "> " + json);
if (json != null) {
try {
JSONObject jsonObj = new JSONObject(json);
if (jsonObj != null) {
JSONArray bedType = jsonObj.getJSONArray("result");
for (int i = 0; i < bedType.length(); i++) {
JSONObject bTypeObj = (JSONObject) bedType.get(i);
Category rcat1 = new Category(bTypeObj.getInt("id"),bTypeObj.getString("type"));
bedTypeArray.add(rcat1);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("JSON Data", "Didn't receive any data from server!");
}
return null;
}
}
}
|
package org.kernelab.basis;
public interface HashedEquality<T> extends Equality<T>
{
public int hashCode(T obj);
}
|
package com.tunisiana.tutorials.dao.impl;
import java.util.List;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import com.tunisiana.tutorials.dao.UserDao;
import com.tunisiana.tutorials.model.User;
@Repository("userDao")
@SuppressWarnings("unchecked")
public class UserDaoImpl extends GenericDaoImpl<User, Integer> implements UserDao {
@Autowired
public UserDaoImpl(@Qualifier("sessionFactory") SessionFactory sessionFactory) {
this.setSessionFactory(sessionFactory);
}
/*
* (non-Javadoc)
*
* @see com.tunisiana.tutorials.dao.UserDao#loadByUsername(java.lang.String)
*/
public User loadByUsername(String username) {
DetachedCriteria userCriteria = DetachedCriteria.forClass(User.class);
userCriteria.add(Restrictions.eq("username", username));
List<User> users = (List<User>) getHibernateTemplate().findByCriteria(userCriteria);
if (users.size() != 0) {
return users.get(0);
}
return null;
}
}
|
package com.nuuedscore.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
/**
* Learning Personality Entity
*
* Classification of a Persons Learning
*
* @author PATavares
* @since Feb 2021
*
*/
@Data
@AllArgsConstructor
@EqualsAndHashCode(callSuper = false)
@ToString
@Entity
public class LearningPersonality extends BaseDomain {
private static final long serialVersionUID = 8277228433832974219L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
public LearningPersonality() {
super();
}
public LearningPersonality(final String name) {
super();
this.name = name;
}
}
|
package jardin.Flore;
public class Tomate extends Vegetal {
public Tomate(String etat, String[] Dessin ) {
super(etat, Dessin);
dessin[3] = "t";
dessin[4] = "T";
}
}
|
package com.jayqqaa12.mobilesafe.service;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import org.xmlpull.v1.XmlSerializer;
import android.content.Intent;
import android.content.res.Resources.NotFoundException;
import android.os.Binder;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.util.Xml;
import android.widget.Toast;
import com.jayqqaa12.abase.annotation.view.FindEngine;
import com.jayqqaa12.abase.core.AbaseIntentService;
import com.jayqqaa12.abase.util.IntentUtil;
import com.jayqqaa12.abase.util.ManageUtil;
import com.jayqqaa12.abase.util.sys.SdCardUtil;
import com.jayqqaa12.abase.util.ui.ScreenUtil;
import com.jayqqaa12.abase.util.ui.ToastUtil;
import com.jayqqaa12.mobilesafe.config.Config;
import com.jayqqaa12.mobilesafe.domain.Sms;
import com.jayqqaa12.mobilesafe.engine.comm.sms.SmsEngine;
public class SmsBackupService extends AbaseIntentService
{
private static final String TAG = "SmsBackupService";
@FindEngine
private SmsEngine engine;
private Binder binder = new SmsServiceBind();
@Override
public void onCreate()
{
super.onCreate();
Log.i(TAG, "serivce is onCreate");
}
@Override
public IBinder onBind(Intent intent)
{
return binder;
}
public class SmsServiceBind extends Binder
{
public SmsBackupService getService()
{
return SmsBackupService.this;
}
}
@Override
protected void onHandleIntent(Intent intent)
{
backupSms();
}
private void backupSms()
{
Log.i(TAG, "start bakcup");
try
{
if (!SdCardUtil.isCanUseSdCard()) throw new NotFoundException("SD卡找不到 或者不可用");
List<Sms> list = engine.getAllSms();
if(list.size()==0)
{
ToastUtil.ShortToast("没有短信 需要 备份哦");
return ;
}
File file = new File(Config.SMS_BACKUP_FILE_PATH);
XmlSerializer serializer = Xml.newSerializer();
FileOutputStream os = new FileOutputStream(file);
serializer.setOutput(os, "utf-8");
serializer.startDocument("utf-8", true);
serializer.startTag(null, "smss");
serializer.startTag(null, "count");
serializer.text(list.size() + "");
serializer.endTag(null, "count");
int i = 0;
for (Sms sms : list)
{
serializer.startTag(null, "sms");
serializer.startTag(null, "id");
serializer.text(sms.getId() + "");
serializer.endTag(null, "id");
serializer.startTag(null, "number");
serializer.text(sms.getNumber());
serializer.endTag(null, "number");
serializer.startTag(null, "date");
serializer.text(sms.getDate());
serializer.endTag(null, "date");
serializer.startTag(null, "type");
serializer.text(sms.getType() + "");
serializer.endTag(null, "type");
String content = sms.getContent().replaceAll("[^\\w]", "");
Log.i(TAG,content);
serializer.startTag(null, "body");
serializer.text(content);
serializer.endTag(null, "body");
serializer.endTag(null, "sms");
}
serializer.endTag(null, "smss");
serializer.endDocument();
// 把文件缓冲区的数据写出去
os.flush();
os.close();
ToastUtil.ShortToast("备份完成,备份了"+list.size()+"条短信");
engine.setBackupDate(new Date());
}
catch (NotFoundException e)
{
ToastUtil.ShortToast("SD卡找不到 或者不可用");
e.printStackTrace();
}
catch (IllegalArgumentException e)
{
ToastUtil.ShortToast("备份失败");
e.printStackTrace();
}
catch (IllegalStateException e)
{
ToastUtil.ShortToast("备份失败");
e.printStackTrace();
}
catch (IOException e)
{
ToastUtil.ShortToast("备份失败");
e.printStackTrace();
}
finally
{
Looper.loop();
}
}
@Override
public void onDestroy()
{
IntentUtil.startService(this,MonitorService.class);
super.onDestroy();
}
}
|
package Utilities;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
public class Screenshot
{
WebDriver dr;
//Assigns the local dr with the browser launched dr
public Screenshot(WebDriver dr)
{
this.dr=dr;
}
//Takes the sreenshot by specified name
public void screenShot(String name)
{
File f1=((TakesScreenshot)dr).getScreenshotAs(OutputType.FILE);
File f2=new File("src/test/resources/SCREENSHOTS/"+name+".png");
try
{
FileUtils.copyFile(f1,f2);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
|
/*
* 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 viinimuistio.domain;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author Tony
*/
public class ViiniMuistiinpanoTest {
public ViiniMuistiinpanoTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
@Test
public void nimiOikeinKunAsetettuMetodilla() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
muistiinpano.setTuotteenNimi("uusinimi");
String vastaus = muistiinpano.getTuotteenNimi();
assertEquals("uusinimi", vastaus);
}
@Test
public void nimiNimieamatonKunEiAnnettuNimea() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
String vastaus = muistiinpano.getTuotteenNimi();
assertEquals("tuntematon", vastaus);
}
@Test
public void asettaaVuosikerranOikein() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
muistiinpano.setMuistiinpanonVuosi(2000);
int vastaus = muistiinpano.getMuistiinpanonVuosi();
assertEquals(2000, vastaus);
}
@Test
public void EiAsetaLiianIsoaVuosiKertaa() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
muistiinpano.setMuistiinpanonVuosi(2020);
int vastaus = muistiinpano.getVuosikerta();
assertEquals(0, vastaus);
}
@Test
public void EiAsetaLiianPientäVuosikertaa() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
muistiinpano.setMuistiinpanonVuosi(1620);
int vastaus = muistiinpano.getVuosikerta();
assertEquals(0, vastaus);
}
@Test
public void vuosikertaAluksiNolla() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
int vastaus = muistiinpano.getVuosikerta();
assertEquals(0, vastaus);
}
@Test
public void paivamaaraAlussa2014() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
String vastaus = muistiinpano.getMuistiinpanoPaivamaara();
assertEquals("01.01.2014", vastaus);
}
@Test
public void paivaAsettuuOikein() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
muistiinpano.setMuistiinpanonPaiva(12);
int vastaus = muistiinpano.getMuistiinpanonPaiva();
assertEquals(12, vastaus);
}
@Test
public void eiLiianIsoaPaivalukemaa() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
muistiinpano.setMuistiinpanonPaiva(32);
int vastaus = muistiinpano.getMuistiinpanonPaiva();
assertEquals(1, vastaus);
}
@Test
public void eiLiianPientaPaivalukemaa() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
muistiinpano.setMuistiinpanonPaiva(0);
int vastaus = muistiinpano.getMuistiinpanonPaiva();
assertEquals(1, vastaus);
}
@Test
public void kuukausiAsettuuOikein() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
muistiinpano.setMuistiinpanonKuukausi(12);
int vastaus = muistiinpano.getMuistiinpanonKuukausi();
assertEquals(12, vastaus);
}
@Test
public void eiLiianIsoaKuukautta() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
muistiinpano.setMuistiinpanonKuukausi(13);
int vastaus = muistiinpano.getMuistiinpanonKuukausi();
assertEquals(1, vastaus);
}
@Test
public void eiLiianPientaKuukautta() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
muistiinpano.setMuistiinpanonKuukausi(0);
int vastaus = muistiinpano.getMuistiinpanonKuukausi();
assertEquals(1, vastaus);
}
@Test
public void eiLiianIsoaVuotta() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
muistiinpano.setMuistiinpanonVuosi(2111);
int vastaus = muistiinpano.getMuistiinpanonVuosi();
assertEquals(2014, vastaus);
}
@Test
public void eiLiianPientaVuotta() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
muistiinpano.setMuistiinpanonVuosi(1600);
int vastaus = muistiinpano.getMuistiinpanonVuosi();
assertEquals(2014, vastaus);
}
@Test
public void vuosiAsettuuOikein() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
muistiinpano.setMuistiinpanonVuosi(1989);
int vastaus = muistiinpano.getMuistiinpanonVuosi();
assertEquals(1989, vastaus);
}
@Test
public void paivamaaraAsettuuOikeinJosAsetettuStringilla() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
muistiinpano.setMuistiinpanonPaivamaara("12.12.2012");
String vastaus = muistiinpano.getMuistiinpanoPaivamaara();
assertEquals("12.12.2012", vastaus);
}
@Test
public void josVuosikertaLisattyNiinOnkoLisattyTrue() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
muistiinpano.setVuosikerta(1989);
boolean vastaus = muistiinpano.onkoVuosikerta();
assertEquals(true, vastaus);
}
@Test
public void josVuosikertaaEiLisattyNiinOnkoLisattyFalse() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
boolean vastaus = muistiinpano.onkoVuosikerta();
assertEquals(false, vastaus);
}
@Test
public void josVirheellinenVuosikertaYritettyLisataNiinOnkoLisatty() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
muistiinpano.setVuosikerta(2049);
boolean vastaus = muistiinpano.onkoVuosikerta();
assertEquals(false, vastaus);
}
@Test
public void kuvauksenLisaysToimii() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
muistiinpano.setVapaaKuvausMuistiinpanoon("hihi");
String vastaus = muistiinpano.getVapaaKuvausMuistiinpanoon();
assertEquals("hihi", vastaus);
}
@Test
public void kuvauksAlussaTyhja() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
String vastaus = muistiinpano.getVapaaKuvausMuistiinpanoon();
assertEquals("", vastaus);
}
@Test
public void viiniAlueLisaytyyOikein() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
muistiinpano.setViinialue("Ranska");
String vastaus = muistiinpano.getViinialue();
assertEquals("Ranska", vastaus);
}
@Test
public void viiniAlueOnHuonollaSyotteellaEiAsetettu() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
muistiinpano.setViinialue("lapua");
String vastaus = muistiinpano.getViinialue();
assertEquals("Ei_asetettu", vastaus);
}
@Test
public void alussaEiOleViiniAluetta() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
String vastaus = muistiinpano.getViinialue();
assertEquals(null, vastaus);
}
@Test
public void viiniTyyppiLisaytyyOikein() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
muistiinpano.setViinityyppi("Punaviini");
String vastaus = muistiinpano.getViinityyppi();
assertEquals("Punaviini", vastaus);
}
@Test
public void viiniTyyppiOnHuonollaSyotteellaEiAsetettu() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
muistiinpano.setViinityyppi("lapua");
String vastaus = muistiinpano.getViinityyppi();
assertEquals("Ei_asetettu", vastaus);
}
@Test
public void alussaEiOleViiniTyyppia() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
String vastaus = muistiinpano.getViinityyppi();
assertEquals(null, vastaus);
}
@Test
public void arvioAsettuuOikein() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
muistiinpano.setArvioViinista(1);
int vastaus = muistiinpano.getArvioViinista();
assertEquals(1, vastaus);
}
@Test
public void eiLiianPientaArviota() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
muistiinpano.setArvioViinista(-1);
int vastaus = muistiinpano.getArvioViinista();
assertEquals(0, vastaus);
}
@Test
public void eiLiianIsoaArviota() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
muistiinpano.setArvioViinista(6);
int vastaus = muistiinpano.getArvioViinista();
assertEquals(0, vastaus);
}
@Test
public void alussaEiArviotaViinista() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
int vastaus = muistiinpano.getArvioViinista();
assertEquals(0, vastaus);
}
@Test
public void tunnisteOnViini() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
String vastaus = muistiinpano.getTunniste();
assertEquals("viini", vastaus);
}
@Test
public void rypaleetOnOikein() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
muistiinpano.setRypaleet("Cabernet Sauvignon");
String vastaus = muistiinpano.getRypaleet();
assertEquals("Cabernet Sauvignon", vastaus);
}
@Test
public void josRypaleetEiMaariteltyVastausOnEiMaaritelty() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
String vastaus = muistiinpano.getRypaleet();
assertEquals("Ei määritelty", vastaus);
}
@Test
public void setArvioViinistaStringinaToimiiJosHyvaArvoAnnettu() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
muistiinpano.setArvioViinistaStringina("4");
int vastaus = muistiinpano.getArvioViinista();
assertEquals(4, vastaus);
}
@Test
public void setArvioViinistaStringinaEiToimiJosHuonoArvoAnnettu() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
muistiinpano.setArvioViinistaStringina("Hihhei");
int vastaus = muistiinpano.getArvioViinista();
assertEquals(0, vastaus);
}
@Test
public void setVuosikertaStringinaEiToimiJosHuonoArvoAnnettu() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
muistiinpano.setVuosikertaStringina("Hihhei");
int vastaus = muistiinpano.getVuosikerta();
assertEquals(0, vastaus);
}
@Test
public void setVuosikertaStringinaToimiiJosHyvaArvoAnnettu() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
muistiinpano.setVuosikertaStringina("1999");
int vastaus = muistiinpano.getVuosikerta();
assertEquals(1999, vastaus);
}
@Test
public void setKuukausiMeneeOikeinKunNollaEnsimmäinenMerkki() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
muistiinpano.setMuistiinpanonKuukausi(Integer.parseInt("02"));
int vastaus = muistiinpano.getMuistiinpanonKuukausi();
assertEquals(2, vastaus);
}
@Test
public void setPaivaMeneeOikeinKunNollaEnsimmäinenMerkki() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
muistiinpano.setMuistiinpanonPaiva(Integer.parseInt("02"));
int vastaus = muistiinpano.getMuistiinpanonPaiva();
assertEquals(2, vastaus);
}
@Test
public void getPaivaStringinaLisaaNollanYksinumeroiseenPaivaan() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
muistiinpano.setMuistiinpanonPaiva(2);
String vastaus = muistiinpano.getMuistiinpanonPaivaKaksinumeroisenaStringina();
assertEquals("02", vastaus);
}
@Test
public void getKuukausiStringinaLisaaNollanYksinumeroiseenKuukauteen() {
ViiniMuistiinpano muistiinpano = new ViiniMuistiinpano();
muistiinpano.setMuistiinpanonKuukausi(2);
String vastaus = muistiinpano.getMuistiinpanonKuukausiKaksinumeroisenaStringina();
assertEquals("02", vastaus);
}
}
|
package pl.mgd.datasource.servlet;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import pl.mgd.datasource.data.City;
import pl.mgd.datasource.util.DbUtil;
/**
* Servlet implementation class ControllerServlet
*/
@WebServlet("/ControllerServlet")
public class ControllerServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("city");
String country = request.getParameter("country");
String district = request.getParameter("district");
String populationString = request.getParameter("population");
int population = 0;
if(populationString != null && !populationString.isEmpty()) {
population = Integer.parseInt(populationString);
}
City city = new City(name, country, district, population);
String option = request.getParameter("option");
request.setAttribute("message", messageGenerator(option, city));
request.getRequestDispatcher("message.jsp").forward(request, response);
}
public String messageGenerator(String option, City city) {
String message = null;
switch(option) {
case "add":
try {
DbUtil.insert(city.getName(), city.getCountry(), city.getDistrict(), city.getPopulation());
message = "A record has been added to the database " + city;
} catch(SQLException e) {
message = "The record could not be added " + city;
e.printStackTrace();
}
break;
case "delete":
try {
DbUtil.delete(city.getName());
message = "A record has been deleted from the database " + city.getName();
} catch(SQLException e) {
message = "The record could not be deleted " + city.getName();
e.printStackTrace();
}
break;
}
return message;
}
}
|
package com.itranswarp.jxrest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.Writer;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.itranswarp.jsonstream.JsonBuilder;
import com.itranswarp.jsonstream.JsonWriter;
/**
* RestApiHandler serves JSON-REST API request, and send JSON-Response.
*
* @author Michael Liao
*/
public class RestApiHandler {
Log log = LogFactory.getLog(getClass());
Routes routes = new Routes();
JsonBuilder jsonBuilder = new JsonBuilder();
public void setJsonBuilder(JsonBuilder jsonBuilder) {
this.jsonBuilder = jsonBuilder;
}
public void setHandlers(List<String> names) {
for (String name : names) {
findHandlers(name);
}
}
protected void findHandlers(String name) {
for (Class<?> clazz : new ClassFinder().findClasses(name)) {
addHandler(clazz);
}
}
protected void addHandler(Class<?> clazz) {
try {
routes.addHandler(clazz.newInstance());
}
catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
protected void processApi(HttpServletRequest req, HttpServletResponse resp, String method, String path) throws IOException {
switch (method) {
case "GET":
processApiRequest(req, resp, "GET", path);
break;
case "POST":
processApiRequest(req, resp, "POST", path);
break;
case "PUT":
processApiRequest(req, resp, "PUT", path);
break;
case "DELETE":
processApiRequest(req, resp, "DELETE", path);
break;
default:
processBadRequest(req, resp, method, path);
break;
}
}
protected Object parseBeanFromJson(Class<?> type, HttpServletRequest req) throws IOException {
String encoding = req.getCharacterEncoding();
if (encoding == null) {
encoding = "UTF-8";
}
Reader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(req.getInputStream(), encoding));
return jsonBuilder.createReader(reader).parse(type);
}
finally {
if (reader != null) {
reader.close();
}
}
}
protected void processBadRequest(HttpServletRequest req, HttpServletResponse resp, String method, String path) throws IOException {
resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, "Method Not Allowed");
}
protected boolean checkContentType(String contentType) {
if (contentType == null) {
return false;
}
String ct = contentType.toLowerCase();
if (ct.equals("application/json")) {
return true;
}
if (ct.startsWith("application/json")) {
char ch = ct.charAt(16);
return ch == ' ' || ch == ';';
}
return false;
}
void processApiRequest(HttpServletRequest req, HttpServletResponse resp, String method, String path) throws IOException {
// check content type:
if (!"GET".equals(method) && (req.getContentLength()!=0 && !checkContentType(req.getContentType()))) {
log.debug("415 UNSUPPORTED MEDIA TYPE: not a json request.");
resp.sendError(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE, "Request must be application/json.");
return;
}
RestContext.initRestContext(req, resp);
try {
JsonCallback jsonCallback = null;
if (!"GET".equals(method)) {
jsonCallback = (Class<?> type) -> {
return parseBeanFromJson(type, req);
};
}
Object ret = this.routes.call(method, path, jsonCallback, req, resp);
if (ret instanceof Void) {
return;
}
resp.setCharacterEncoding("UTF-8");
resp.setContentType("application/json");
Writer writer = resp.getWriter();
JsonWriter jsonWriter = this.jsonBuilder.createWriter(writer);
jsonWriter.write(ret);
writer.flush();
}
catch (ApiNotFoundException e) {
resp.sendError(HttpServletResponse.SC_NOT_FOUND);
}
catch (Exception e) {
log.error("Process API failed.", e);
resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
finally {
RestContext.destroyRestContext();
}
}
}
|
package cdn.discovery;
import java.util.HashMap;
import cdn.shared.message.types.LinkInfo;
public class Cdn extends HashMap<String, PeerList> {
/**
*
*/
private static final long serialVersionUID = 1L;
private LinkInfo[] links;
/**
* Returns null if no node left to advertise.
*
* @return the PeerList to advertise.
*/
public PeerList getNextAdvertisement() {
for (String key : keySet()) {
PeerList cur = get(key);
if (cur.hasPeers()) {
return cur;
}
}
return null;
}
public void resetNotifications() {
for (String key : keySet()) {
PeerList cur = get(key);
cur.resetNotifications();
}
}
public LinkInfo[] getCurrentGraph() {
return links;
}
public void setLinks(LinkInfo[] links) {
this.links = links;
}
}
|
package com.cs371m.austinrecycle;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.Settings;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity<ViewGroup> extends Activity {
private static final String TAG = "MainActivity.java";
private EditText _materialEditText;
private ImageButton _searchButton;
private AutoCompleteTextView _locationAutoCompleteTextView;
private CheckBox _currentLocationCheckBox;
private String[] _materialNames;
private TypedArray _icons;
private ArrayList<MaterialItem> _materialItemArray;
private Geocoder _geocoder;
private double _currentLat;
private double _currentLong;
private LocationManager _locationManager;
private AlertDialog _materialListDialog;
private PlacesTask _placesTask;
private boolean[] _oldSelectedItems;
private ArrayList<Integer> _seletedItems;
private boolean _isSearching;
/**
* onCreate
*/
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialization
_materialItemArray = new ArrayList<MaterialItem>();
_geocoder = new Geocoder(this, Locale.getDefault());
_materialNames = MainActivity.this.getResources().getStringArray(R.array.list_material_name);
_oldSelectedItems = new boolean[_materialNames.length];
for(int i = 0; i < _oldSelectedItems.length; i++) {
_oldSelectedItems[i] = false;
}
_seletedItems = new ArrayList<Integer>();
_isSearching = false;
if(savedInstanceState != null) {
_oldSelectedItems = savedInstanceState.getBooleanArray("_oldSelectedItems");
_seletedItems = savedInstanceState.getIntegerArrayList("_seletedItems");
}
// Setup _materialEditText to show MaterialDialog when clicked
_materialEditText = (EditText) MainActivity.this.findViewById(R.id.materials_editText);
_materialEditText.setKeyListener(null);
_materialEditText.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
_materialItemArray.clear();
showMaterialDialog();
}
});
// Setup actions when the search button is clicked
_searchButton = (ImageButton) MainActivity.this.findViewById(R.id.search_button);
_searchButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Users must select at least ONE material
if(_materialEditText.getText().toString().equals("")) {
Toast.makeText(MainActivity.this, "Please select at least ONE material", Toast.LENGTH_SHORT).show();
_materialEditText.requestFocus();
}
else if(_locationAutoCompleteTextView.getText().toString().equals("")) {
showLocationDialog();
}
else {
if(_isSearching == false) {
// Get the latitude and longitude of address entered
try {
String currentAddress = _locationAutoCompleteTextView.getText().toString();
List<Address> returnedAddress = _geocoder.getFromLocationName(currentAddress, 1);
_currentLat = returnedAddress.get(0).getLatitude();
_currentLong = returnedAddress.get(0).getLongitude();
}
catch(IOException e) {
Log.e(TAG, "Error occured in Geocoder: ", e);
}
// Convert to String array to pass as parameter
String[] selectedMaterialArray = _materialEditText.getText().toString().split(",");
// Trim spaces, and format material names to their database attribute names
for(int i = 0; i < selectedMaterialArray.length; ++i) {
selectedMaterialArray[i] = selectedMaterialArray[i].trim().toLowerCase().replace(' ', '_');;
}
// Needs to create a new task every time
new NetworkRequestTask().execute(selectedMaterialArray);
_isSearching = true;
}
else {
Toast.makeText(MainActivity.this, "Austin Recycling is searching for locations now. Please wait.", Toast.LENGTH_SHORT).show();
}
}
}
});
// Location AutoComplete using suggestions from Google Location API
_locationAutoCompleteTextView = (AutoCompleteTextView) MainActivity.this.findViewById(R.id.location_autoCompleteTextView);
_locationAutoCompleteTextView.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
_placesTask = new PlacesTask();
_placesTask.execute(s.toString());
}
@Override
public void afterTextChanged(Editable s) {
Log.d(TAG, "afterTextChanged: " + s.toString());
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
Log.d(TAG, "beforeTextChanged: " + s);
}
});
_locationAutoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
_placesTask.cancel(true);
InputMethodManager imm = (InputMethodManager)MainActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(_locationAutoCompleteTextView.getWindowToken(), 0);
_locationAutoCompleteTextView.dismissDropDown();
}
});
// Setup actions to get current location
_currentLocationCheckBox = (CheckBox)this.findViewById(R.id.current_location_checkbox);
try {
_currentLocationCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked) {
if(checkGpsStatus()) {
MainActivity.this.getCurrentLocation();
InputMethodManager imm = (InputMethodManager)MainActivity.this.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(_locationAutoCompleteTextView.getWindowToken(), 0);
_placesTask.cancel(true);
}
else {
showGpsDialog();
_currentLocationCheckBox.setChecked(false);
}
}
else {
_locationAutoCompleteTextView.setText("");
}
}
});
}
catch(Exception e) {
showErrorDialog("Error getting current location.");
Log.e(TAG, "Error getting current location", e);
}
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBooleanArray("_oldSelectedItems", _oldSelectedItems);
outState.putIntegerArrayList("_seletedItems", _seletedItems);
}
/**
* onResume() is called after onCreate()
*/
@Override
protected void onResume() {
super.onResume();
}
/**
* onStop() will be called when the orientation is changed
*/
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop");
if(_materialListDialog != null) {
_materialListDialog.dismiss();
}
if(_placesTask == null) {
_placesTask = new PlacesTask();
}
_isSearching = false;
}
/**
* onPause
*/
@Override
protected void onPause() {
super.onPause();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case(R.id.action_about):
showAbout();
return true;
case(R.id.reset):
_materialEditText.setText("");
_locationAutoCompleteTextView.setText("");
_currentLocationCheckBox.setChecked(false);
_oldSelectedItems = new boolean[_materialNames.length];
return true;
}
return false;
}
static class ViewHolder {
public TextView text;
public CheckBox checkbox;
}
/**
* private methods in this class
*/
private void showAbout() {
AlertDialog.Builder aboutDialogBuilder = new AlertDialog.Builder(MainActivity.this);
aboutDialogBuilder.setTitle("About Austin Recycling");
aboutDialogBuilder.setMessage("Developed by: David, Mike and Alex\n\n" +
"Advised by: Mike Scott\n\n" +
"Most location related features are powered by Google.\n\n" +
"Recycle Drop Off Locations from https://data.austintexas.gov");
aboutDialogBuilder.setNeutralButton("Done", new AlertDialog.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog aboutDialog = aboutDialogBuilder.create();
aboutDialog.show();
}
/**
* Display list of materials
* Selected materials will be removed from the list
*/
private void showMaterialDialog() {
Log.d(TAG, "entering popChooseMaterialDialog");
final AlertDialog.Builder materialDialogBuilder = new AlertDialog.Builder(this)
.setTitle("Please select materials");
_icons = MainActivity.this.getResources().obtainTypedArray(R.array.list_material_icon);
// Store MaterialItem into ArrayList
for(int i=0; i<_materialNames.length; ++i) {
_materialItemArray.add(new MaterialItem(_icons.getResourceId(i, 0), _materialNames[i]));
}
_icons.recycle();
final CharSequence[] items = new CharSequence[_materialNames.length];
final int[] localSelectedItems = new int[_materialNames.length];
for(int i=0; i<_materialNames.length; ++i) {
items[i] = _materialNames[i];
localSelectedItems[i] = 0;
}
ListAdapter adapter = new ArrayAdapter<MaterialItem>(this, R.layout.checkboxes, R.id.textView1, _materialItemArray){
public View getView(final int position, View convertView, android.view.ViewGroup parent) {
ViewHolder viewHolder = null;
if(convertView == null){
LayoutInflater inflator = getLayoutInflater();
convertView = inflator.inflate(R.layout.checkboxes, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) convertView.findViewById(R.id.textView1);
viewHolder.checkbox = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(viewHolder);
viewHolder.checkbox.setTag(_oldSelectedItems[position]);
}
else {
((ViewHolder) convertView.getTag()).checkbox.setTag(_oldSelectedItems[position]);
}
viewHolder = (ViewHolder) convertView.getTag();
// Put the image on the TextView
final Drawable image;
Resources res = getResources();
image = res.getDrawable(_materialItemArray.get(position).getIcon());
int dp25 = (int) (25 * getResources().getDisplayMetrics().density + 0.5f);
image.setBounds(0, 0, dp25, dp25);
viewHolder.text.setCompoundDrawables(image, null, null, null);
viewHolder.text.setText(_materialItemArray.get(position).getName());
//Add margin between image and text (support various screen densities)
int dp5 = (int) (5 * getResources().getDisplayMetrics().density + 0.5f);
viewHolder.text.setCompoundDrawablePadding(dp5);
//Ensure no other setOnCheckedChangeListener is attached before you manually change its state.
viewHolder.checkbox.setOnCheckedChangeListener(null);
if(_oldSelectedItems[position]) viewHolder.checkbox.setChecked(true);
else viewHolder.checkbox.setChecked(false);
viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// If the user checked the item, add it to the selected items
Log.d("true","true");
_seletedItems.add(position);
_oldSelectedItems[position] = true;
localSelectedItems[position] = 2;
}
else if (_seletedItems.contains(position)) {
Log.d("false","false");
// Else, if the item is already in the array, remove it
_seletedItems.remove(Integer.valueOf(position));
_oldSelectedItems[position] = false;
localSelectedItems[position] = 1;
}
}
});
return convertView;
}
};
materialDialogBuilder.setAdapter(adapter, null);
// Set action for OK buttons
materialDialogBuilder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
String oldString = "";
for(int i=0; i<_materialNames.length; ++i) {
String clickedMaterial = items[i].toString();
if(_oldSelectedItems[i])
oldString = oldString.equals("") ? clickedMaterial : oldString + ", " + clickedMaterial;
}
_materialEditText.setText(oldString);
dialog.dismiss();
}
});
// Set action for Cancel buttons
materialDialogBuilder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int id) {
String oldString = "";
for(int i=0; i<_materialNames.length; ++i) {
String clickedMaterial = items[i].toString();
if(localSelectedItems[i] == 2)
_oldSelectedItems[i] = false;
if(localSelectedItems[i] == 1)
_oldSelectedItems[i] = true;
if(_oldSelectedItems[i])
oldString = oldString.equals("") ? clickedMaterial : oldString + ", " + clickedMaterial;
}
_materialEditText.setText(oldString);
dialog.dismiss();
}
});
_materialListDialog = materialDialogBuilder.create();
_materialListDialog.show();
}
/**
* Check GPS status
* @return true if GPS is on
* @return false if GPS is off
*/
private boolean checkGpsStatus() {
ContentResolver contentResolver = MainActivity.this.getBaseContext().getContentResolver();
boolean gpsStatus = Settings.Secure.isLocationProviderEnabled(contentResolver, LocationManager.GPS_PROVIDER);
return gpsStatus;
}
/**
* Check mobile status
* @return true if mobile is on
* @return false if mobile is off
*/
private boolean checkMobileStatus() {
ContentResolver contentResolver = MainActivity.this.getBaseContext().getContentResolver();
boolean mobileStatus = Settings.Secure.isLocationProviderEnabled(contentResolver, LocationManager.NETWORK_PROVIDER);
return mobileStatus;
}
/**
* Get current location using GPS and display the address to _locationAutoCompleteTextView
*/
private void getCurrentLocation() {
_locationManager = (LocationManager)this.getSystemService(LOCATION_SERVICE);
Location location = null;
if (checkMobileStatus()) {
_locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 15000, 10, new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, "begin onStatusChanged");
Log.d(TAG, "provider: " + provider);
Log.d(TAG, "status: " + status);
Log.d(TAG, "extras: " + extras.describeContents());
Log.d(TAG, "end onStatusChanged");
}
@Override
public void onProviderEnabled(String provider) {
Log.d(TAG, "begin onProviderEnabled");
Log.d(TAG, "provider: " + provider);
Log.d(TAG, "end onProviderEnabled");
}
@Override
public void onProviderDisabled(String provider) {
Log.d(TAG, "begin onProviderDisabled");
Log.d(TAG, "provider: " + provider);
Log.d(TAG, "end onProviderDisabled");
}
@Override
public void onLocationChanged(Location location) {
Log.d(TAG, "begin onLocationChanged");
Log.d(TAG, "provider: " + location.describeContents());
_currentLat = location.getLatitude();
_currentLong = location.getLongitude();
Log.d(TAG, "end onLocationChanged");
}
});
Log.d("Network", "Network Enabled");
if (_locationManager != null) {
location = _locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
_currentLat = location.getLatitude();
_currentLong = location.getLongitude();
}
}
}
if (checkGpsStatus()) {
if (location == null) {
_locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 15000, 10, new LocationListener() {
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.d(TAG, "begin onStatusChanged");
Log.d(TAG, "provider: " + provider);
Log.d(TAG, "status: " + status);
Log.d(TAG, "extras: " + extras.describeContents());
Log.d(TAG, "end onStatusChanged");
}
@Override
public void onProviderEnabled(String provider) {
Log.d(TAG, "begin onProviderEnabled");
Log.d(TAG, "provider: " + provider);
Log.d(TAG, "end onProviderEnabled");
}
@Override
public void onProviderDisabled(String provider) {
Log.d(TAG, "begin onProviderDisabled");
Log.d(TAG, "provider: " + provider);
Log.d(TAG, "end onProviderDisabled");
}
@Override
public void onLocationChanged(Location location) {
Log.d(TAG, "begin onLocationChanged");
Log.d(TAG, "provider: " + location.describeContents());
_currentLat = location.getLatitude();
_currentLong = location.getLongitude();
Log.d(TAG, "end onLocationChanged");
}
});
Log.d(TAG, "GPS Enabled");
if (_locationManager != null) {
location = _locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
_currentLat = location.getLatitude();
_currentLong = location.getLongitude();
}
}
}
}
// Convert coordinates to address
try {
List<Address> returnedAddress = _geocoder.getFromLocation(_currentLat, _currentLong, 5);
for(Address addr : returnedAddress) {
Log.d(TAG, "returnedAddress: " + addr.getAddressLine(0) + ", "
+ addr.getAddressLine(1) + ", "
+ addr.getAddressLine(2));
}
Address currentAddress = returnedAddress.get(0);
_locationAutoCompleteTextView.setText(currentAddress.getAddressLine(0) + ", "
+ currentAddress.getAddressLine(1) + ", "
+ currentAddress.getAddressLine(2));
}
catch (IOException e) {
showErrorDialog("Error getting current location.");
Log.e(TAG, "Error getting current location", e);
}
}
/**
* show error dialog when exception occurs
*/
private void showErrorDialog(String errorMessage) {
Log.d(TAG, "called");
final AlertDialog.Builder errorDialogBuilder = new AlertDialog.Builder(MainActivity.this);
errorDialogBuilder.setTitle("Error");
errorDialogBuilder.setMessage(errorMessage + "\nPlease try again.");
errorDialogBuilder.setNeutralButton("Ok", new AlertDialog.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
final AlertDialog errorDialog = errorDialogBuilder.create();
errorDialog.show();
}
/**
* Show locationDialog
*/
private void showLocationDialog() {
final AlertDialog.Builder locationDialogBuilder = new AlertDialog.Builder(MainActivity.this);
locationDialogBuilder.setTitle("Use current location");
locationDialogBuilder.setMessage("You did not enter an address. Would you like to use your current location?");
locationDialogBuilder.setNegativeButton("No", new AlertDialog.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
locationDialogBuilder.setPositiveButton("Yes", new AlertDialog.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if(checkGpsStatus()) {
MainActivity.this.getCurrentLocation();
_currentLocationCheckBox.setChecked(true);
}
else {
dialog.dismiss();
showGpsDialog();
_currentLocationCheckBox.setChecked(false);
}
}
});
final AlertDialog locationDialog = locationDialogBuilder.create();
locationDialog.show();
}
/**
* Show GPS Settings dialog
*/
private void showGpsDialog() {
final AlertDialog.Builder gpsDialogBuilder = new AlertDialog.Builder(MainActivity.this);
gpsDialogBuilder.setTitle("Turn on GPS");
gpsDialogBuilder.setMessage("Please turn on your GPS and try again.");
gpsDialogBuilder.setNegativeButton("Try again", new AlertDialog.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
_currentLocationCheckBox.setChecked(false);
}
});
gpsDialogBuilder.setPositiveButton("Go to Settings", new AlertDialog.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Log.d(TAG, "GPS Settings");
startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
MainActivity.this.recreate();
}
});
final AlertDialog gpsDialog = gpsDialogBuilder.create();
gpsDialog.show();
}
/**
* Class to run HTTP network requests in a worker thread. Necessary to
* keep the UI interactive.
*
* Types specified are <Argument Type, Progress Update Type, Return Type>
*/
private class NetworkRequestTask extends AsyncTask<String, Float, ArrayList<FacilityItem>> {
private static final String TAG = "MainActivity.NetworkRequestTask";
@Override
protected ArrayList<FacilityItem> doInBackground(String... materials) {
Log.d(TAG, "begin doInBackground");
Model m = new Model(_currentLat, _currentLong);
Log.d(TAG, "end doInBackground");
return m.getFacilities(materials);
}
@Override
protected void onPreExecute() {
_searchButton.startAnimation(AnimationUtils.loadAnimation(MainActivity.this, R.anim.rotate));
}
/**
* Invoked in asynchronously in MainActivity when the network request
* has finished and doInBackground returns its result.
*/
@Override
protected void onPostExecute(ArrayList<FacilityItem> facilities) {
Log.d(TAG, "begin onPostExecute");
// Start the ResultListActivity
Intent resultIntent = new Intent(MainActivity.this, ResultListActivity.class);
resultIntent.putParcelableArrayListExtra("RETURNED_RESULT", (ArrayList<? extends Parcelable>) facilities);
resultIntent.putExtra("CURRENT_LAT", _currentLat);
resultIntent.putExtra("CURRENT_LONG", _currentLong);
MainActivity.this.startActivity(resultIntent);
Log.d(TAG, "end onPostExecute");
}
}
/**
* Asynchronously get place suggestions from Google
*/
private class PlacesTask extends AsyncTask<String, Void, ArrayList<String>> {
private static final String TAG = "MainActivity.PlacesTask";
private static final String PLACES_API_BASE = "https://maps.googleapis.com/maps/api/place";
private static final String TYPE_AUTOCOMPLETE = "/autocomplete";
private static final String OUT_JSON = "/json";
private static final String API_KEY = "AIzaSyCnLUmKZNvy5P7R2p1RJw2fd4VGNRbcJBU";
protected ArrayList<String> doInBackground(String... input) {
Log.d(TAG, "Async PlacesTask doInBackground(): ");
ArrayList<String> resultList = null;
HttpURLConnection conn = null;
StringBuilder jsonResults = new StringBuilder();
try {
StringBuilder sb = new StringBuilder(PLACES_API_BASE + TYPE_AUTOCOMPLETE + OUT_JSON);
sb.append("?sensor=true");
sb.append("&components=country:us");
sb.append("&input=" + URLEncoder.encode(input[0], "utf8"));
sb.append("&country=austin");
sb.append("&types=geocode");
sb.append("&key=" + API_KEY);
URL url = new URL(sb.toString());
conn = (HttpURLConnection) url.openConnection();
InputStreamReader in = new InputStreamReader(conn.getInputStream());
// Load the results into a StringBuilder
int read;
char[] buff = new char[1024];
while ((read = in.read(buff)) != -1) {
jsonResults.append(buff, 0, read);
}
}
catch (MalformedURLException e) {
showErrorDialog("Error connecting to Google.");
Log.e(TAG, "Error processing Places API URL", e);
}
catch (IOException e) {
showErrorDialog("Error connecting to Google.");
Log.e(TAG, "Error connecting to Places API", e);
}
catch(Exception e) {
showErrorDialog("Error connecting to Google.");
Log.e(TAG, "Error connecting to Places API", e);
}
finally {
if (conn != null) {
conn.disconnect();
}
}
try {
// Create a JSON object hierarchy from the results
JSONObject jsonObj = new JSONObject(jsonResults.toString());
JSONArray predsJsonArray = jsonObj.getJSONArray("predictions");
// Extract the Place descriptions from the results
resultList = new ArrayList<String>(predsJsonArray.length());
for (int i = 0; i < predsJsonArray.length(); i++) {
resultList.add(predsJsonArray.getJSONObject(i).getString("description"));
}
}
catch (JSONException e) {
showErrorDialog("Error connecting to Google.");
Log.e(TAG, "Cannot process JSON results", e);
}
return resultList;
}
protected void onPostExecute(ArrayList<String> resultList) {
Log.d(TAG, "Async PlacesTask onPostExecute(): ");
LocationAutoCompleteAdapter locAdapter = new LocationAutoCompleteAdapter(MainActivity.this, R.layout.location_list_item, resultList);
_locationAutoCompleteTextView.setAdapter(locAdapter);
_locationAutoCompleteTextView.showDropDown();
}
}
}
|
package fe.dto;
import be.entity.OrderPosition;
import java.util.ArrayList;
import java.util.List;
public class OrderDto {
private Long id_order;
private Long id_user;
private List<OrderPositionDto> orderPositions;
private Double total_price;
public OrderDto() {
orderPositions = new ArrayList<>();
total_price = 0.0;
}
public Long getId_order() {
return id_order;
}
public void setId_order(Long id_order) {
this.id_order = id_order;
}
public Long getId_user() {
return id_user;
}
public void setId_user(Long id_user) {
this.id_user = id_user;
}
public List<OrderPositionDto> getOrderPositions() {
return orderPositions;
}
public void setOrderPositions(List<OrderPositionDto> orderPositions) {
this.orderPositions = orderPositions;
}
public void setMapOrderPositions(List<OrderPosition> ordersPositions) {
for(OrderPosition orderPosition: ordersPositions){
this.orderPositions.add(Mapper.map(orderPosition));
}
}
public Double getTotal_price() {
return total_price;
}
public void setTotal_price(Double total_price) {
this.total_price = total_price;
}
}
|
/**
* KITE2
*/
package com.kite.modules.att.dao;
import java.util.Date;
import org.apache.ibatis.annotations.Param;
import com.kite.common.persistence.CrudDao;
import com.kite.common.persistence.annotation.MyBatisDao;
import com.kite.modules.att.entity.SysBaseStudent;
/**
* 学员DAO接口
* @author lyb
* @version 2019-11-13
*/
@MyBatisDao
public interface SysBaseStudentDao extends CrudDao<SysBaseStudent> {
/**
* 查找学生表当前数量
* @return
*/
public int findStudentCount(@Param("beginTime")Date beginTime, @Param("endTime")Date endTime);
}
|
package com.tencent.mm.plugin.profile.ui;
import android.content.Intent;
import android.view.View;
import android.view.View.OnClickListener;
import com.tencent.mm.plugin.profile.ui.NormalUserFooterPreference.j;
class NormalUserFooterPreference$j$1 implements OnClickListener {
final /* synthetic */ j lXQ;
NormalUserFooterPreference$j$1(j jVar) {
this.lXQ = jVar;
}
public final void onClick(View view) {
NormalUserFooterPreference.b(this.lXQ.lXw).getIntent().removeExtra("Accept_NewFriend_FromOutside");
Intent intent = new Intent(NormalUserFooterPreference.b(this.lXQ.lXw), SayHiWithSnsPermissionUI.class);
intent.putExtra("Contact_User", NormalUserFooterPreference.a(this.lXQ.lXw).field_username);
intent.putExtra("Contact_Nick", NormalUserFooterPreference.a(this.lXQ.lXw).field_nickname);
intent.putExtra("Contact_RemarkName", NormalUserFooterPreference.a(this.lXQ.lXw).field_conRemark);
if (NormalUserFooterPreference.l(this.lXQ.lXw) == 14 || NormalUserFooterPreference.l(this.lXQ.lXw) == 8) {
intent.putExtra("Contact_RoomNickname", NormalUserFooterPreference.b(this.lXQ.lXw).getIntent().getStringExtra("Contact_RoomNickname"));
}
intent.putExtra("Contact_Scene", NormalUserFooterPreference.l(this.lXQ.lXw));
intent.putExtra("Verify_ticket", NormalUserFooterPreference.y(this.lXQ.lXw));
intent.putExtra("sayhi_with_sns_perm_send_verify", false);
intent.putExtra("sayhi_with_sns_perm_add_remark", true);
intent.putExtra("sayhi_with_sns_perm_set_label", true);
NormalUserFooterPreference.b(this.lXQ.lXw).startActivity(intent);
}
}
|
package org.sbbs.base.webapp.action;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.Dispatcher;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.opensymphony.xwork2.config.Configuration;
import com.opensymphony.xwork2.config.ConfigurationManager;
import com.opensymphony.xwork2.config.RuntimeConfiguration;
import com.opensymphony.xwork2.config.entities.ActionConfig;
/**
* @author Administrator
*/
public class BaseDwzAction
extends ActionSupport
implements Preparable {
/**
*
*/
private static final long serialVersionUID = -6789529022826198177L;
//protected final transient Logger log = LoggerFactory.getLogger( getClass() );
protected HttpServletRequest getRequest() {
return ServletActionContext.getRequest();
}
protected HttpServletResponse getResponse() {
return ServletActionContext.getResponse();
}
protected HttpSession getSession() {
return getRequest().getSession();
}
@Override
public void prepare()
throws Exception { // TODO Auto-generated method stub
// printAllStruts2Actions();
}
protected void printAllStruts2Actions() {
Dispatcher dispatcher = Dispatcher.getInstance();
ConfigurationManager cm = dispatcher.getConfigurationManager();
Configuration cf = cm.getConfiguration();
RuntimeConfiguration rc = cf.getRuntimeConfiguration();
Map<String, Map<String, ActionConfig>> d = rc.getActionConfigs();
Set nc = d.keySet();
for ( String key1 : d.keySet() ) {
if ( !key1.equalsIgnoreCase( "" ) && !key1.equalsIgnoreCase( "/config-browser" ) ) {
System.out.println( key1 );
Map<String, ActionConfig> a = d.get( key1 );
for ( String key2 : a.keySet() ) {
System.out.println( key2 );
ActionConfig ac = a.get( key2 );
}
}
}
}
protected static final int AJAX_STATUS_SUCCESS = 200;
protected static final int AJAX_STATUS_ERROR = 300;
protected static final int AJAX_STATUS_TIMEOUT = 301;
protected static final String CALLBACKTYPE_CLOSECURRENT = "closeCurrent";
private int statusCode = AJAX_STATUS_SUCCESS;
private String message;
private String callbackType = "";
public String getMessage() {
return message;
}
public void setMessage( String ajaxMessage ) {
this.message = ajaxMessage;
}
public int getStatusCode() {
return statusCode;
}
public void setStatusCode( int ajaxStatus ) {
this.statusCode = ajaxStatus;
}
public String getCallbackType() {
return callbackType;
}
public void setCallbackType( String callbackType ) {
this.callbackType = callbackType;
}
}
|
package com.example.x_b;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.x_b.db.DatasBeanDao;
import java.util.ArrayList;
import java.util.List;
/**
* A simple {@link Fragment} subclass.
*/
public class BFragment extends Fragment {
private ArrayList<DatasBean> list;
private Rvadapter rvadapter;
private View inflate;
public BFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
inflate = inflater.inflate(R.layout.fragment_b, container, false);
return inflate;
}
@Override
public void onHiddenChanged(boolean hidden) {
if(hidden==false){
initview(inflate);
}
super.onHiddenChanged(hidden);
}
private void initview(View inflate) {
RecyclerView rv = inflate.findViewById(R.id.rv);
rv.setLayoutManager(new LinearLayoutManager(getContext()));
rv.addItemDecoration(new DividerItemDecoration(getContext(),DividerItemDecoration.VERTICAL));
DatasBeanDao datasBeanDao = BaseApp.getInstance().getDaoSession().getDatasBeanDao();
list = new ArrayList<>();
List<DatasBean> listbean = datasBeanDao.queryBuilder().list();
list.addAll(listbean);
rvadapter = new Rvadapter(list,getContext());
rv.setAdapter(rvadapter);
}
}
|
package com.example.gymsy.connection;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class PostData implements Runnable {
private volatile String value;
private String postData;
private String url;
public PostData(String postData, String url){
this.postData = postData;
this.url = url;
}
@Override
public void run() {
try {
URL url = new URL(this.url);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setRequestMethod("POST");
con.setDoOutput(true);
con.getOutputStream().write(this.postData.getBytes("UTF-8"));
InputStream response = con.getInputStream();
String jsonReply = convertStreamToString(response);
this.value = jsonReply;
} catch (Exception e) {
e.printStackTrace();
}
}
public String getValue(){
return this.value;
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
public String postData() {
try {
Thread thread = new Thread(this);
thread.start();
thread.join();
String jsonResult = this.getValue();
Log.e("test", jsonResult );
return jsonResult;
}
catch(Exception e){
e.printStackTrace();
String fail = "{\"msg\":\"Username Exists\"}";
return fail;
}
}
}
|
/**
* Cria um JPanel que contém uma tabela, usando o GridBagLayout
* @return JPanel
* */
public JPanel createTablePanel(String[] table_columns, Object[][] table_rows, JButton[] buttons,
String[] buttons_names, String panel_name,
DefaultTableModel tm, JTable t)
{
JLabel panel_title = new JLabel(panel_name); //título do painel
Box button_box = new Box(BoxLayout.X_AXIS); //caixa para os botoes
buttons = new JButton[buttons_names.length]; //botões do painel
JPanel table_panel = new JPanel();
table_panel.setLayout(new GridBagLayout()); //setando o layout
GridBagConstraints c = new GridBagConstraints(); //definições do layout
c.fill = GridBagConstraints.HORIZONTAL; //se necessário, aumente o tamanho do componente na horizontal
//definindo o modelo da tabela e a tabela
tm = new DefaultTableModel(table_rows, table_columns);
t = new JTable(tm);
JScrollPane spane = new JScrollPane(t); //cria um scrollpane com a tabela
t.setPreferredScrollableViewportSize(new Dimension(500, 300));
t.setFillsViewportHeight(true);
//adicionar o título do painel na linha 0 e coluna 0
c.weightx = 0.5; //definir o espaço distribuido pelas colunas (0.0 - 1.0)
c.gridx = 0; c.gridy = 0;
table_panel.add(panel_title, c);
//criar o grupo de botões
for(int i = 0; i < buttons_names.length; i++)
{
buttons[i] = new JButton(buttons_names[i]);
button_box.add(buttons[i]);
}
//adicionar tabela na linha 1 e preencher 3 colunas na horizontal
c.gridwidth = 3;
c.gridx = 0;
c.gridy = 1;
table_panel.add(spane, c);
//adicionar os botões na linha 2
c.gridx = 0;
c.gridy = 2;
table_panel.add(button_box, c);
return table_panel;
}
|
package com.kimkha.readability;
import org.jsoup.nodes.TextNode;
/**
* Object to relate a range of PC-data to a text node in an XOM tree.
*/
public class OffsetRange {
private int start;
private int end;
private TextNode text;
OffsetRange(int start, int end, TextNode text) {
this.start = start;
this.end = end;
this.text = text;
assert this.text == null || this.text.text().length() == this.end - this.start;
}
public String toString() {
return super.toString() + "[" + this.start + "-" + this.end + " " + this.text.text() + "]";
}
public TextNode getText() {
return text;
}
public int getEnd() {
return end;
}
public int getStart() {
return start;
}
public void setStart(int start) {
this.start = start;
}
public void setEnd(int end) {
this.end = end;
}
public void setText(TextNode text) {
this.text = text;
}
public boolean offsetInRange(int offset) {
return offset >= start && offset < end;
}
}
|
package com.espendwise.manta.util;
import com.espendwise.manta.model.data.FiscalCalenderData;
import com.espendwise.manta.model.data.FiscalCalenderDetailData;
import com.espendwise.manta.model.view.FiscalCalendarIdentView;
import com.espendwise.manta.model.view.FiscalCalendarListView;
import com.espendwise.manta.model.view.FiscalCalendarPhysicalView;
import com.espendwise.manta.util.parser.Parse;
import org.apache.log4j.Logger;
import java.text.SimpleDateFormat;
import java.util.*;
public class FiscalCalendarUtility {
private static final Logger logger = Logger.getLogger(FiscalCalendarUtility .class);
public static String getTailPeriodByDate(Date pExpDate) {
String res = "";
if (pExpDate != null) {
Calendar c = new GregorianCalendar();
c.setTime(pExpDate);
c.add(Calendar.DAY_OF_MONTH, 1);
res = new SimpleDateFormat("M/d").format(c.getTime());
}
return res;
}
public static FiscalCalenderDetailData createTailPeriod(FiscalCalenderData calendarData, int num) {
FiscalCalenderDetailData p = new FiscalCalenderDetailData();
p.setFiscalCalenderId(calendarData.getFiscalCalenderId());
p.setPeriod(num);
p.setMmdd(getTailPeriodByDate(calendarData.getExpDate()));
return p;
}
public static SortedMap<Integer, FiscalCalenderDetailData> toPeriodMap(List<FiscalCalenderDetailData> periods) {
SortedMap<Integer, FiscalCalenderDetailData> m = new TreeMap<Integer, FiscalCalenderDetailData>();
for (FiscalCalenderDetailData p : periods) {
m.put(p.getPeriod(), p);
}
return m;
}
public static Date getMmDdDate(FiscalCalendarIdentView calendar, int period) {
return getMmDdDate(calendar.getFiscalCalendarData(), period, toPeriodMap(calendar.getPeriods()));
}
public static Date getMmDdDate(FiscalCalenderData calendar, List<FiscalCalenderDetailData> periods, int period) {
return getMmDdDate(calendar, period, toPeriodMap(periods));
}
public static Date getMmDdDate(FiscalCalenderData calendar, int period, SortedMap<Integer, FiscalCalenderDetailData> periodMsp) {
return getMmDdDate(calendar.getEffDate(), period, periodMsp);
}
public static Date getMmDdDate(Date effDate, int period, SortedMap<Integer, FiscalCalenderDetailData> periodMsp) {
ArrayList<Integer> periodIndexes = new ArrayList<Integer>(periodMsp.keySet());
int year = getYearForDate(effDate);
if (periodIndexes.size() == 1) {
return Parse.parseMonthWithDay(
getMmdd(periodMsp, periodIndexes.get(0)),
year,
Constants.SYSTEM_MONTH_WITH_DAY_PATTERN
);
}
for (int i = 0; i < periodIndexes.size() - 1; i++) {
String mmdd1 = getMmdd(periodMsp, periodIndexes.get(i));
Date date1 = Utility.isSet(mmdd1) ? Parse.parseMonthWithDay(mmdd1, year, Constants.SYSTEM_MONTH_WITH_DAY_PATTERN) : null;
String mmdd2 = getMmdd(periodMsp, periodIndexes.get(i + 1));
Date date2 = Utility.isSet(mmdd2) ? Parse.parseMonthWithDay(mmdd2, year, Constants.SYSTEM_MONTH_WITH_DAY_PATTERN) : null;
if (date2 != null && date1 != null && date1.compareTo(date2) > 0) {
year = year + 1;
date2 = Parse.parseMonthWithDay(getMmdd(periodMsp, periodIndexes.get(i + 1)), year, Constants.SYSTEM_MONTH_WITH_DAY_PATTERN);
}
if (period == periodIndexes.get(i)) {
return date1;
}
if (period == periodIndexes.get(i + 1)) {
return date2;
}
}
return null;
}
private static String getMmdd(SortedMap<Integer, FiscalCalenderDetailData> periodMsp, Integer period) {
return periodMsp.get(period).getMmdd();
}
public static int getYearForDate(Date pDate) {
GregorianCalendar cal = new GregorianCalendar();
cal.setTime(pDate);
return cal.get(Calendar.YEAR);
}
public static SortedMap<Integer, Date> toPeriodDateMap(FiscalCalendarIdentView calendar) {
SortedMap<Integer, Date> x = new TreeMap<Integer, Date>();
SortedMap<Integer, FiscalCalenderDetailData> periodsMap = toPeriodMap(calendar.getPeriods());
for (Integer period : periodsMap.keySet()) {
x.put(period, getMmDdDate(calendar.getFiscalCalendarData(),
period,
periodsMap
)
);
}
return x;
}
public static SortedMap<Integer, Date> toPeriodDateMap(FiscalCalendarPhysicalView calendarPhysical) {
SortedMap<Integer, Date> x = new TreeMap<Integer, Date>();
SortedMap<Integer, FiscalCalenderDetailData> periodsMap = toPeriodMap(calendarPhysical.getPeriods());
for (Integer period : periodsMap.keySet()) {
x.put(period,
getMmDdDate(
getPhysicalEffDate(calendarPhysical),
period,
periodsMap
)
);
}
return x;
}
public static SortedMap<Integer, Integer> signedPeriodsIndexSet(FiscalCalendarPhysicalView calendarPhysical) {
SortedMap<Integer, Integer> x = new TreeMap<Integer, Integer>();
SortedMap<Integer, FiscalCalenderDetailData> periodsMap = toPeriodMap(calendarPhysical.getPeriods());
if(calendarPhysical.isServiceScheduleCalendar()) {
periodsMap.remove(periodsMap.lastKey());
}
int i = 0;
for (Integer period : periodsMap.keySet()) {
x.put(i++, period);
}
return x;
}
public static Date getPhysicalEffDate(FiscalCalendarPhysicalView calendarPhysical) {
Calendar cal = new GregorianCalendar();
cal.setTime(calendarPhysical.getEffDate());
if (Utility.intNN(calendarPhysical.getCalendatFiscalYear()) == 0) {
return new GregorianCalendar(calendarPhysical.getPhysicalFiscalYear(),
cal.get(Calendar.MONTH),
cal.get(Calendar.DAY_OF_MONTH)
).getTime();
} else {
return cal.getTime();
}
}
public static int getPhysicalYear(Integer fiscalYear, Date date) {
return Utility.intNN(fiscalYear) == 0 ? getYearForDate(date) : fiscalYear;
}
public static Date calcExpDate(FiscalCalendarListView calendar) {
return calcExpDate(calendar.getFiscalYear());
}
public static Date calcExpDate(Integer fiscalYear) {
Date dt = new Date();
Calendar c = Calendar.getInstance();
c.setTime(new Date());
int year = c.get(Calendar.YEAR);
year = (fiscalYear > 0) ? fiscalYear : year;
try {
dt = Parse.parseDate("12/31/" + year, Constants.SYSTEM_DATE_PATTERN);
} catch (Exception ex) {
ex.printStackTrace();
}
return dt;
}
public static Date calcExpDate(Integer fiscalYear, Date expDate) {
return expDate == null
? Parse.parseDate("12/31/" + getPhysicalYear(fiscalYear, new Date()), Constants.SYSTEM_DATE_PATTERN)
: expDate;
}
public static Integer getPeriodOrNull(FiscalCalendarPhysicalView calendarPhysical, Date date) {
//logger.info("getPeriodOrNull()=> BEGIN, date: " + date);
Date today = Utility.setToMidnight(date);
SortedMap<Integer, Date> periodDateMap = toPeriodDateMap(calendarPhysical);
ArrayList<Integer> periodIndexes = new ArrayList<Integer>(periodDateMap.keySet());
Date effDate = getPhysicalEffDate(calendarPhysical);
Date expDate = calendarPhysical.getExpDate();
//logger.info("getPeriodOrNull()=> effDate: " + calendarPhysical.getEffDate());
//logger.info("getPeriodOrNull()=> physicalDate: " + effDate);
// logger.info("getPeriodOrNull()=> expDate: " + expDate);
Set<Integer> keys = periodDateMap.keySet();
// logger.info("getPeriodOrNull()=> periodDateMap: " + periodDateMap);
// logger.info("getPeriodOrNull()=> periodIndexes: " + periodIndexes);
//logger.info("getPeriodOrNull()=> keys: " + keys);
Integer period = 0;
for (int i = 0; i < periodIndexes.size() - 1; i++) {
Date from = periodDateMap.get(periodIndexes.get(i));
Date to = periodDateMap.get(periodIndexes.get(i + 1));
// logger.info("getPeriodOrNull()=> check[" + i + "] " + new DateArgument(from).resolve() + " > " + new DateArgument(date).resolve() + " < " + new DateArgument(to).resolve());
if (to != null) { // if calendar valid and was created by manta
if (from.compareTo(today) <= 0 && to.compareTo(today) > 0) {
return periodIndexes.get(i);
}
} else if (i == periodIndexes.size()) { // maybe created using old ui and last period is null
if (expDate != null) { // old calendars have expDate is null
if (from.compareTo(today) <= 0 && expDate.compareTo(today) > 0 || from.compareTo(today) <= 0) {
return periodIndexes.get(i);
}
}
}
period = periodIndexes.get(i);
}
return period;
}
public static boolean isPeriodAfter(Date periodA, Date periodB, boolean ignoreYear) {
Calendar calPeriodA = Calendar.getInstance();
calPeriodA.setTime(periodA);
Calendar calPeriodB = Calendar.getInstance();
calPeriodB.setTime(periodB);
if (!ignoreYear) {
logger.info(" calPeriodB.getTime(): "+calPeriodB.getTime()+" after "+calPeriodA.getTime());
return calPeriodB.getTime().after(calPeriodA.getTime());
} else {
calPeriodA.set(Calendar.YEAR, Constants.LEAP_YEAR);
calPeriodB.set(Calendar.YEAR, Constants.LEAP_YEAR);
logger.info(" calPeriodB.getTime(): "+calPeriodB.getTime()+" after(ignoreYear) "+calPeriodA.getTime());
return calPeriodB.getTime().after(calPeriodA.getTime());
}
}
}
|
package com.xm.user.service;
import com.xm.user.dao.BlogCatalogDao;
import com.xm.user.dao.BlogDao;
import com.xm.user.domain.Blog;
import com.xm.user.domain.BlogCatalog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* Created by xm on 2017/1/5.
*/
@Service
public class BlogService {
@Autowired
private BlogDao blogDao;
@Autowired
private BlogCatalogDao bcDao;
public int addBlogCatalog(BlogCatalog blogCatalog){
return bcDao.addBlogCatalog(blogCatalog);
}
//limit pageSize
//offset 起始位置
public List<BlogCatalog> queryBlogCatalog(String uid,int limit,int offset){
return bcDao.queryBlogCatalog(uid,limit,offset);
}
public int countBlogCatalog(String uid){
return bcDao.countBlogCatalog(uid);
}
public int addBlog(Blog blog){
return blogDao.addBlog(blog);
}
public int deleteBlogCatalog(List<Integer> idList,String uid){
return bcDao.deleteBlogCatalog(idList,uid);
}
public int updateBlogCatalog(String name,int id,String uid){
return bcDao.updateBlogCatalog(name,id,uid);
}
}
|
package com.duanxr.yith.midium;
import java.util.PriorityQueue;
/**
* @author 段然 2021/3/8
*/
public class KClosestPointsToOrigin {
/**
* Given an array of points where points[i] = [xi, yi] represents a point on the X-Y plane and an integer k, return the k closest points to the origin (0, 0).
*
* The distance between two points on the X-Y plane is the Euclidean distance (i.e, √(x1 - x2)2 + (y1 - y2)2).
*
* You may return the answer in any order. The answer is guaranteed to be unique (except for the order that it is in).
*
*
*
* Example 1:
*
*
* Input: points = [[1,3],[-2,2]], k = 1
* Output: [[-2,2]]
* Explanation:
* The distance between (1, 3) and the origin is sqrt(10).
* The distance between (-2, 2) and the origin is sqrt(8).
* Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
* We only want the closest k = 1 points from the origin, so the answer is just [[-2,2]].
* Example 2:
*
* Input: points = [[3,3],[5,-1],[-2,4]], k = 2
* Output: [[3,3],[-2,4]]
* Explanation: The answer [[-2,4],[3,3]] would also be accepted.
*
*
* Constraints:
*
* 1 <= k <= points.length <= 104
* -104 < xi, yi < 104
*
* 我们有一个由平面上的点组成的列表 points。需要从中找出 K 个距离原点 (0, 0) 最近的点。
*
* (这里,平面上两点之间的距离是欧几里德距离。)
*
* 你可以按任何顺序返回答案。除了点坐标的顺序之外,答案确保是唯一的。
*
*
*
* 示例 1:
*
* 输入:points = [[1,3],[-2,2]], K = 1
* 输出:[[-2,2]]
* 解释:
* (1, 3) 和原点之间的距离为 sqrt(10),
* (-2, 2) 和原点之间的距离为 sqrt(8),
* 由于 sqrt(8) < sqrt(10),(-2, 2) 离原点更近。
* 我们只需要距离原点最近的 K = 1 个点,所以答案就是 [[-2,2]]。
* 示例 2:
*
* 输入:points = [[3,3],[5,-1],[-2,4]], K = 2
* 输出:[[3,3],[-2,4]]
* (答案 [[-2,4],[3,3]] 也会被接受。)
*
*
* 提示:
*
* 1 <= K <= points.length <= 10000
* -10000 < points[i][0] < 10000
* -10000 < points[i][1] < 10000
*
*/
class Solution {
public int[][] kClosest(int[][] points, int K) {
int[][] result = new int[K][2];
PriorityQueue<PointClass> priorityQueue = new PriorityQueue<>();
for (int[] point : points) {
priorityQueue.add(new PointClass(point));
}
for (int i = 0; i < K; i++) {
result[i] = priorityQueue.poll().getPoint();
}
return result;
}
public class PointClass implements Comparable<PointClass> {
private int[] point;
PointClass(int[] point) {
this.point = point;
}
public int getDistancePow() {
int x = point[0];
int y = point[1];
return x * x + y * y;
}
public int[] getPoint() {
return point;
}
@Override
public int compareTo(PointClass o) {
return this.getDistancePow() - o.getDistancePow();
}
}
}
}
|
public class Vector {
float x, y, z;
float length;
public Vector(float x, float y, float z) {
this.x = x;
this.y = y;
this.z = z;
length = (float) Math.sqrt(x*x + y*y + z*z);
}
public Vector add(Vector v) {
return new Vector(this.x + v.x,
this.y + v.y,
this.z + v.z);
}
public Vector mul(float k) {
return new Vector(k * this.x,
k * this.y,
k * this.z);
}
public Vector sub(Vector v) {
return this.add(v.mul(-1));
}
public Vector div(float k) {
return this.mul(1 / k);
}
public float dot(Vector v) {
return (this.x * v.x) + (this.y * v.y) + (this.z * v.z);
}
public Vector cross(Vector v) {
return new Vector(this.y*v.z - this.z*v.y,
-(this.x*v.z - this.z*v.x),
this.x*v.y - this.y*v.x);
}
public Vector unitVector() {
return this.div(this.length);
}
}
|
package com.android.account;
import android.content.Intent;
import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import com.android.base.FragmentHostActivity;
import com.android.base.fragment.BaseFragment;
import com.android.base.fragment.FragmentAction;
import com.android.common.utils.view.ToolbarUtil;
import com.viewinject.annotation.MyBindView;
import com.viewinject.annotation.MyOnClick;
import com.viewinject.bindview.MyViewInjector;
public class AccountLoginFragment extends BaseFragment {
private static final String TAG = AccountLoginFragment.class.getSimpleName();
private String username;
@MyBindView(resId = "et_username")
public EditText et_username;
@MyBindView(resId = "tv_register")
public TextView textView;
public static AccountLoginFragment newInstance() {
return new AccountLoginFragment();
}
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return setRootView(inflater, R.layout.account_frg_login);
}
@Override
public void initRootViews(View baseRootView) {
super.initRootViews(baseRootView);
ToolbarUtil.configTitle(baseRootView, "登录", View.VISIBLE);
MyViewInjector.bindView(this, baseRootView);
Log.d(TAG, "initRootViews: "+getContext().getPackageName());
}
@Override
public void onViewStateRestored(@Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
// et_username.setText(username);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == FragmentAction.FRAGMENT_RESULT_OK) {
username = data.getStringExtra("username");
}
}
@Override
public void onDestroy() {
super.onDestroy();
MyViewInjector.unbindView(this);
}
@MyOnClick(resId = "tv_register") // 在同一个Activity里面
public void register() {
replaceFragmentToStack(AccountRegisterFragment.newInstance(), AccountLoginFragment.this);
}
@MyOnClick(resId = "tv_setpwd") // 重新打开Activity
public void setPwd() {
FragmentHostActivity.openFragment(getActivity(), AccountModPwdFragment.newInstance());
}
}
|
package com.company.Weak4Day2;
public class Task1 {
public static void main(String[] args) {
Person person1 = new Person("Suren", "Badalyan", "Male", "Armenian", "457687186", 24);
Person person2 = new Person();
person2.setFirstName("Suren");
System.out.println("Firstname - " + person2.getFirstName());
person2.setPassportId("AN768718");
System.out.println("Passpor ID - " + person2.getPassportId());
// person2.display();
}
}
|
/*
* 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 pe.gob.onpe.adan.model.adan;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
/**
*
* @author bvaldez
*/
@Entity
@Table(name = "TAB_DOCUMENTO")
public class Documento implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "SEQ_DOCUMENTO")
@SequenceGenerator(name = "SEQ_DOCUMENTO", sequenceName = "SEQ_DOCUMENTO_PK")
@Column(name = "N_DOCUMENTO_PK")
private Integer id;
@Column(name = "C_NOMBRE")
private String nombre;
@Column(name = "B_ARCHIVO")
private byte[] archivo;
@Column(name = "N_MODULO")
private int modulo;
@Column(name = "D_FECHA_CARGA")
private Date fechaCarga;
@Column(name = "C_RESOLUCION")
private String resolucion;
@Column(name = "C_INFORMACION_ADICIONAL")
private String informacionAdicional;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public byte[] getArchivo() {
return archivo;
}
public void setArchivo(byte[] archivo) {
this.archivo = archivo;
}
public int getModulo() {
return modulo;
}
public void setModulo(int modulo) {
this.modulo = modulo;
}
public Date getFechaCarga() {
return fechaCarga;
}
public void setFechaCarga(Date fechaCarga) {
this.fechaCarga = fechaCarga;
}
public String getResolucion() {
return resolucion;
}
public void setResolucion(String resolucion) {
this.resolucion = resolucion;
}
public String getInformacionAdicional() {
return informacionAdicional;
}
public void setInformacionAdicional(String informacionAdicional) {
this.informacionAdicional = informacionAdicional;
}
}
|
package sortAlgorithm;
public class QuickSortDemo {
}
|
package uk.ac.dundee.computing.aec.instagrim.servlets;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
@WebServlet("/uploaddoc1")
@MultipartConfig(maxFileSize = 161772155) // upload file's size up to 16MB
public class FileUploadDBServlet4 extends HttpServlet {
// database connection settings
private String dbURL = "jdbc:mysql://localhost:3306/test";
private String dbUser = "root";
private String dbPass = "";
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// gets values of text fields
String accno = request.getParameter("accno");
/* String email = request.getParameter("email");
String age = request.getParameter("age");
String dob=request.getParameter("dob");
String gender=request.getParameter("gender");
String add=request.getParameter("address");
String city=request.getParameter("city");
String email=request.getParameter("email");
String mob=request.getParameter("mobile");
String username=request.getParameter("username");
*/
InputStream inputStream = null; // input stream of the upload file
// obtains the upload file part in this multipart request
Part filePart = request.getPart("photo");
if (filePart != null) {
// prints out some information for debugging
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
// obtains input stream of the upload file
inputStream = filePart.getInputStream();
}
Connection conn = null; // connection to the database
String message = null; // message will be sent back to client
try {
// connects to the database
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
conn = DriverManager.getConnection(dbURL, dbUser, dbPass);
// constructs SQL statement
String sql = "INSERT INTO upload1 (accno, photo) values ( ?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, accno);
System.out.println("username in upload serv "+ accno);
/* statement.setString(2, email);
statement.setString(4, age);
statement.setString(5, dob);
statement.setString(6, gender);
statement.setString(7, add);
statement.setString(8, city);
statement.setString(9, email);
statement.setString(10, mob);
statement.setString(11, username);
*/
if (inputStream != null) {
// fetches input stream of the upload file for the blob column
statement.setBlob(2, inputStream);
}
// sends the statement to the database server
int row = statement.executeUpdate();
System.out.println("File uploaded and saved into database");
if (row > 0) {
message = "File uploaded and saved into database";
}
} catch (SQLException ex) {
message = "ERROR: " + ex.getMessage();
ex.printStackTrace();
} finally {
if (conn != null) {
// closes the database connection
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
// sets the message in request scope
request.setAttribute("accno", accno);
request.setAttribute("Message", message);
request.getRequestDispatcher("Index2.jsp").forward(request,response);
System.out.println("data send to set pass");
// forwards to the message page
//response.sendRedirect("Set_Pass.jsp");
System.out.println("complete");
// getServletContext().getRequestDispatcher("/Set_Pass.jsp").forward(request, response);
}
}
}
|
package de.dhbw.studientag.dbHelpers;
import java.util.ArrayList;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import de.dhbw.studientag.model.Company;
import de.dhbw.studientag.model.Subject;
public final class OfferedSubjectsHelper {
protected static final String OFFERED_SUBJECTS_TABLE_NAME = "OfferedSubjects";
protected static final String COMPANY_ID = "companyId";
protected static final String SUBJECT_ID = "subjectId";
protected static final String[] OFFERED_SUBJECTS_ALL_COLUMNS = { COMPANY_ID,
SUBJECT_ID };
protected static final String OFFERED_SUBJECTS_TABLE_CREATE = "CREATE TABLE "
+ OFFERED_SUBJECTS_TABLE_NAME + " ( " + COMPANY_ID + " INTEGER REFERENCES "
+ CompanyHelper.COMPANY_TABLE_NAME + "(" + MySQLiteHelper.ID + "), "
+ SUBJECT_ID + " INTEGER REFERENCES " + SubjectsHelper.SUBJECTS_TABLE_NAME
+ "(" + MySQLiteHelper.ID + ")" + ")";
protected static final void initOfferedSubjects(Company company, SQLiteDatabase db) {
ArrayList<Subject> offeredSubjects = company.getSubjectList();
for (Subject subject : offeredSubjects) {
ContentValues values = new ContentValues();
values.put(COMPANY_ID, company.getId());
Subject subjectbyname = SubjectsHelper
.getSubjectByName(db, subject.getName());
values.put(SUBJECT_ID, subjectbyname.getId());
db.insert(OFFERED_SUBJECTS_TABLE_NAME, null, values);
}
}
protected static ArrayList<Subject> getOfferdSubjectsByCompanyId(long companyId,
SQLiteDatabase db) {
ArrayList<Subject> offeredSubjects = new ArrayList<Subject>();
String query = "SELECT " + SUBJECT_ID + ", " + SubjectsHelper.SUBJECT_NAME
+ " FROM " + OFFERED_SUBJECTS_TABLE_NAME + " os INNER JOIN "
+ SubjectsHelper.SUBJECTS_TABLE_NAME + " s ON " + "s."
+ MySQLiteHelper.ID + "=os." + SUBJECT_ID + " WHERE os." + COMPANY_ID
+ "=? ORDER BY s." + SubjectsHelper.SUBJECT_NAME + " ASC";
Cursor cursor = db.rawQuery(query, new String[] { Long.toString(companyId) });
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
int subjectId = cursor.getInt(cursor.getColumnIndex(SUBJECT_ID));
Subject subject = SubjectsHelper.getSubjectById(db, subjectId);
offeredSubjects.add(subject);
cursor.moveToNext();
}
cursor.close();
return offeredSubjects;
}
}
|
import java.util.*;
public class SelectionSort
{
public static void selectionSort(ArrayList<Integer> arr)
{
if(arr == null)
return;
for(int i = 0; i < arr.size()-1; i++)
{
int smallestIndex = findSmallest(arr, i, arr.size()-1);
swap(arr, i, smallestIndex);
}
}
/*
* Purpose: Swaps the elements in the array at the given indices
*/
public static void swap(ArrayList<Integer> arr, int index1, int index2)
{
if(arr == null || index1 < 0 || index1 >= arr.size() || index2 < 0 || index2 >= arr.size())
throw new IllegalArgumentException();
int temp = arr.get(index1);
arr.set(index1, arr.get(index2));
arr.set(index2, temp);
}
/*
* Purpose: Returns the index of the smallest value in an Integer array in the given range.
*/
public static int findSmallest(ArrayList<Integer> al, int lo, int hi)
{
if(al == null || al.size()==0 || lo < 0 || hi >= al.size())
throw new IllegalArgumentException();
int smallestIndex = lo;
int smallestElem = al.get(lo);
for(int i = lo + 1; i <= hi; i++)
{
if(al.get(i) < smallestElem)
{
smallestIndex = i;
smallestElem = al.get(i);
}
}
return smallestIndex;
}
/*
* Purpose: Returns the index of the smallest value in an Integer aray.
*/
public static int findSmallest(ArrayList<Integer> al)
{
if(al == null || al.size() == 0)
return -1;
return findSmallest(al, 0, al.size()-1);
}
/*
* Purpose: Generate an array of random Integers with "num" elements
*/
public static ArrayList<Integer> makeItArRain(int num) //Topher, you're not the only punny one.
{
ArrayList<Integer> arr = new ArrayList<Integer>();
for(int i = 0; i < num; i++)
{
int rando = (int)(num * Math.random());
arr.add(rando);
}
return arr;
}
}//end class
|
package model.interfaces;
import java.awt.Graphics2D;
import java.util.List;
import model.shapes.Shape;
public interface IShapeDraw {
void drawAllShapes(Graphics2D g2d,List<Shape>shapeList);
void clearCanvais(Graphics2D g2d);
}
|
package ru.qa.addressbook.tests;
import org.testng.annotations.*;
import ru.qa.addressbook.model.GroupData;
import ru.qa.addressbook.model.Groups;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.MatcherAssert.assertThat;
public class GroupDeletionsTests extends TestBase {
@BeforeMethod
public void ensurePreconditions() {
app.goTo().groupPage();
if (app.group().all().size() == 0){
app.group().create(new GroupData().withName("test2"));
}
}
@Test
public void testGroupDelete() {
Groups before = app.group().all();
GroupData deleteGroup = before.iterator().next();
app.group().delete(deleteGroup);
assertThat(app.group().count(), equalTo(before.size() - 1));
Groups after = app.group().all();
assertThat(after, equalTo(before.without(deleteGroup)));
}
}
|
package com.lucy.start.mvc.spring.service;
import java.util.List;
import com.lucy.start.mvc.spring.vo.News;
public interface NewsService {
public List<News> getNews();
}
|
package figury;
import java.awt.Color;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import javax.swing.JComponent;
import tools.RandomValues;
public class Circle extends JComponent implements Figure, Moveable
{
public Circle(int rangeMin, int rangeMax)
{
RandomValues validator = new RandomValues();
x = validator.randomize(rangeMin, rangeMax);
y = validator.randomize(rangeMin, rangeMax);
diameter = validator.randomize(rangeMin, rangeMax);
}
public Circle()
{
RandomValues validator = new RandomValues();
x = validator.randomize(RANGE_MIN, RANGE_MAX);
y = validator.randomize(RANGE_MIN, RANGE_MAX);
diameter = validator.randomize(RANGE_MIN, RANGE_MAX);
}
public int getX()
{
return x;
}
public int getY() {
return y;
}
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2.setPaint(new GradientPaint(0,0,Color.gray,20,20,Color.green,true));
g2.fillOval(0, 0, this.diameter, this.diameter);
repaint();
}
public void drawObject(Frame frame)
{
frame.add(this);
frame.revalidate();
}
public boolean containsFigure(int xCoordinateWhileClicked,int yCoordinateWhileClicked)
{
if(xCoordinateWhileClicked > this.x && xCoordinateWhileClicked < (this.x + this.diameter)
&& yCoordinateWhileClicked > this.y && yCoordinateWhileClicked < (this.y+this.diameter))
return true;
else
return false;
}
public void moveObject(int xOffsetValue, int yOffsetValue)
{
repaint(0, 0, this.diameter+1, this.diameter+1);
this.x += xOffsetValue;
this.y += yOffsetValue;
}
private int x;
private int y;
private int diameter;
}
|
package com.carty.service.impl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import com.carty.message.request.Article;
import com.carty.message.response.NewsMessage;
import com.carty.message.response.TextMessage;
import com.carty.service.CoreService;
import com.carty.util.MessageUtil;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 核心服务类
*/
@Service("coreService")
public class CoreServiceImpl implements CoreService {
private static Logger logger = LoggerFactory.getLogger(CoreServiceImpl.class);
/**
* 处理微信发来的请求(包括事件的推送)
*
* @param request
* @return
*/
public String processRequest(HttpServletRequest request) {
String respMessage = null;
try {
// 默认返回的文本消息内容
String respContent = "请求处理异常,请稍候尝试!";
// xml请求解析
Map<String, String> requestMap = MessageUtil.parseXml(request);
// 发送方帐号(open_id)
String fromUserName = requestMap.get("FromUserName");
// 公众帐号
String toUserName = requestMap.get("ToUserName");
// 消息类型
String msgType = requestMap.get("MsgType");
// 回复文本消息
TextMessage textMessage = new TextMessage();
textMessage.setToUserName(fromUserName);
textMessage.setFromUserName(toUserName);
textMessage.setCreateTime(new Date().getTime());
textMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);
textMessage.setFuncFlag(0);
// 创建图文消息
NewsMessage newsMessage = new NewsMessage();
newsMessage.setToUserName(fromUserName);
newsMessage.setFromUserName(toUserName);
newsMessage.setCreateTime(new Date().getTime());
newsMessage.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_NEWS);
newsMessage.setFuncFlag(0);
List<Article> articleList = new ArrayList<Article>();
// 接收文本消息内容
String content = requestMap.get("Content");
//记录日志
logger.info(fromUserName + "请求的内容是:" + content);
// 自动回复文本消息
if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_TEXT)) {
//如果用户发送表情,则回复同样表情。
if (isQqFace(content)) {
respContent = content;
textMessage.setContent(respContent);
// 将文本消息对象转换成xml字符串
respMessage = MessageUtil.textMessageToXml(textMessage);
} else {
//回复固定消息
switch (content) {
case "1": {
StringBuffer buffer = new StringBuffer();
buffer.append("您好,我是小8,请回复数字选择服务:").append("\n\n");
buffer.append("11 可查看测试单图文").append("\n");
buffer.append("12 可测试多图文发送").append("\n");
buffer.append("13 可测试网址").append("\n");
buffer.append("或者您可以尝试发送表情").append("\n\n");
buffer.append("回复“1”显示此帮助菜单").append("\n");
respContent = String.valueOf(buffer);
textMessage.setContent(respContent);
respMessage = MessageUtil.textMessageToXml(textMessage);
break;
}
case "11": {
//测试单图文回复
Article article = new Article();
article.setTitle("微信公众帐号开发教程Java版");
// 图文消息中可以使用QQ表情、符号表情
article.setDescription("这是测试有没有换行\n\n如果有空行就代表换行成功\n\n点击图文可以跳转到百度首页");
// 将图片置为空
article.setPicUrl("http://www.sinaimg.cn/dy/slidenews/31_img/2016_38/28380_733695_698372.jpg");
article.setUrl("http://www.baidu.com");
articleList.add(article);
newsMessage.setArticleCount(articleList.size());
newsMessage.setArticles(articleList);
respMessage = MessageUtil.newsMessageToXml(newsMessage);
break;
}
case "12": {
//多图文发送
Article article1 = new Article();
article1.setTitle("紧急通知,不要捡这种钱!湛江都已经传疯了!\n");
article1.setDescription("");
article1.setPicUrl("http://www.sinaimg.cn/dy/slidenews/31_img/2016_38/28380_733695_698372.jpg");
article1.setUrl("http://mp.weixin.qq.com/s?__biz=MjM5Njc2OTI4NQ==&mid=2650924309&idx=1&sn=8bb6ae54d6396c1faa9182a96f30b225&chksm=bd117e7f8a66f769dc886d38ca2d4e4e675c55e6a5e01e768b383f5859e09384e485da7bed98&scene=4#wechat_redirect");
Article article2 = new Article();
article2.setTitle("湛江谁有这种女儿,请给我来一打!");
article2.setDescription("");
article2.setPicUrl("http://www.sinaimg.cn/dy/slidenews/31_img/2016_38/28380_733695_698372.jpg");
article2.setUrl("http://mp.weixin.qq.com/s?__biz=MjM5Njc2OTI4NQ==&mid=2650924309&idx=2&sn=d7ffc840c7e6d91b0a1c886b16797ee9&chksm=bd117e7f8a66f7698d094c2771a1114853b97dab9c172897c3f9f982eacb6619fba5e6675ea3&scene=4#wechat_redirect");
Article article3 = new Article();
article3.setTitle("以上图片我就随意放了");
article3.setDescription("");
article3.setPicUrl("http://www.sinaimg.cn/dy/slidenews/31_img/2016_38/28380_733695_698372.jpg");
article3.setUrl("http://mp.weixin.qq.com/s?__biz=MjM5Njc2OTI4NQ==&mid=2650924309&idx=3&sn=63e13fe558ff0d564c0da313b7bdfce0&chksm=bd117e7f8a66f7693a26853dc65c3e9ef9495235ef6ed6c7796f1b63abf1df599aaf9b33aafa&scene=4#wechat_redirect");
articleList.add(article1);
articleList.add(article2);
articleList.add(article3);
newsMessage.setArticleCount(articleList.size());
newsMessage.setArticles(articleList);
respMessage = MessageUtil.newsMessageToXml(newsMessage);
break;
}
case "13": {
//测试网址回复
respContent = "<a href=\"http://www.baidu.com\">百度主页</a>";
textMessage.setContent(respContent);
// 将文本消息对象转换成xml字符串
respMessage = MessageUtil.textMessageToXml(textMessage);
break;
}
default: {
respContent = "(这是里面的)很抱歉,现在小8暂时无法提供此功能给您使用。\n\n回复“1”显示帮助信息";
textMessage.setContent(respContent);
// 将文本消息对象转换成xml字符串
respMessage = MessageUtil.textMessageToXml(textMessage);
}
}
}
}
// 图片消息
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_IMAGE)) {
respContent = "您发送的是图片消息!";
textMessage.setContent(respContent);
// 将文本消息对象转换成xml字符串
respMessage = MessageUtil.textMessageToXml(textMessage);
}
// 地理位置消息
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LOCATION)) {
respContent = "您发送的是地理位置消息!";
textMessage.setContent(respContent);
// 将文本消息对象转换成xml字符串
respMessage = MessageUtil.textMessageToXml(textMessage);
}
// 链接消息
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_LINK)) {
respContent = "您发送的是链接消息!";textMessage.setContent(respContent);
// 将文本消息对象转换成xml字符串
respMessage = MessageUtil.textMessageToXml(textMessage);
}
// 音频消息
else if (msgType.equals(MessageUtil.REQ_MESSAGE_TYPE_VOICE)) {
respContent = "您发送的是音频消息!";
textMessage.setContent(respContent);
// 将文本消息对象转换成xml字符串
respMessage = MessageUtil.textMessageToXml(textMessage);
}
} catch (Exception e) {
e.printStackTrace();
}
return respMessage;
}
/**
* 判断是否是QQ表情
*
* @param content
* @return
*/
public static boolean isQqFace(String content) {
boolean result = false;
// 判断QQ表情的正则表达式
String qqfaceRegex = "/::\\)|/::~|/::B|/::\\||/:8-\\)|/::<|/::$|/::X|/::Z|/::'\\(|/::-\\||/::@|/::P|/::D|/::O|/::\\(|/::\\+|/:--b|/::Q|/::T|/:,@P|/:,@-D|/::d|/:,@o|/::g|/:\\|-\\)|/::!|/::L|/::>|/::,@|/:,@f|/::-S|/:\\?|/:,@x|/:,@@|/::8|/:,@!|/:!!!|/:xx|/:bye|/:wipe|/:dig|/:handclap|/:&-\\(|/:B-\\)|/:<@|/:@>|/::-O|/:>-\\||/:P-\\(|/::'\\||/:X-\\)|/::\\*|/:@x|/:8\\*|/:pd|/:<W>|/:beer|/:basketb|/:oo|/:coffee|/:eat|/:pig|/:rose|/:fade|/:showlove|/:heart|/:break|/:cake|/:li|/:bome|/:kn|/:footb|/:ladybug|/:shit|/:moon|/:sun|/:gift|/:hug|/:strong|/:weak|/:share|/:v|/:@\\)|/:jj|/:@@|/:bad|/:lvu|/:no|/:ok|/:love|/:<L>|/:jump|/:shake|/:<O>|/:circle|/:kotow|/:turn|/:skip|/:oY|/:#-0|/:hiphot|/:kiss|/:<&|/:&>";
Pattern p = Pattern.compile(qqfaceRegex);
Matcher m = p.matcher(content);
if (m.matches()) {
result = true;
}
return result;
}
}
|
package com.algorithm.queue;
/**
* @author zhangbingquan
* @desc 队列的抽象接口
* @time 2019/8/30 1:46
*/
public interface Queue {
/*
* @desc 入队
* @return boolean
*/
public boolean append(Object object)throws Exception;
/*
* @desc 删除元素
* @return java.lang.Object
*/
public Object delete() throws Exception;
/*
* @desc 获取队头元素
* @return java.lang.Object
*/
public Object getFront() throws Exception;
/*
* @desc 队列判空,队列为空返回true
* @return boolean
*/
public boolean isEmpty();
}
|
package com.rui.cn.controller;
import com.rui.cn.feignclients.HelloFenginService;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/get")
public class HelloFeigenController {
@Autowired
private HelloFenginService helloFenginService;
@GetMapping("/search/github")
public ResponseEntity<byte[]> searchRepo(@RequestParam("str") @ApiParam(name = "关键字", required = true) String queryStr) {
return helloFenginService.searchRepo(queryStr);
}
}
|
package net.minecraft.network.play.server;
import java.io.IOException;
import net.minecraft.network.INetHandler;
import net.minecraft.network.Packet;
import net.minecraft.network.PacketBuffer;
import net.minecraft.network.play.INetHandlerPlayClient;
public class SPacketUpdateHealth implements Packet<INetHandlerPlayClient> {
private float health;
private int foodLevel;
private float saturationLevel;
public SPacketUpdateHealth() {}
public SPacketUpdateHealth(float healthIn, int foodLevelIn, float saturationLevelIn) {
this.health = healthIn;
this.foodLevel = foodLevelIn;
this.saturationLevel = saturationLevelIn;
}
public void readPacketData(PacketBuffer buf) throws IOException {
this.health = buf.readFloat();
this.foodLevel = buf.readVarIntFromBuffer();
this.saturationLevel = buf.readFloat();
}
public void writePacketData(PacketBuffer buf) throws IOException {
buf.writeFloat(this.health);
buf.writeVarIntToBuffer(this.foodLevel);
buf.writeFloat(this.saturationLevel);
}
public void processPacket(INetHandlerPlayClient handler) {
handler.handleUpdateHealth(this);
}
public float getHealth() {
return this.health;
}
public int getFoodLevel() {
return this.foodLevel;
}
public float getSaturationLevel() {
return this.saturationLevel;
}
}
/* Location: C:\Users\BSV\AppData\Local\Temp\Rar$DRa6216.20396\Preview\Preview.jar!\net\minecraft\network\play\server\SPacketUpdateHealth.class
* Java compiler version: 8 (52.0)
* JD-Core Version: 1.1.3
*/
|
package com.java.smart_garage.repositories;
import com.java.smart_garage.contracts.repoContracts.ManufacturerRepository;
import com.java.smart_garage.models.Manufacturer;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.query.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.java.smart_garage.exceptions.EntityNotFoundException;
import java.util.List;
@Repository
public class ManufacturerRepositoryImpl implements ManufacturerRepository {
private final SessionFactory sessionFactory;
@Autowired
public ManufacturerRepositoryImpl(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
@Override
public List<Manufacturer> getAllManufacturers() {
try (Session session = sessionFactory.openSession()) {
Query<Manufacturer> query = session.createQuery("from Manufacturer order by manufacturerId", Manufacturer.class);
return query.list();
}
}
@Override
public Manufacturer getById(int id){
try (Session session = sessionFactory.openSession()) {
Manufacturer manufacturer = session.get(Manufacturer.class, id);
if(manufacturer==null){
throw new EntityNotFoundException("Manufacturer", "id", id);
}
return manufacturer;
}
}
@Override
public Manufacturer getByName(String name){
try (Session session = sessionFactory.openSession()){
Query<Manufacturer> query = session.createQuery("from Manufacturer where manufacturerName like concat('%', :name, '%')",
Manufacturer.class);
query.setParameter("name", name);
List<Manufacturer> result = query.list();
if (result.size()==0){
throw new EntityNotFoundException("Manufacturer", "name", name);
}
return result.get(0);
}
}
@Override
public Manufacturer create(Manufacturer manufacturer){
try (Session session = sessionFactory.openSession()) {
session.save(manufacturer);
}
return manufacturer;
}
@Override
public void delete(int id){
try(Session session = sessionFactory.openSession()){
session.beginTransaction();
session.delete(session.get(Manufacturer.class,id));
session.getTransaction().commit();
}
}
}
|
package com.elepy.auth.methods;
import com.elepy.annotations.ElepyConstructor;
import com.elepy.annotations.Inject;
import com.elepy.auth.AuthenticationMethod;
import com.elepy.auth.User;
import com.elepy.auth.UserLoginService;
import com.elepy.http.Request;
import java.util.Optional;
public class BasicAuthenticationMethod implements AuthenticationMethod {
private final UserLoginService userService;
@ElepyConstructor
public BasicAuthenticationMethod(@Inject UserLoginService userService) {
this.userService = userService;
}
public User getUserFromRequest(Request request) {
final Optional<String[]> authorizationOpt = this.basicCredentials(request);
if (authorizationOpt.isEmpty()) {
return null;
}
final String[] authorization = authorizationOpt.get();
final Optional<User> login = userService.login(authorization[0], authorization[1]);
return login.orElse(null);
}
}
|
package com.weboot.book.repository;
import com.weboot.book.model.Item;
import com.weboot.book.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* @author Yaroslav Bondarchuk
* Date: 02.01.2016
* Time: 18:15
*/
public interface UserRepository extends JpaRepository<User, String> {
}
|
package com.example.bilp210_7;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private TextView adetTV,ucretTV;
private Button artirButon,azaltButon,siparisButon;
private int adet = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adetTV=findViewById(R.id.adetTV);
ucretTV=findViewById(R.id.ucretTV);
azaltButon=findViewById(R.id.azaltButon);
artirButon=findViewById(R.id.artirButon);
siparisButon=findViewById(R.id.siparisButon);
azaltButon.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(adet>0)
adet--;
adetTV.setText(""+adet);
ucretTV.setText(adet*20+"TL");
}
});
artirButon.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
adet++;
adetTV.setText(""+adet);
ucretTV.setText(adet*20+"TL");
}
});
siparisButon.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String mesaj="sipariş alındı: "+adet*20+"TL";
Toast.makeText(getApplicationContext(),mesaj,Toast.LENGTH_LONG).show();
ucretTV.setText("0 TL");
adetTV.setText("0");
adet=0;
}
});
}
}
|
public class Gerente implements CalculoAumento{
Funcionario func;
public Gerente(double salario) {
func = new Funcionario();
func.setSalario(salario);
func.setListener(this);
func.novoSalario();
}
@Override
public String toString() {
return "Gerente [" + (func != null ? "func=" + func.getSalario() : "") + "]";
}
@Override
public double CalcularAumento(double salario) {
salario *= 1.2;
System.out.println(salario);
return salario;
}
}
|
/*
* Copyright (c) 2016 名片项目组 All rights reserved.
*/
package com.poetic.emotion;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.os.Build;
import java.lang.reflect.Field;
/**
* <p>Created by poetic on 2016/4/8 14:51 Email: <a href="mailto:dequanking@qq.com">dequanking@qq.com.</a></p>
*/
public class EmotionUtil {
public static String getStringByName(String name, Context context){
try {
Field field = Class.forName("com.poetic.emotion.R$string").getField(name);
int drawableRes = field.getInt(field);
return context.getString(drawableRes);
} catch (Resources.NotFoundException e){
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IllegalAccessException e){
e.printStackTrace();
} catch (NoSuchFieldException e){
e.printStackTrace();
}
return null;
}
public static Drawable getDrawableByName(String name, Context context){
try {
Field field = Class.forName("com.poetic.emotion.R$drawable").getField(name);
int drawableRes = field.getInt(field);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return context.getDrawable(drawableRes);
} else {
return context.getResources().getDrawable(drawableRes);
}
} catch (Resources.NotFoundException e){
e.printStackTrace();
} catch (ClassNotFoundException e){
e.printStackTrace();
} catch (IllegalAccessException e){
e.printStackTrace();
} catch (NoSuchFieldException e){
e.printStackTrace();
}
return null;
}
}
|
package cn.edu.zucc.web.dao;
import cn.edu.zucc.core.feature.test.TestSupport;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import static org.junit.Assert.*;
/**
* Created by zxy on 2016/7/9.
*/
public class UserMapperTest extends TestSupport{
@Autowired
private UserMapper userMapper;
@Test
public void deleteByUserid() throws Exception {
System.out.println(userMapper.deleteByUserid(11));
System.out.println(userMapper.deleteByUserid(10));
System.out.println(userMapper.deleteByUserid(8));
}
@Test
public void insert() throws Exception {
}
@Test
public void selectByKeyword() throws Exception {
}
@Test
public void updateByRecord() throws Exception {
}
@Test
public void authentication() throws Exception {
}
@Test
public void selectPwdByUserno() throws Exception {
}
@Test
public void selectByUserno() throws Exception {
}
@Test
public void selectUsers() throws Exception {
}
}
|
package com.sdk4.boot.controller.user;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sdk4.boot.bo.LoginUser;
import com.sdk4.boot.common.BaseResponse;
import com.sdk4.boot.domain.AdminUser;
import com.sdk4.boot.enums.UserTypeEnum;
import com.sdk4.boot.exception.BaseError;
import com.sdk4.boot.service.AuthService;
import com.sdk4.boot.util.DruidUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
/**
* 用户登录验证及权限信息获取
*
* @author sh
*/
@RequestMapping("/user")
@RestController("BootUserController")
public class UserController {
@Autowired
AuthService authService;
@PostMapping(value = "login", produces = "application/json;charset=utf-8")
public BaseResponse<Map> login(@RequestBody Map<String, String> reqMap, HttpServletRequest request, HttpServletResponse response) {
BaseResponse<Map> ret = new BaseResponse<>();
String type = reqMap.get("type");
String username = reqMap.get("username");
String password = reqMap.get("password");
if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
ret.put(BaseError.MISSING_PARAMETER.getCode(), "登录账号密码不能为空");
} else {
if (StringUtils.isEmpty(type)) {
type = UserTypeEnum.ADMIN_USER.name();
}
// username = type + ":" + username;
UsernamePasswordToken token = new UsernamePasswordToken(username, password);
// token.setRememberMe(true);
try {
Subject subject = SecurityUtils.getSubject();
subject.login(token);
if (subject.isAuthenticated()) {
ret.put(0, "登录成功");
Map data = Maps.newHashMap();
data.put("token", subject.getPrincipals().getRealmNames().iterator().next());
ret.setData(data);
} else {
ret.put(BaseError.USERNAME_OR_PASSWORD_INCORRECT);
}
} catch (IncorrectCredentialsException e) {
ret.put(BaseError.USERNAME_OR_PASSWORD_INCORRECT);
} catch (ExcessiveAttemptsException e) {
ret.put(BaseError.EXCESSIVE_ATTEMPT);
} catch (LockedAccountException e) {
ret.put(BaseError.ACCOUNT_LOCKED);
} catch (DisabledAccountException e) {
ret.put(BaseError.ACCOUNT_DISABLED);
} catch (ExpiredCredentialsException e) {
ret.put(BaseError.ACCOUNT_EXPIRED);
} catch (UnknownAccountException e) {
ret.put(BaseError.USERNAME_OR_PASSWORD_INCORRECT);
} catch (UnauthorizedException e) {
ret.put(BaseError.UNAUTHORIZED);
} catch (AuthenticationException e) {
ret.put(BaseError.USERNAME_OR_PASSWORD_INCORRECT);
} catch (Exception e) {
ret.put(BaseError.USERNAME_OR_PASSWORD_INCORRECT);
}
}
return ret;
}
@RequestMapping(value = "info", produces = "application/json;charset=utf-8")
public BaseResponse<Map> info(HttpServletRequest request, HttpServletResponse response) {
BaseResponse<Map> ret = new BaseResponse<>();
List<String> roles = Lists.newArrayList();
roles.add("default");
roles.add("admin");
Subject subject = SecurityUtils.getSubject();
if (subject != null && subject.isAuthenticated()) {
PrincipalCollection pc = subject.getPrincipals();
if (pc != null && !pc.getRealmNames().isEmpty()) {
ret.put(BaseError.SUCCESS);
Map data = Maps.newHashMap();
String token = pc.getRealmNames().iterator().next();
data.put("token", token);
LoginUser loginUser = authService.getLoginUserFromSession();
if (loginUser != null && loginUser.getUserObject() != null) {
if (loginUser.getUserType() == UserTypeEnum.ADMIN_USER) {
AdminUser adminUser = loginUser.toUserObject();
data.put("id", adminUser.getId());
data.put("name", adminUser.getMobile());
String defaultAvatar = "https://secure.gravatar.com/avatar/default.jpg";
data.put("avatar", defaultAvatar);
data.put("roles", roles);
ret.setData(data);
DruidUtils.setLoginedName(request, adminUser.getMobile());
}
} else {
ret.put(BaseError.NOT_LOGIN);
}
} else {
ret.put(BaseError.NOT_LOGIN);
}
} else {
ret.put(BaseError.NOT_LOGIN);
}
return ret;
}
@ResponseBody
@RequestMapping(value = "logout", produces = "application/json;charset=utf-8")
public BaseResponse logout() {
BaseResponse ret = new BaseResponse();
Subject subject = SecurityUtils.getSubject();
if (subject != null) {
subject.logout();
}
ret.put(BaseError.SUCCESS);
return ret;
}
}
|
/*
* This file is part of PixelCam Mod, licensed under the Apache License, Version 2.0.
*
* Copyright (c) 2016 CrushedPixel <http://crushedpixel.eu>
* Copyright (c) contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.replaymod.pixelcam.path;
import com.replaymod.pixelcam.interpolation.Interpolation;
import com.replaymod.pixelcam.interpolation.InterpolationType;
import com.replaymod.pixelcam.interpolation.LinearInterpolation;
import com.replaymod.pixelcam.interpolation.SplineInterpolation;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class CameraPath {
private final List<Position> points;
private Interpolation<Position> interpolation;
public CameraPath() {
this(new LinkedList<Position>());
}
public CameraPath(List<Position> points) {
this.points = points;
}
public int addPoint(Position position, int index) {
if(index < 0) points.add(position);
else points.add(index, position);
interpolation = null;
if(index < 0) return points.size()-1;
return index;
}
public void clear() {
points.clear();
interpolation = null;
}
public void removePoint(int index) {
points.remove(index);
interpolation = null;
}
public int getPointCount() {
return points.size();
}
public List<Position> getPoints() {
return new ArrayList<>(points);
}
public Position getPoint(int index) {
return points.get(index);
}
public Interpolation<Position> getInterpolation(InterpolationType type) {
if(interpolation == null || (interpolation.getInterpolationType() != type && points.size() > 2)) {
interpolation = (type == InterpolationType.LINEAR || points.size() < 3)
? new LinearInterpolation() : new SplineInterpolation();
for(Position pos : points) {
interpolation.addPoint(pos);
}
interpolation.prepare();
}
return interpolation;
}
public void setPoints(List<Position> points) {
this.points.clear();
this.points.addAll(points);
interpolation = null;
}
}
|
import java.util.*;
public class Array_generic
{
public static <t> void print(t a[])
{
for(t i:a)
{
System.out.println(i+" ");
}
}
public static void main(String ars[])
{
Scanner s=new Scanner(System.in);
System.out.println("Enter size");
int n=s.nextInt();
Integer i[]=new Integer[n];
Double d[]=new Double[n];
String s1[]=new String[n];
System.out.println("Enter Integer value");
for(int j=0;j<n;j++)
{
i[j]=s.nextInt();
}
System.out.println("Enter Double value");
for(int j=0;j<n;j++)
{
d[j]=s.nextDouble();
}
System.out.println("Enter String value");
for(int j=0;j<n;j++)
{
s1[j]=s.next();
}
System.out.println("\nInteger values");
print(i);
System.out.println("\nDouble values");
print(d);
System.out.println("\nString values");
print(s1);
}
}
|
package lintcode;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Random;
import java.util.Set;
public class L657 {
}
class RandomizedSet {
Set set = new HashSet<Integer>();
public RandomizedSet() {
// do intialization if necessary
}
/*
* @param val: a value to the set
* @return: true if the set did not already contain the specified element or false
*/
public boolean insert(int val) {
return set.add(val);
}
/*
* @param val: a value from the set
* @return: true if the set contained the specified element or false
*/
public boolean remove(int val) {
return set.remove(val);
}
/*
* @return: Get a random element from the set
*/
public int getRandom() {
Iterator<Integer> iterator = set.iterator();
Random random = new Random();
random.nextInt();
int pos = (int) (Math.random() * (set.size() - 1));
int i = 0;
while (iterator.hasNext()) {
int value = iterator.next().intValue();
if (i == pos) {
return value;
}
i++;
}
return 0;
}
}
/**
* Your RandomizedSet object will be instantiated and called as such:
* RandomizedSet obj = new RandomizedSet();
* boolean param = obj.insert(val);
* boolean param = obj.remove(val);
* int param = obj.getRandom();
*/
|
package org.usfirst.frc.team1165.robot.commands.auto;
import org.usfirst.frc.team1165.robot.Robot;
import edu.wpi.first.wpilibj.command.Command;
/**
*
*/
public class DriveStraightSpeed extends Command
{
private double mY;
private double mTwist;
public DriveStraightSpeed(double y, double twist)
{
mY = y;
mTwist = twist;
requires(Robot.mDriveTrain);
}
@Override
protected void execute()
{
Robot.mDriveTrain.arcadeDrive(mY, mTwist);
}
@Override
protected boolean isFinished()
{
return false;
}
@Override
protected void end()
{
Robot.mDriveTrain.tankDrive(0, 0);
}
}
|
package blockchain.block.mining;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Hasher {
// Applies sha256 to the given input and returns the hash bytes
public static byte[] applySHA(byte[] input) {
try {
MessageDigest msgDigest = MessageDigest.getInstance("SHA-256");
msgDigest.update(input);
return msgDigest.digest();
} catch (NoSuchAlgorithmException e) {
System.out.println("Hashing algorithm not found");
e.printStackTrace();
}
return null;
}
// Converts the given bytes to a hex string representation
public static String bytesToHexString(byte[] hashBytes) {
StringBuilder hexString = new StringBuilder();
for (byte hashByte : hashBytes) {
// Convert byte to an unsigned value and then convert to a string
String hex = Integer.toHexString(0xFF & hashByte);
// Append a leading 0 if hex value is only one character long (ie. less than 16)
if (hex.length() == 1)
hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
}
}
|
package com.DeGuzmanFamilyAPI.DeGuzmanFamilyAPIBackend.logger;
import java.io.File;
import java.io.IOException;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import javassist.bytecode.stackmap.TypeData.ClassName;
public class AutoTrxLogger {
static boolean append = true;
public final static Logger autoTrxLogger = Logger.getLogger(ClassName.class.getName());
public final static String path = "C:\\EJ-Projects\\DeGUzmanFamilyAPI-Backend\\log\\auto-transaction-logs\\auto-transaction.log";
public static FileHandler autoTrxHandler;
public static void createLog() throws SecurityException, IOException {
File logDirectory = new File("C:\\EJ-Projects\\DeGuzmanFamilyAPI-Backend\\log\\auto-transaction-logs");
if(!logDirectory.exists()) {
logDirectory.mkdirs();
System.out.println("created directory" + " " + logDirectory);
}
autoTrxHandler = new FileHandler(path, append);
autoTrxLogger.addHandler(autoTrxHandler);
System.out.println("Created log directory" + " " + logDirectory);
}
}
|
package tripleplacement.jobs;
import java.io.IOException;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import com.google.common.collect.Lists;
import common.Config;
public class IncludeTypePredicate {
public static class GraphMapper extends
Mapper<LongWritable, Text, Text, Text> {
public void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
String line = value.toString();
String[] data = StringUtils
.split(line, Config.partitionIdVerticesSprator);
String partitionID = StringUtils.trim(data[1]);
String subject = StringUtils.split(data[0], Config.VerticesSeparator)[0];
String predicate = StringUtils.split(data[0], Config.VerticesSeparator)[1];
String object = StringUtils.split(data[0], Config.VerticesSeparator)[2];
context.write(new Text(subject), new Text(predicate
+ Config.VerticesSeparator + object
+ Config.partitionIdVerticesSprator + partitionID));
}
}
public static class RDFMapper extends Mapper<LongWritable, Text, Text, Text> {
public void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
String line = value.toString();
String[] data = StringUtils.split(line, Config.VerticesSeparator);
String subject = data[0];
String predicate = data[1];
String object = data[2];
if (StringUtils.equalsIgnoreCase(predicate, Config.typePredicate)) {
context.write(new Text(subject), new Text(predicate
+ Config.VerticesSeparator + object));
}
}
}
public static class Red extends Reducer<Text, Text, Text, NullWritable> {
public void reduce(Text key, Iterable<Text> values, Context context)
throws IOException, InterruptedException {
String originalPertition = StringUtils.EMPTY;
Text outValue = new Text();
List<Text> valuesList = Lists.newLinkedList(values);
for (Text value : valuesList) {
if (StringUtils.contains(value.toString(),
Config.partitionIdVerticesSprator)) {
if (StringUtils.equalsIgnoreCase(
StringUtils.split(value.toString(), Config.VerticesSeparator)[0],
Config.isOwnedPredicate)) {
originalPertition = StringUtils.split(value.toString(),
Config.partitionIdVerticesSprator)[1];
}
}
outValue.set(key.toString() + Config.VerticesSeparator
+ value.toString());
context.write(outValue, null);
}
for (Text value : valuesList) {
if (!StringUtils.contains(value.toString(),
Config.partitionIdVerticesSprator)) {
outValue.set(key.toString() + Config.VerticesSeparator
+ value.toString() + Config.partitionIdVerticesSprator
+ originalPertition);
context.write(outValue, null);
}
}
}
}
}
|
package com.tutorial.inheritance;
import com.tutorial.inheritance.employee.Employee;
import com.tutorial.inheritance.employee.it.DotNetProgrammer;
import com.tutorial.inheritance.employee.it.JavaProgrammer;
import com.tutorial.inheritance.employee.network.NetWorkingEmployee;
public class HiringCompany {
public static void main(String[] args) {
/*Employee emp = new Employee("Archna",300,"");
System.out.println(emp.getId());*/
// ITEmployee itemp = new JavaProgrammer("Pushkar",400);
// itemp.tieColor();
// itemp.algorithmSkills();
/*Employee netEmp = new NetWorkingEmployee("Sudheer",500);
netEmp.tieColor();*/
/*ITEmployee itemp = new ITEmployee("Pushkar",400);
System.out.println(itemp.getId());*/
// ITEmployee program = new JavaProgrammer("Kavitha",89);
// program.jvmConcepts();
/*Employee emp = getEmployee("Debashis",45,".net");
emp.meetingAgenda();
if(emp instanceof JavaProgrammer) {
JavaProgrammer javaProg = (JavaProgrammer)emp;
javaProg.jvmConcepts();
}else if(emp instanceof DotNetProgrammer) {
DotNetProgrammer javaProg = (DotNetProgrammer)emp;
javaProg.microsoftProgramming();
}*/
NetWorkingEmployee networkEmp = new NetWorkingEmployee("Ishtiaq",56);
networkEmp.meetingAgenda();
networkEmp.getEmpType();
}
public static Employee getEmployee(String name , int id, String type){
if("java".equals(type))
return new JavaProgrammer(name, id);
else if(".net".equals(type)) {
return new DotNetProgrammer(name, id);
}
return null;
}
}
|
package com.hb.rssai.adapter;
import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
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.hb.rssai.R;
import com.hb.rssai.bean.ResInformation;
import com.hb.rssai.constants.Constant;
import com.hb.rssai.util.DateUtil;
import com.hb.rssai.util.HttpLoadImg;
import com.hb.rssai.util.SharedPreferencesUtil;
import com.hb.rssai.util.StringUtil;
import com.hb.rssai.util.T;
import com.hb.rssai.view.common.ContentActivity;
import com.hb.rssai.view.common.RichTextActivity;
import com.hb.rssai.view.subscription.SourceCardActivity;
import java.net.URLDecoder;
import java.util.List;
/**
* Created by Administrator on 2017/7/6.
*/
/**
* Created by Administrator on 2016/12/10 0010.
*/
public class InfoTestAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private Context mContext;
private List<ResInformation.RetObjBean.RowsBean> rssList;
private LayoutInflater layoutInflater;
private String longDatePat = "yyyy-MM-dd HH:mm:ss";
private String[] images = null;
private boolean isNoImageMode = true;
private static final int TYPE_NO_IMAGE = 1;
private static final int TYPE_ONE_IMAGE = 2;
private static final int TYPE_THREE_IMAGE = 3;
private static final int TYPE_FOUR = 4;//分割线
private String title;
private ResInformation.RetObjBean.RowsBean rowsBean;
public InfoTestAdapter(Context mContext, List<ResInformation.RetObjBean.RowsBean> rssList) {
this.mContext = mContext;
this.rssList = rssList;
layoutInflater = LayoutInflater.from(mContext);
init();
}
public void init() {
isNoImageMode = SharedPreferencesUtil.getBoolean(mContext, Constant.KEY_IS_NO_IMAGE_MODE, false);
}
@Override
public int getItemViewType(int position) {
if (null != rssList && null != rssList.get(position) && rssList.get(position).getViewType() == 4) {
return TYPE_FOUR;
}
if (null == rssList || null == rssList.get(position) || TextUtils.isEmpty(rssList.get(position).getImageUrls())) {
return TYPE_NO_IMAGE;
}
String[] images = rssList.get(position).getImageUrls().split(",http");
if (images.length >= 3) {
return TYPE_THREE_IMAGE;
} else {
return TYPE_ONE_IMAGE;
}
}
@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == TYPE_NO_IMAGE) {
View view = layoutInflater.inflate(R.layout.include_item_no_image, parent, false);
return new NoImageViewHolder(view);
} else if (viewType == TYPE_ONE_IMAGE) {
View view = layoutInflater.inflate(R.layout.include_item_one_image, parent, false);
return new OneImageViewHolder(view);
} else if (viewType == TYPE_THREE_IMAGE) {
View view = layoutInflater.inflate(R.layout.include_item_three_image, parent, false);
return new ThreeImageViewHolder(view);
} else if (viewType == TYPE_FOUR) {
View view = layoutInflater.inflate(R.layout.include_item_four, parent, false);
return new BarViewHolder(view);
}
return null;
}
@Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position) {
String time = "";
rowsBean = rssList.get(position);
if (null == rowsBean) {
return;
}
title = rowsBean.getTitle() != null ? rowsBean.getTitle() : "";
try {
time = DateUtil.showDate(Constant.sdf.parse(rowsBean.getPubTime()), longDatePat);
} catch (Exception e) {
e.printStackTrace();
}
if (holder instanceof NoImageViewHolder) {
((NoImageViewHolder) holder).item_na_title.setText(title);
((NoImageViewHolder) holder).item_na_layout.setOnClickListener(v -> click(position));
} else if (holder instanceof OneImageViewHolder) {
((OneImageViewHolder) holder).item_na_title.setText(title);
if (isNoImageMode) {
((OneImageViewHolder) holder).item_na_img.setVisibility(View.GONE);
} else {
((OneImageViewHolder) holder).item_na_img.setVisibility(View.VISIBLE);
images = TextUtils.isEmpty(rowsBean.getImageUrls()) ? null : rowsBean.getImageUrls().split(",http");
if (null != images && images.length > 0) {
System.out.println("==>"+images[0]);
String url = URLDecoder.decode(images[0]);
//TODO 过滤网址
HttpLoadImg.loadRoundImg(mContext, StringUtil.filterImage(url), ((OneImageViewHolder) holder).item_na_img);
}
}
((OneImageViewHolder) holder).item_na_layout.setOnClickListener(v -> click(position));
} else if (holder instanceof ThreeImageViewHolder) {
((ThreeImageViewHolder) holder).item_na_title.setText(title);
if (isNoImageMode) {
((ThreeImageViewHolder) holder).item_na_image_group.setVisibility(View.GONE);
} else {
((ThreeImageViewHolder) holder).item_na_image_group.setVisibility(View.VISIBLE);
images = TextUtils.isEmpty(rowsBean.getImageUrls()) ? null : rowsBean.getImageUrls().split(",http");
System.out.println("==>"+images[0]);
System.out.println("==>"+"http" + images[1]);
System.out.println("==>"+"http" + images[2]);
HttpLoadImg.loadRoundImg(mContext, images[0], ((ThreeImageViewHolder) holder).item_na_image_a);
HttpLoadImg.loadRoundImg(mContext, "http" + images[1], ((ThreeImageViewHolder) holder).item_na_image_b);
HttpLoadImg.loadRoundImg(mContext, "http" + images[2], ((ThreeImageViewHolder) holder).item_na_image_c);
}
((ThreeImageViewHolder) holder).item_na_layout.setOnClickListener(v -> click(position));
} else if (holder instanceof BarViewHolder) {
((BarViewHolder) holder).item_na_where_from.setText(rowsBean.getWhereFrom());
((BarViewHolder) holder).item_na_time.setText(time);
HttpLoadImg.loadCircleImg(mContext, rowsBean.getSubscribeImg(), ((BarViewHolder) holder).item_iv_logo);
((BarViewHolder) holder).item_iv_logo.setOnClickListener(v -> {
Intent intent = new Intent(mContext, SourceCardActivity.class);
intent.putExtra(SourceCardActivity.KEY_TITLE, rssList.get(position).getWhereFrom());
intent.putExtra(SourceCardActivity.KEY_SUBSCRIBE_ID, rssList.get(position).getSubscribeId());
intent.putExtra(SourceCardActivity.KEY_IMAGE, rssList.get(position).getSubscribeImg());
mContext.startActivity(intent);
});
((BarViewHolder) holder).item_na_where_from.setOnClickListener(v -> {
Intent intent = new Intent(mContext, SourceCardActivity.class);
intent.putExtra(SourceCardActivity.KEY_TITLE, rssList.get(position).getWhereFrom());
intent.putExtra(SourceCardActivity.KEY_SUBSCRIBE_ID, rssList.get(position).getSubscribeId());
intent.putExtra(SourceCardActivity.KEY_IMAGE, rssList.get(position).getSubscribeImg());
mContext.startActivity(intent);
});
}
}
private void click(int position) {
if (rssList.size() > 0) {
ResInformation.RetObjBean.RowsBean rowsBean = rssList.get(position);
String data = rowsBean.getLink();//获取编辑框里面的文本内容
if (!TextUtils.isEmpty(data) || !TextUtils.isEmpty(rowsBean.getAbstractContent())) {
Intent intent = new Intent(mContext, RichTextActivity.class);//创建Intent对象
intent.putExtra(ContentActivity.KEY_TITLE, rowsBean.getTitle());
intent.putExtra(ContentActivity.KEY_URL, rowsBean.getLink());
intent.putExtra(ContentActivity.KEY_INFORMATION_ID, rowsBean.getId());
intent.putExtra("pubDate", rowsBean.getPubTime());
intent.putExtra("whereFrom", rowsBean.getWhereFrom());
intent.putExtra("abstractContent", rowsBean.getAbstractContent());
intent.putExtra("clickGood", rowsBean.getClickGood());
intent.putExtra("clickNotGood", rowsBean.getClickNotGood());
intent.putExtra("id", rowsBean.getId());
intent.putExtra("subscribeImg", rowsBean.getSubscribeImg());
intent.putExtra("count", rowsBean.getCount());
mContext.startActivity(intent);//将Intent传递给Activity
} else {
T.ShowToast(mContext, "链接错误,无法跳转!");
}
} else {
T.ShowToast(mContext, "请等待数据加载完成!");
}
}
@Override
public int getItemCount() {
return rssList == null ? 0 : rssList.size();
}
class BarViewHolder extends RecyclerView.ViewHolder {
TextView item_na_where_from;
TextView item_na_time;
ImageView item_iv_logo;
public BarViewHolder(View itemView) {
super(itemView);
item_na_where_from = itemView.findViewById(R.id.item_na_where_from);
item_na_time = itemView.findViewById(R.id.item_na_time);
item_iv_logo = itemView.findViewById(R.id.item_iv_logo);
}
}
class NoImageViewHolder extends RecyclerView.ViewHolder {
TextView item_na_title;
TextView item_na_where_from;
TextView item_na_time;
RelativeLayout item_na_layout;
ImageView item_iv_logo;
public NoImageViewHolder(View itemView) {
super(itemView);
item_na_title = itemView.findViewById(R.id.item_na_title);
item_na_where_from = itemView.findViewById(R.id.item_na_where_from);
item_na_time = itemView.findViewById(R.id.item_na_time);
item_iv_logo = itemView.findViewById(R.id.item_iv_logo);
item_na_layout = itemView.findViewById(R.id.item_na_layout);
}
}
class OneImageViewHolder extends RecyclerView.ViewHolder {
ImageView item_na_img;
TextView item_na_title;
TextView item_na_time;
TextView item_na_where_from;
ImageView item_iv_logo;
LinearLayout item_na_layout;
public OneImageViewHolder(View itemView) {
super(itemView);
item_na_title = itemView.findViewById(R.id.item_na_title);
item_na_time = itemView.findViewById(R.id.item_na_time);
item_na_where_from = itemView.findViewById(R.id.item_na_where_from);
item_na_img = itemView.findViewById(R.id.item_na_img);
item_iv_logo = itemView.findViewById(R.id.item_iv_logo);
item_na_layout = itemView.findViewById(R.id.item_na_layout);
}
}
class ThreeImageViewHolder extends RecyclerView.ViewHolder {
TextView item_na_where_from;
TextView item_na_time;
TextView item_na_title;
ImageView item_na_image_a;
ImageView item_na_image_b;
ImageView item_na_image_c;
ImageView item_iv_logo;
LinearLayout item_na_layout;
LinearLayout item_na_image_group;
public ThreeImageViewHolder(View itemView) {
super(itemView);
item_na_where_from = itemView.findViewById(R.id.item_na_where_from);
item_na_time = itemView.findViewById(R.id.item_na_time);
item_na_title = itemView.findViewById(R.id.item_na_title);
item_na_image_a = itemView.findViewById(R.id.item_na_image_a);
item_na_image_b = itemView.findViewById(R.id.item_na_image_b);
item_na_image_c = itemView.findViewById(R.id.item_na_image_c);
item_iv_logo = itemView.findViewById(R.id.item_iv_logo);
item_na_layout = itemView.findViewById(R.id.item_na_layout);
item_na_image_group = itemView.findViewById(R.id.item_na_image_group);
}
}
}
|
package vectorAndStack;
//import java.util.Stack;
public class VectorAndStack {
public static void main(String[] args) throws Exception {
MyStack<Integer> stack = new MyStack<>();
stack.push(12);
stack.push(15);
stack.push(35);
int popped = stack.pop();
System.out.println(popped+" popped");
int peeked = stack.peek();
System.out.println(peeked+" peek");
}
}
|
package presentacion.vistas.departamento;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import negocio.departamento.TransferDepartamento;
import presentacion.contexto.Contexto;
import presentacion.controlador.appController.Controller;
import presentacion.eventos.EventosDepartamento;
import presentacion.eventos.EventosLibreria;
import presentacion.eventos.EventosMenu;
import presentacion.vistas.gui.VistaPrincipal;
public class VistaDepartamento extends JFrame implements VistaPrincipal {
private static final long serialVersionUID = -4344608606248648803L;
protected Object altaDepartamento;
protected Object bajaDepartamento;
protected Object modificarDepartamento;
protected Object mostrarDepartamento;
protected Object listarDepartamentos;
protected Controller controller;
private JTable jTable;
private JLabel jLabel;
private DefaultTableModel defaultTableModel;
private TransferDepartamento buscarDepartamento;
private boolean libreriaExistente;
public VistaDepartamento() {
vista();
}
@Override
public void actualizar(final Contexto contexto) {
limpiarJLabel();
limpiarJTable();
switch (contexto.getEvento()) {
case EventosDepartamento.ALTA_DEPARTAMENTO_OK:
jLabel.setText((String) contexto.getDatos());
jLabel.setOpaque(true);
jLabel.setBackground(new Color(91, 186, 86));
break;
case EventosDepartamento.ALTA_DEPARTAMENTO_KO:
jLabel.setText((String) contexto.getDatos());
jLabel.setOpaque(true);
jLabel.setBackground(new Color(218, 63, 54));
break;
case EventosDepartamento.BAJA_DEPARTAMENTO_OK:
jLabel.setText((String) contexto.getDatos());
jLabel.setOpaque(true);
jLabel.setBackground(new Color(91, 186, 86));
break;
case EventosDepartamento.BAJA_DEPARTAMENTO_KO:
jLabel.setText((String) contexto.getDatos());
jLabel.setOpaque(true);
jLabel.setBackground(new Color(218, 63, 54));
break;
case EventosDepartamento.MODIFICAR_DEPARTAMENTO_OK: {
jLabel.setText((String) contexto.getDatos());
jLabel.setOpaque(true);
jLabel.setBackground(new Color(91, 186, 86));
}
;
break;
case EventosDepartamento.MODIFICAR_DEPARTAMENTO_KO: {
final String texto = (String) contexto.getDatos();
jLabel.setText(texto);
jLabel.setOpaque(true);
jLabel.setBackground(new Color(218, 63, 54));
}
;
break;
case EventosLibreria.BUSCAR_LIBRERIA_KO:{
final String texto = (String) contexto.getDatos();
jLabel.setText(texto);
jLabel.setOpaque(true);
jLabel.setBackground(new Color(218, 63, 54));
this.libreriaExistente = false;
} ;
break;
case EventosDepartamento.MOSTRAR_DEPARTAMENTO_OK: {
final TransferDepartamento transferDepartamento =
(TransferDepartamento) contexto.getDatos();
defaultTableModel
.addRow(new Object[] { transferDepartamento.getId(), transferDepartamento.getNombre(),
transferDepartamento.getCantidadEmpleados(), transferDepartamento.getLibreria(), transferDepartamento.getActivo() });
}
;
break;
case EventosDepartamento.MOSTRAR_DEPARTAMENTO_KO: {
final String texto = (String) contexto.getDatos();
jLabel.setText(texto);
jLabel.setOpaque(true);
jLabel.setBackground(new Color(218, 63, 54));
}
;
break;
case EventosDepartamento.LISTAR_DEPARTAMENTOS_OK: {
@SuppressWarnings("unchecked")
final List<TransferDepartamento> lista = (List<TransferDepartamento>) contexto.getDatos();
for (final TransferDepartamento transferDepartamento : lista) {
defaultTableModel
.addRow(new Object[] { transferDepartamento.getId(), transferDepartamento.getNombre(),
transferDepartamento.getCantidadEmpleados(), transferDepartamento.getLibreria(), transferDepartamento.getActivo() });
}
}
;
break;
case EventosDepartamento.LISTAR_DEPARTAMENTOS_KO: {
final String texto = (String) contexto.getDatos();
jLabel.setText(texto);
jLabel.setOpaque(true);
jLabel.setBackground(new Color(218, 63, 54));
}
;
break;
case EventosDepartamento.BUSCAR_DEPARTAMENTO_OK: {
buscarDepartamento = (TransferDepartamento) contexto.getDatos();
}
;
break;
case EventosDepartamento.BUSCAR_DEPARTAMENTO_KO: {
final String texto = (String) contexto.getDatos();
jLabel.setText(texto);
jLabel.setOpaque(true);
jLabel.setBackground(new Color(218, 63, 54));
}
;
break;
}
}
public JButton crearBoton(final String Path, final Color color) {
final JButton boton = new JButton();
boton.setPreferredSize(new Dimension(136, 61));
boton.setBackground(color);
boton.setBorder(null);
boton.setFocusPainted(false);
boton.setIcon(new ImageIcon(Path));
return boton;
}
public JButton crearBotonMenu(final String nombre) {
final JButton boton = new JButton(nombre);
boton.setFocusPainted(false);
boton.setBorderPainted(false);
boton.setFont(new Font("Arial", Font.PLAIN, 18));
boton.setBackground(new Color(255, 255, 255));
boton.setMaximumSize(new Dimension(170, 50));
return boton;
}
public JButton crearBotonSalir() {
final JButton boton = new JButton("X");
boton.setFocusPainted(false);
boton.setBorder(null);
boton.setContentAreaFilled(false);
boton.setBorderPainted(false);
boton.setPreferredSize(new Dimension(30, 30));
boton.setFont(new Font("Corbel", Font.BOLD, 20));
boton.setForeground(new Color(110, 120, 140));
boton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
final int confirmacion = JOptionPane.showConfirmDialog(null, "¿Desea cerrar el programa?",
"Salir", JOptionPane.YES_NO_OPTION);
if (confirmacion == JOptionPane.YES_OPTION) {
System.exit(0);
}
}
});
return boton;
}
public void limpiarJLabel() {
jLabel.setText(" ");
jLabel.setOpaque(false);
}
public void limpiarJTable() {
for (int i = defaultTableModel.getRowCount() - 1; i >= 0; i--) {
defaultTableModel.removeRow(i);
}
}
private void vista() {
setSize(1080, 720);
setLocationRelativeTo(null);
setResizable(false);
setUndecorated(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
final JPanel fondo = new JPanel();
final JPanel barra = new JPanel();
final JPanel panelMenuBoton = new JPanel();
final JPanel panelSalir = new JPanel();
final JPanel panelBotones = new JPanel();
final JPanel panelTabla = new JPanel();
final JPanel panelMensaje = new JPanel();
jLabel = new JLabel(" ");
jLabel.setFont(new Font("Arial", Font.PLAIN, 18));
jLabel.setForeground(new Color(255, 255, 255));
final JLabel modulo = new JLabel(" > DEPARTAMENTO");
modulo.setFont(new Font("Arial", Font.PLAIN, 18));
modulo.setForeground(new Color(255, 255, 255));
barra.setBackground(new Color(66, 86, 98));
panelMenuBoton.setBackground(new Color(66, 86, 98));
panelSalir.setBackground(new Color(66, 86, 98));
fondo.setBackground(new Color(225, 225, 225));
panelBotones.setBackground(new Color(125, 125, 125));
barra.setLayout(new BorderLayout());
fondo.setLayout(new BorderLayout());
panelTabla.setLayout(new FlowLayout(FlowLayout.CENTER, 25, 25));
panelMensaje.setLayout(new FlowLayout(FlowLayout.CENTER, 25, 25));
panelBotones.setLayout(new FlowLayout(FlowLayout.CENTER, 15, 20));
// Creacion del boton de menu
final JButton menuBoton = crearBotonMenu("MENÚ");
menuBoton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
dispose();
final Contexto contexto = new Contexto(EventosMenu.MOSTRAR_MENU_VISTA, null);
Controller.getInstance().handleRequest(contexto);
}
});
final JButton salir = crearBotonSalir();
// --------------------------------
panelMenuBoton.add(menuBoton);
panelMenuBoton.add(modulo);
panelSalir.add(salir);
barra.add(panelMenuBoton, BorderLayout.WEST);
barra.add(panelSalir, BorderLayout.EAST);
// Creacion de la tabla.
final String[] nombreColummnas = { "ID", "Nombre", "CantidadEmpleados", "Libreria", "Activo" };
defaultTableModel = new DefaultTableModel(null, nombreColummnas);
jTable = new JTable(defaultTableModel);
jTable.setBackground(new Color(255,255,255));
jTable.getTableHeader().setFont(new Font("Segoe UI", Font.BOLD,14));
jTable.getTableHeader().setOpaque(false);
jTable.getTableHeader().setBackground(Color.LIGHT_GRAY);
jTable.getTableHeader().setForeground(new Color(255, 255, 255));
jTable.setPreferredSize(new Dimension(800, 400));
final JScrollPane scroll = new JScrollPane(jTable);
panelTabla.add(scroll);
// -----------------------
panelMensaje.add(jLabel);
fondo.add(panelTabla, BorderLayout.CENTER);
fondo.add(panelMensaje, BorderLayout.SOUTH);
// Panel de botones.
final JButton altaBoton = crearBoton(
getClass().getClassLoader().getResource("iconos/departamento/ALTA_DEPARTAMENTO.png").getPath(),
new Color(255, 255, 255));
altaBoton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
final JTextField nombre = new JTextField();
final JTextField cantidadEmpleados = new JTextField();
final JTextField libreria = new JTextField();
final JCheckBox activoField = new JCheckBox();
final Object[] mensaje = { "Nombre:", nombre, "CantidadEmpleados:", cantidadEmpleados,
"Libreria:", libreria, "Activo:", activoField };
final int opcion = JOptionPane.showConfirmDialog(null, mensaje, "ALTA DEPARTAMENTO",
JOptionPane.OK_CANCEL_OPTION);
if (opcion == JOptionPane.OK_OPTION) {
try {
if (nombre.getText() != null && cantidadEmpleados.getText() != null
&& libreria.getText() != null && activoField.getText() != null
&& !nombre.getText().equalsIgnoreCase("")
&& !cantidadEmpleados.getText().equalsIgnoreCase("")
&& !libreria.getText().equalsIgnoreCase("")) {
TransferDepartamento transferDepartamento = new TransferDepartamento();
transferDepartamento.setNombre(nombre.getText());
transferDepartamento
.setCantidadEmpleados(Integer.valueOf(cantidadEmpleados.getText()));
transferDepartamento.setLibreria(Integer.valueOf(libreria.getText()));
transferDepartamento.setActivo(activoField.isSelected());
final Contexto contexto =
new Contexto(EventosDepartamento.ALTA_DEPARTAMENTO, transferDepartamento);
Controller.getInstance().handleRequest(contexto);
} else {
JOptionPane.showMessageDialog(null, "Datos introducidos incorrectos.",
"Mensaje de error", JOptionPane.WARNING_MESSAGE);
}
} catch (final NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "Datos introducidos incorrectos.",
"Mensaje de error", JOptionPane.WARNING_MESSAGE);
}
}
}
});
panelBotones.add(altaBoton);
final JButton bajasBoton = crearBoton(
getClass().getClassLoader().getResource("iconos/departamento/BAJA_DEPARTAMENTO.png").getPath(),
new Color(255, 255, 255));
bajasBoton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
final String idString = JOptionPane.showInputDialog(null, "Introduce ID:",
"BAJA DEPARTAMENTO", JOptionPane.QUESTION_MESSAGE);
try {
if (idString != null) {
final int id = Integer.parseInt(idString);
final Contexto contexto = new Contexto(EventosDepartamento.BAJA_DEPARTAMENTO, id);
Controller.getInstance().handleRequest(contexto);
}
} catch (final NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "ID introducido incorrecto.", "Mensaje de error",
JOptionPane.WARNING_MESSAGE);
}
}
});
panelBotones.add(bajasBoton);
final JButton editarBoton = crearBoton(
getClass().getClassLoader().getResource("iconos/departamento/MODIFICAR_DEPARTAMENTO.png").getPath(),new Color(255, 255, 255));
editarBoton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
final String idString = JOptionPane.showInputDialog(null, "Introduce ID:",
"BUSCAR DEPARTAMENTO", JOptionPane.QUESTION_MESSAGE);
try {
if (idString != null) {
final int id = Integer.parseInt(idString);
final Contexto contexto = new Contexto(EventosDepartamento.BUSCAR_DEPARTAMENTO, id);
Controller.getInstance().handleRequest(contexto);
}
}
catch (final NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "ID introducido incorrecto.", "Mensaje de error",
JOptionPane.WARNING_MESSAGE);
}
if (buscarDepartamento != null) {
final JTextField nombreField =
new JTextField(String.valueOf(buscarDepartamento.getNombre()));
final JTextField cantidadEmpleadosField =
new JTextField(String.valueOf(buscarDepartamento.getCantidadEmpleados()));
final JTextField libreriaField = new
JTextField(String.valueOf(buscarDepartamento.getLibreria()));
final JCheckBox activoField = new JCheckBox();
activoField.setSelected(buscarDepartamento.getActivo());
final Object[] mensaje = { "Nombre:", nombreField, "CantidadEmpleados:",
cantidadEmpleadosField, "Libreria:", libreriaField, "Activo:", activoField };
final int opcion = JOptionPane.showConfirmDialog(null, mensaje, "MODIFICAR DEPARTAMENTO",
JOptionPane.OK_CANCEL_OPTION);
if (opcion == JOptionPane.OK_OPTION) {
try {
if (nombreField.getText() != null && activoField.getText() != null) {
final TransferDepartamento transferDepartamento = new TransferDepartamento();
transferDepartamento.setId(buscarDepartamento.getId());
transferDepartamento.setNombre(nombreField.getText());
transferDepartamento
.setCantidadEmpleados(Integer.valueOf(cantidadEmpleadosField.getText()));
transferDepartamento.setLibreria(Integer.valueOf(libreriaField.getText()));
transferDepartamento.setActivo(activoField.isSelected());
libreriaExistente = true;
if (transferDepartamento.getLibreria() != null) {
final int id = transferDepartamento.getLibreria();
final Contexto contexte = new Contexto(EventosLibreria.BUSCAR_LIBRERIA, id);
Controller.getInstance().handleRequest(contexte);
if(contexte.getEvento() == EventosLibreria.BUSCAR_LIBRERIA_KO){
libreriaExistente = false;
}
}
if( libreriaExistente ){ final Contexto contexto =
new Contexto(EventosDepartamento.MODIFICAR_DEPARTAMENTO, transferDepartamento);
Controller.getInstance().handleRequest(contexto);
}
}
} catch (final NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "Datos introducidos incorrectos.",
"Mensaje de error", JOptionPane.WARNING_MESSAGE);
}
}
buscarDepartamento = null;
}
}
});
panelBotones.add(editarBoton);
final JButton mostrarBoton = crearBoton(
getClass().getClassLoader().getResource("iconos/departamento/MOSTRAR_DEPARTAMENTO.png").getPath(),
new Color(255, 255, 255));
mostrarBoton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
final String idString = JOptionPane.showInputDialog(null, "Introduce ID:",
"MOSTRAR DEPARTAMENTO", JOptionPane.QUESTION_MESSAGE);
try {
if (idString != null) {
final int id = Integer.parseInt(idString);
final Contexto contexto = new Contexto(EventosDepartamento.MOSTRAR_DEPARTAMENTO, id);
Controller.getInstance().handleRequest(contexto);
}
} catch (final NumberFormatException ex) {
JOptionPane.showMessageDialog(null, "ID introducido incorrecto.", "Mensaje de error",
JOptionPane.WARNING_MESSAGE);
}
}
});
panelBotones.add(mostrarBoton);
final JButton listarBoton = crearBoton(
getClass().getClassLoader().getResource("iconos/departamento/LISTAR_DEPARTAMENTOS.png").getPath(),
new Color(255, 255, 255));
listarBoton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
final Contexto contexto = new Contexto(EventosDepartamento.LISTAR_DEPARTAMENTOS, null);
Controller.getInstance().handleRequest(contexto);
}
});
panelBotones.add(listarBoton);
final JButton asignarMaterialDeOficina = crearBoton(
getClass().getClassLoader().getResource("iconos/departamento/ASIGNAR_MATERIAL_OFICINA.png").getPath(),
new Color(255, 255, 255));
listarBoton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
final Contexto contexto = new Contexto(EventosDepartamento.ASIGNAR_MATERIAL_OFICINA, null);
Controller.getInstance().handleRequest(contexto);
}
});
panelBotones.add(asignarMaterialDeOficina);
// Aniadimos todos los paneles al JFrame.
add(barra, BorderLayout.NORTH);
add(fondo, BorderLayout.CENTER);
add(panelBotones, BorderLayout.SOUTH);
setVisible(true);
}
}
|
package jdbchomework.dao.jdbc;
import jdbchomework.dao.model.SkillsDao;
import jdbchomework.entity.Skill;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
public class SkillsJdbcDao extends AbstractJdbcDao<Skill> implements SkillsDao {
public SkillsJdbcDao(Connection connection, String table) {
super(connection, table);
}
@Override
protected Skill createEntity(ResultSet resultSet) throws SQLException {
return new Skill(resultSet.getInt("id"), resultSet.getString("name"));
}
}
|
package com.imesne.office.excel.read;
import com.imesne.office.excel.model.ExcelRange;
import com.imesne.office.excel.utils.ExcelKitUtils;
import com.imesne.office.excel.validation.CellValueValidator;
import java.util.ArrayList;
import java.util.List;
/**
* excel工具类配置
* <p>
* Created by liyd on 17/7/3.
*/
public class ExcelReaderConfig {
private ExcelBookReader excelBookReader;
private ExcelSheetReader excelSheetReader;
private ExcelRowReader excelRowReader;
private ExcelCellReader excelCellReader;
/**
* 首行是否标题
*/
private boolean isFirstRowTitle;
private List<CellValueValidator> cellValueValidators;
private List<ExcelRange> excelRanges;
private ExcelReadProcessor excelReadProcessor;
public ExcelReaderConfig() {
this.excelBookReader = new ExcelBookReaderImpl();
this.excelSheetReader = new ExcelSheetReaderImpl();
this.excelRowReader = new ExcelRowReaderImpl();
this.excelCellReader = new ExcelCellReaderImpl();
excelRanges = new ArrayList<>();
cellValueValidators = new ArrayList<>();
this.isFirstRowTitle = true;
}
/**
* 添加读取范围
*
* @param excelRange
*/
public void addRange(ExcelRange excelRange) {
excelRanges.add(excelRange);
}
/**
* 添加读取单元格
*
* @param sheetNum
* @param x 行
* @param y 列
*/
public void addRangeCell(int sheetNum, int x, String y) {
int yNum = ExcelKitUtils.columnToNum(y);
addRangeCell(sheetNum, x, yNum);
}
/**
* 添加读取单元格
*
* @param sheetNum
* @param x 行
* @param y 列
*/
public void addRangeCell(int sheetNum, int x, int y) {
ExcelRange range = ExcelRange.builder()
.sheetNum(sheetNum)
.beginRowNum(x)
.endRowNum(x)
.beginCellNum(y)
.endCellNum(y)
.build();
excelRanges.add(range);
}
public void addCellValueValidator(CellValueValidator cellValueValidator) {
this.cellValueValidators.add(cellValueValidator);
}
public ExcelBookReader getExcelBookReader() {
initReader(excelBookReader);
return excelBookReader;
}
public ExcelSheetReader getExcelSheetReader() {
initReader(excelSheetReader);
return excelSheetReader;
}
public ExcelRowReader getExcelRowReader() {
initReader(excelRowReader);
return excelRowReader;
}
public ExcelCellReader getExcelCellReader() {
initReader(excelCellReader);
return excelCellReader;
}
public List<CellValueValidator> getCellValueValidators() {
return cellValueValidators;
}
public void setExcelBookReader(ExcelBookReader excelBookReader) {
this.excelBookReader = excelBookReader;
}
public void setExcelSheetReader(ExcelSheetReader excelSheetReader) {
this.excelSheetReader = excelSheetReader;
}
public void setExcelRowReader(ExcelRowReader excelRowReader) {
this.excelRowReader = excelRowReader;
}
public void setExcelCellReader(ExcelCellReader excelCellReader) {
this.excelCellReader = excelCellReader;
}
public boolean isFirstRowTitle() {
return isFirstRowTitle;
}
public void setFirstRowTitle(boolean firstRowTitle) {
isFirstRowTitle = firstRowTitle;
}
public List<ExcelRange> getExcelRanges() {
return excelRanges;
}
public ExcelReadProcessor getExcelReadProcessor() {
return excelReadProcessor;
}
public void setExcelReadProcessor(ExcelReadProcessor excelReadProcessor) {
this.excelReadProcessor = excelReadProcessor;
}
private void initReader(Object reader) {
if (reader instanceof AbstractConfigReader) {
((AbstractConfigReader) reader).setExcelReaderConfig(this);
}
}
}
|
package figures;
import components.Matrix;
import components.Piece;
/**
* Constructeur de la piece en 'S'.
*
* @param posX
* Position X de la piece.
* @param posY
* Position Y de la piece.
*/
public class S extends Piece {
/*
* param posX Position X de la piece.
*
* @param posY Position Y de la piece.
*/
public S(int posX, int posY) {
super(posX, posY);
this.mat = new Matrix(3);
int couleur = (int) (Math.random() * 4.0);
this.mat.setVal(1, 1, couleur);
this.mat.setVal(2, 1, couleur);
this.mat.setVal(0, 2, couleur);
this.mat.setVal(1, 2, couleur);
}
}
|
package com.todo.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="Userregister")
public class UserVO {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="Uid")
private int uid;
@Column(name="Email")
private String mail;
@Column(name="Password")
private String password;
@Column(name="Status")
private boolean status;
public boolean isStatus() {
return status;
}
public void setStatus(boolean status) {
this.status = status;
}
public int getUid() {
return uid;
}
public void setUid(int uid) {
this.uid = uid;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
|
package xyz.tanku.suggestionbox.commands;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Sound;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.HandlerList;
import org.bukkit.event.Listener;
import org.bukkit.event.player.AsyncPlayerChatEvent;
import xyz.tanku.suggestionbox.SuggestionBox;
import xyz.tanku.suggestionbox.sql.utils.SQLUtils;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public class SuggestionCommand implements TabExecutor, Listener {
private Player p = null;
private String s = "";
@Override
public boolean onCommand(CommandSender sender, Command cmd, String s, String[] args) {
if (!(sender instanceof Player)) {
sender.sendMessage("Non-players can not make suggestions.");
return false;
}
Player player = (Player) sender;
if (args.length != 0) {
player.sendMessage(ChatColor.RED + "Suggestion can not be empty.");
StringBuilder stringBuilder = new StringBuilder();
for (String str : args) { stringBuilder.append(str).append(" "); }
String suggestion = stringBuilder.substring(0, stringBuilder.length() - 1) + ".";
player.sendMessage(ChatColor.GREEN + "Make suggestion " + ChatColor.YELLOW + "\"" + suggestion + "\"" + ChatColor.GREEN + "?"
+ "\nType \"y\" to confirm, and \"n\" to deny.");
this.p = player;
this.s = suggestion;
Bukkit.getServer().getPluginManager().registerEvents(this, SuggestionBox.getInstance());
}
player.sendMessage(ChatColor.RED + "Suggestion can not be empty.");
return false;
}
@Override
public List<String> onTabComplete(CommandSender sender, Command cmd, String s, String[] args) {
return Collections.emptyList();
}
@EventHandler
public void onMessage(AsyncPlayerChatEvent event) {
if (event.getPlayer() != p) return;
event.setCancelled(true);
if (event.getMessage().equalsIgnoreCase("y")) {
p.sendMessage(ChatColor.GREEN + "Suggestion sent.");
try {
makeSuggestion(p, s);
} catch(Exception e) {
e.printStackTrace();
}
HandlerList.unregisterAll(this);
} else if (event.getMessage().equalsIgnoreCase("n")) {
p.sendMessage(ChatColor.GREEN + "Suggestion cancelled.");
HandlerList.unregisterAll(this);
} else {
p.sendMessage(ChatColor.RED + "Invalid arguments. Please type \"y\" to confirm, or \"n\" to deny confirmation of suggestion.");
}
}
public void makeSuggestion(Player player, String suggestion) throws Exception {
SQLUtils utils = new SQLUtils();
utils.addSuggestion(player.getUniqueId().toString(), suggestion);
notifyMods(player, suggestion);
}
public void notifyMods(Player suggester, String suggestion) {
Collection<? extends Player> players = Bukkit.getOnlinePlayers();
for (Player player : players) {
if (!player.hasPermission("suggestionbox.mod.notify")) return;
player.playSound(player.getLocation(), Sound.ENTITY_ARROW_HIT_PLAYER, 1.0f, 1.0f);
player.sendMessage(ChatColor.GREEN + "New suggestion created by: " + ChatColor.YELLOW + suggester.getName() + ChatColor.GREEN + ":\n" + ChatColor.GOLD + "\"" + suggestion + "\"");
}
}
}
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.duylp.mathutil.main;
import com.duylp.mathutil.MathUtility;
/**
*
* @author Le Phuoc Duy
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// tui mún test 5! có bằng 120 hay hơm ?
int n = 5; // 5! coi bằng mấy
long expected = 120; // tui kì vọng, hy vọng bạn/ hàm tính ra 120.
long actual = MathUtility.getFactorial(n);
System.out.println("5! expected: "+ expected + "; actual: " + actual);
}
}
//Trong quy trình làm phần mềm, dân dev phải có trách nhiêm test từng hàm từng class mà mình việc ra trước khi đóng gói gửi cho bên QA/QC test độc lập, từng hàm , từng class phải được test cẩn thận trước khi chúng được dùng để phối hợp vs các class khác, test ngay mức hàm, mức class vừa hoàn thiện, chưa thèm bàn về UI, thì mức độ test sớm này gọi là UNIT TEST LEVEL - TEST từng đơn thể, đơn vị code
// Vậy làm sao để test từng hàm, từng class ??
// CÓ nhieuf cách để test từng hàm từng class
// 1. Cách 1: DÙng sout(gọi hàm cần test()) để in ra giá trị xử lí của hàm
// Dùng trong môn OOP
// 2. Cách 2: Dùng JOptionPane của môn Java Desktop để pop-up một cửa sổ in kết quả xử lí của hàm để kiểm tra coi hàm chạy đúng sai
// 3. Cách 3: Dùng Log file, trang Web in ra kết quả xử lí của hàm (môn Java Web)
// dù là cách nào thì cũng cần phải in ra giá trị hàm đã xử lí gọi là ACTUAL VALUE
// rồi ta đi so sánh cái giá trị trả về của hàm có giống như ta tính toán trước đó hay không, cái ta hy vong hàm sẽ trả về - gọi là EXPECTED VALUE
// nếu ACTUAL VALIUE == EXPECTED VALUE -> hàm chạy ngon
// != -> hàm sai
// Nguyên tắc của việc test: so sánh ACTUAL VỚI EXPECTED
// 3 cách này đều cùng 1 nguyên tắc:
// gọi hàm này để xem hàm xử lí ra kết quả mấy sau đó dùng mắt để so sánh ACTUAL và EXPECTED rồi ta tự kết luận cách này tiềm ẩn sai sót khi ta phải xem xét quá nhiều cặp VALUE ví dụ hàm GTHUA() phải test trường hợp N<0, =0, =1, 18, 19, 20 (Biên) 21, 30, 1Trieu
// MỖi n để test ta gọi là 1 tình huống xài hàm, 1 tình huống test
// Test case
// 4. Cách 4: Không thèm nhìn bằng mắt từng trường hợp expected vs actual nhờ máy nhìn giùm luôn, vì máy dư sức biết cách so sánh máy quét qua tất cả các cặp expected vs actual nếu tất cả đều khớp báo tao màu Xanh - Đường thống báo code tốt, nếu có xuất hiện ít nhất 1 thằng ko khớp actual vs expected báo tao màu đỏ, đường kẹt, do code có trục trặc tính toán , muốn làm được điều này ta cần thư viện phụ trợ
// Java: JUnit, TestNG
// C#: NUnit, MsTest, xUnit
// PHP: PHPUnit
// ... Mọi ngôn ngữ đều có thư viện Xanh Đỏ giúp cảnh báo hàm tốt hay ko
|
package simulator.factories;
import org.json.JSONArray;
import org.json.JSONObject;
import simulator.misc.Vector;
import simulator.model.Body;
import simulator.model.MassLosingBody;
public class MassLosingBodyBuilder extends Builder<Body> {
public MassLosingBodyBuilder() {
this.typeTag = "mlb";
this.desc = "Mass losing body";
}
public Body createTheInstance(JSONObject info) {
double[] z = {0.0, 0.0};
return new MassLosingBody(info.getString("id"), info.getDouble("mass"), new Vector(this.createArray(info.getJSONArray("pos"))), new Vector(new Vector(this.createArray(info.getJSONArray("vel")))), new Vector(z), info.getDouble("freq"), info.getDouble("factor"));
}
private double[] createArray(JSONArray arr) {
double[] ret = new double[arr.length()];
for(int i = 0; i < arr.length(); ++i)
ret[i] = arr.getDouble(i);
return ret;
}
public JSONObject getData() {
JSONObject json = new JSONObject();
json.put("id", "id");
json.put("mass", "mass");
json.put("pos", "pos");
json.put("vel", "vel");
json.put("acc", "acc");
json.put("factor", "Mass loss facotr");
json.put("freq", "Mass loss freq");
return json;
}
}
|
package idv.randy.petwall;
import android.app.Activity;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.java.iPet.R;
import java.util.List;
import idv.randy.me.MembersVO;
import idv.randy.member.MemberActivity;
import idv.randy.petwall.PwDetailFragment.OnListFragmentInteractionListener;
import idv.randy.ut.AsyncImageTask;
import idv.randy.ut.Me;
public class MyPwDetailRecyclerViewAdapter extends RecyclerView.Adapter<MyPwDetailRecyclerViewAdapter.ViewHolder> implements View.OnClickListener {
private final List<PwrVO> mPwrVOs;
private final List<MembersVO> mMembersVOs;
private final OnListFragmentInteractionListener mListener;
public MyPwDetailRecyclerViewAdapter(List<PwrVO> mPwrVOs, List<MembersVO> mMembersVOs, OnListFragmentInteractionListener listener) {
this.mPwrVOs = mPwrVOs;
mListener = listener;
this.mMembersVOs = mMembersVOs;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.r_fragment_pw_detail, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
holder.mItem = mPwrVOs.get(position);
holder.tvMemID.setText(mMembersVOs.get(position).getMemName());
holder.tvPwrContent.setText(mPwrVOs.get(position).getPwrcontent());
int memNo = mMembersVOs.get(position).getMemNo();
new AsyncImageTask(memNo, holder.ivMemImg, R.drawable.person).execute(Me.MembersServlet);
View.OnClickListener onClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
Activity activity = (Activity) holder.tvMemID.getContext();
MemberActivity.start(activity, memNo);
}
};
holder.tvMemID.setOnClickListener(onClickListener);
holder.ivMemImg.setOnClickListener(onClickListener);
}
@Override
public int getItemCount() {
return mPwrVOs.size();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.tvMemID:
}
}
public class ViewHolder extends RecyclerView.ViewHolder {
public final View mView;
public final TextView tvPwrContent;
public final TextView tvMemID;
public final ImageView ivMemImg;
public PwrVO mItem;
public ViewHolder(View view) {
super(view);
mView = view;
ivMemImg = (ImageView) view.findViewById(R.id.ivMemImg);
tvMemID = (TextView) view.findViewById(R.id.tvMemID);
tvPwrContent = (TextView) view.findViewById(R.id.content);
}
@Override
public String toString() {
return super.toString() + " '" + tvPwrContent.getText() + "'";
}
}
}
|
package com.maverick.elevator.api;
import org.slf4j.*;
import org.springframework.stereotype.*;
import java.util.*;
import java.util.stream.*;
import static java.lang.Math.*;
/**
* Created by abhinav on 2017-03-08.
*/
@Service
public class ElevatorService implements ElevatorController {
private static final Logger LOG = LoggerFactory.getLogger(ElevatorService.class);
private static final int retryWaitTimeWhenAllBusy = 100;
private final List<Elevator> elevators = Collections.synchronizedList(new ArrayList<>());
private final int noFloors;
public ElevatorService(int noElevators, int noFloors) {
this.noFloors = noFloors;
LOG.debug("Boot up {} elevators", noElevators);
IntStream.rangeClosed(1, noElevators).forEach(id -> elevators.add(new StandardElevator(id, this.noFloors)));
}
@Override
public Elevator requestElevator(int toFloor) {
LOG.debug("Elevator requested, floor {}", toFloor);
//Check if an elevator is already requested for the floor or an elevator is already at the floor
Elevator closest = checkElevatorAlreadyAddressed(toFloor);
if (closest == null) {
//check if any elevator is available
List<Elevator> availableElevators = elevators.stream().filter(elevator -> !elevator.isBusy()).collect(Collectors.toList());
while (availableElevators.isEmpty()) {
LOG.debug("Busy times, Floor {} request has to wait.", toFloor);
waitWhenAllBusy();
availableElevators = elevators.stream().filter(elevator -> !elevator.isBusy()).collect(Collectors.toList());
}
int offset = this.noFloors;
// find the closest elevator
for (Elevator e : availableElevators) {
int diff = abs(e.currentFloor() - toFloor);
if (diff < offset) {
offset = diff;
closest = e;
}
}
//all available elevators are at same offset, return any
if (closest == null) {
closest = availableElevators.get(0);
}
LOG.debug("Elevator available: {}", closest.toString());
return closest;
} else {
LOG.debug("Elevator already addressed or present: {}", closest.toString());
return null;
}
}
private void waitWhenAllBusy() {
//wait till any elevator is available
try {
Thread.sleep(retryWaitTimeWhenAllBusy);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private Elevator checkElevatorAlreadyAddressed(int toFloor) {
return getElevators().stream()
.filter(elevator -> (!elevator.isBusy() && elevator.currentFloor() == toFloor)
|| (elevator.isBusy() && elevator.getAddressedFloor() == toFloor))
.findFirst()
.orElse(null);
}
@Override
public List<Elevator> getElevators() {
return elevators;
}
@Override
public void releaseElevator(Elevator elevator) {
//doing this will make the elevator available as addressed and current floor will be same
elevator.moveElevator(elevator.currentFloor());
LOG.info("Elevator released: {}", elevator.toString());
}
@Override
public Integer getElevatorOnFloor(int floor) {
return getElevators()
.stream()
.filter(elevator -> !elevator.isBusy())
.filter(elevator -> elevator.currentFloor() == floor)
.map(Elevator::getId)
.findAny()
.orElse(null);
}
@Override
public Elevator getElevatorById(int elevatorId) {
return getElevators()
.stream()
.filter(elevator -> !elevator.isBusy())
.filter(elevator -> elevator.getId() == elevatorId)
.findFirst()
.orElse(null);
}
}
|
package org.slevin.dao.service;
import org.slevin.dao.ParserDao;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
@Component
@Transactional
public class ParserService implements ParserDao {
}
|
package scriptinterface.execution.parseerrors;
import scriptinterface.execution.returnvalues.ExecutionError;
/**
* An error that occurs when parsing a string.
*
* @author Andreas Fender
*/
public class ParseError extends ExecutionError {
public ParseError(String errorKey) {
super(errorKey);
}
@Override
public String toString() {
return "Syntax error";
}
/**
* Returns a user-readable string representation of the error.
*/
@Override
public String getStringRepresentation() {
return toString();
}
}
|
package main.form.exceptions;
import java.lang.reflect.Field;
public class UnsupportedFieldTypeException extends RuntimeException {
public UnsupportedFieldTypeException(Field field) {
super("Unsupported field: " + field);
}
}
|
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int max = 0;
public int diameterOfBinaryTree(TreeNode root) {
findDia(root);
return max;
}
int findDia(TreeNode node)
{
if(node == null)
{
return 0;
}
int left = 1 + findDia(node.left);
int right = 1 + findDia(node.right);
if((left + right - 2) > max)
{
max = left + right - 2;
}
return Math.max(left, right);
}
}
|
package com.jd.dao;
import com.jd.entity.User;
import java.util.List;
/**
* Created by HXS on 2021/4/25.
*
* 用户的持久层接口
*/
public interface IUserDao {
/**
* 查询所有操作
* @return
*/
List<User> findAll();
}
|
package uz.pdp.apphemanagement.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import uz.pdp.apphemanagement.entity.Salary;
import uz.pdp.apphemanagement.entity.User;
import uz.pdp.apphemanagement.payload.ApiResponse;
import uz.pdp.apphemanagement.payload.SalaryDto;
import uz.pdp.apphemanagement.repository.SalaryRepository;
import uz.pdp.apphemanagement.repository.UserRepository;
import java.sql.Timestamp;
import java.util.List;
import java.util.Optional;
import java.util.UUID;
@Service
public class SalaryService {
@Autowired
SalaryRepository salaryRepository;
@Autowired
UserRepository userRepository;
/**
* ADD SALARY
*
* @param salaryDto Salary,
* UserId
* @return ApiResponse in ResponseEntity
*/
public ApiResponse add(SalaryDto salaryDto) {
Salary salary = new Salary();
salary.setSalary(salaryDto.getSalary());
Optional<User> optionalUser = userRepository.findById(salaryDto.getUserId());
if (!optionalUser.isPresent()) {
return new ApiResponse("User not found", false);
}
User user = optionalUser.get();
salary.setUser(user);
salaryRepository.save(salary);
return new ApiResponse("Successfully added", true);
}
/**
* GET SALARIES OF USER
*
* @param id UUID
* @return ApiResponse in ResponseEntity
*/
public List<Salary> getById(UUID id) {
return salaryRepository.findAllByUserId(id);
}
}
|
package com.kristi71111.bacoskyrestrict.commands;
import com.kristi71111.bacoskyrestrict.BacoSkyRestrict;
import org.spongepowered.api.command.CommandException;
import org.spongepowered.api.command.CommandResult;
import org.spongepowered.api.command.CommandSource;
import org.spongepowered.api.command.args.CommandContext;
import org.spongepowered.api.command.spec.CommandExecutor;
import org.spongepowered.api.entity.living.player.Player;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.format.TextColors;
public class BacoSkyRestrictCommand implements CommandExecutor {
@Override
public CommandResult execute(CommandSource src, CommandContext args) throws CommandException {
if (!(src instanceof Player)) {
BacoSkyRestrict.getLogger().info("Usage: /bsr reload");
} else if (src.hasPermission("bacoskyrestrict.command.base") || src.hasPermission("bacoskyrestrict.admin")){
Text BacoSkyRestrict = Text.builder("Usage: /bsr reload|getworld").color(TextColors.RED).build();
src.sendMessage(BacoSkyRestrict);
}else{
src.sendMessage(Text.of(TextColors.RED, "You do not have the permission to execute this command"));
}
return CommandResult.success();
}
}
|
package com.tencent.mm.plugin.voip.ui;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import com.tencent.mm.plugin.voip.ui.e.16;
class e$16$2 implements OnClickListener {
final /* synthetic */ 16 oSg;
e$16$2(16 16) {
this.oSg = 16;
}
public final void onClick(DialogInterface dialogInterface, int i) {
e.d(this.oSg.oSe);
}
}
|
package com.example.huanglisa.nightynight;
/**
* Created by huanglisa on 11/25/16.
*/
public class ReceivedFriend {
public String id;
public String buildingId;
public String friendId;
public String name;
public boolean status;
}
|
package com.vendingMachine.DeloitteTask;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import com.vendingMachine.DeloitteTask.Config.VendingMachineConfig;
import com.vendingMachine.DeloitteTask.Entity.VendingMachineEntity;
import com.vendingMachine.DeloitteTask.Enum.Coin;
import com.vendingMachine.DeloitteTask.Enum.Product;
import com.vendingMachine.DeloitteTask.Exception.NotFullPaidException;
import com.vendingMachine.DeloitteTask.Exception.NotSufficientChangeException;
import com.vendingMachine.DeloitteTask.Exception.SoldOutException;
import com.vendingMachine.DeloitteTask.service.VendingMachine;
/**
* VendingMachineTest is used to perform test on vending machine
*
* @author NB
*
*/
public class VendingMachineTest {
private static VendingMachine vm;
@Before
public void setUp() {
vm = VendingMachineConfig.createVendingMachine(5, 5);
}
@After
public void tearDown() {
vm = null;
}
@Test
public void testInitialProductData() {
Map<String, Integer> initialProductMap = new HashMap<String, Integer>();
int initialData = 5;
initialProductMap.put(Product.CANDY.toString(), initialData);
initialProductMap.put(Product.CHOCOLATE.toString(), initialData);
initialProductMap.put(Product.COOLDRINK.toString(), initialData);
Assert.assertEquals(vm.getProductInWarehouse().toString(), initialProductMap.toString());
}
@Test
public void testInitialCoinData() {
Map<String, Integer> initialCoinMap = new HashMap<String, Integer>();
int initialData = 5;
initialCoinMap.put(Coin.PENNY.toString(), initialData);
initialCoinMap.put(Coin.NICKLE.toString(), initialData);
initialCoinMap.put(Coin.DIME.toString(), initialData);
initialCoinMap.put(Coin.QUARTER.toString(), initialData);
Assert.assertEquals(vm.getCashInWarehouse().toString(), initialCoinMap.toString());
}
@Test
public void testPriceOfProducts() {
Assert.assertEquals(25, Product.CHOCOLATE.getPrice());
Assert.assertEquals(35, Product.CANDY.getPrice());
Assert.assertEquals(45, Product.COOLDRINK.getPrice());
}
@Test
public void testValueOfCoins() {
Assert.assertEquals(1, Coin.PENNY.getDenomination());
Assert.assertEquals(5, Coin.NICKLE.getDenomination());
Assert.assertEquals(10, Coin.DIME.getDenomination());
Assert.assertEquals(25, Coin.QUARTER.getDenomination());
}
@Test
public void testBuyWithExactPrice() {
vm.selectProductAndGetPrice(Product.CHOCOLATE);
vm.insertCoin(Coin.QUARTER);
VendingMachineEntity<Product, List<Coin>> entity = vm.collectProductAndChange();
Product product = entity.getProduct();
assertEquals(Product.CHOCOLATE, product);
List<Coin> change = entity.getCoin();
assertTrue(change.isEmpty());
assertEquals(25, vm.getTotalSales());
assertEquals("{NICKLE=5, PENNY=5, QUARTER=6, DIME=5}", vm.getCashInWarehouse().toString());
assertEquals("{CHOCOLATE=4, COOLDRINK=5, CANDY=5}", vm.getProductInWarehouse().toString());
}
@Test(expected = NotFullPaidException.class)
public void testBuyWithInsufficientPrice() {
vm.selectProductAndGetPrice(Product.CANDY);
vm.insertCoin(Coin.PENNY);
vm.collectProductAndChange();
}
@Test
public void testBuyWithExtraPrice() {
vm.selectProductAndGetPrice(Product.COOLDRINK);
vm.insertCoin(Coin.QUARTER);
vm.insertCoin(Coin.QUARTER);
VendingMachineEntity<Product, List<Coin>> entity = vm.collectProductAndChange();
Product product = entity.getProduct();
assertEquals(Product.COOLDRINK, product);
List<Coin> change = entity.getCoin();
assertFalse(change.isEmpty());
assertEquals(45, vm.getTotalSales());
assertEquals("{NICKLE=4, PENNY=5, QUARTER=7, DIME=5}", vm.getCashInWarehouse().toString());
assertEquals("{CHOCOLATE=5, COOLDRINK=4, CANDY=5}", vm.getProductInWarehouse().toString());
}
@Test
public void testRemainingWarehouseData() {
vm.selectProductAndGetPrice(Product.CHOCOLATE);
vm.insertCoin(Coin.QUARTER);
vm.collectProductAndChange();
vm.selectProductAndGetPrice(Product.CHOCOLATE);
vm.insertCoin(Coin.QUARTER);
vm.insertCoin(Coin.QUARTER);
vm.collectProductAndChange();
vm.selectProductAndGetPrice(Product.CANDY);
vm.insertCoin(Coin.QUARTER);
vm.insertCoin(Coin.DIME);
vm.collectProductAndChange();
vm.selectProductAndGetPrice(Product.CANDY);
vm.insertCoin(Coin.QUARTER);
vm.insertCoin(Coin.DIME);
vm.insertCoin(Coin.PENNY);
vm.collectProductAndChange();
vm.selectProductAndGetPrice(Product.CANDY);
vm.insertCoin(Coin.QUARTER);
vm.insertCoin(Coin.DIME);
vm.insertCoin(Coin.PENNY);
vm.insertCoin(Coin.NICKLE);
vm.collectProductAndChange();
vm.selectProductAndGetPrice(Product.COOLDRINK);
vm.insertCoin(Coin.QUARTER);
vm.insertCoin(Coin.QUARTER);
vm.collectProductAndChange();
vm.selectProductAndGetPrice(Product.COOLDRINK);
vm.insertCoin(Coin.QUARTER);
vm.insertCoin(Coin.QUARTER);
vm.collectProductAndChange();
vm.selectProductAndGetPrice(Product.COOLDRINK);
vm.insertCoin(Coin.QUARTER);
vm.insertCoin(Coin.QUARTER);
vm.collectProductAndChange();
vm.selectProductAndGetPrice(Product.COOLDRINK);
vm.insertCoin(Coin.QUARTER);
vm.insertCoin(Coin.QUARTER);
vm.collectProductAndChange();
assertEquals(335, vm.getTotalSales());
assertEquals("{NICKLE=1, PENNY=5, QUARTER=18, DIME=8}", vm.getCashInWarehouse().toString());
assertEquals("{CHOCOLATE=3, COOLDRINK=1, CANDY=2}", vm.getProductInWarehouse().toString());
}
@Test(expected = SoldOutException.class)
public void testSoldOut() {
// when trying to get the sixth product error will be thrown
for (int i = 0; i < 6; i++) {
vm.selectProductAndGetPrice(Product.CHOCOLATE);
vm.insertCoin(Coin.QUARTER);
vm.collectProductAndChange();
}
}
@Test(expected = SoldOutException.class)
public void testReset() {
vm.reset();
vm.selectProductAndGetPrice(Product.CHOCOLATE);
}
@Test
public void testRefund() {
long price = vm.selectProductAndGetPrice(Product.CANDY);
assertEquals(Product.CANDY.getPrice(), price);
vm.insertCoin(Coin.PENNY);
vm.insertCoin(Coin.NICKLE);
vm.insertCoin(Coin.DIME);
vm.insertCoin(Coin.QUARTER);
VendingMachineEntity<Product, List<Coin>> entity = vm.collectProductAndChange();
List<Coin> change = entity.getCoin();
assertFalse(change.isEmpty());
assertEquals(6, getTotal(change));
}
@Test(expected = NotSufficientChangeException.class)
public void testNotSufficientChangeException() {
vm = VendingMachineConfig.createVendingMachine(0, 5);
vm.selectProductAndGetPrice(Product.COOLDRINK);
vm.insertCoin(Coin.QUARTER);
vm.insertCoin(Coin.QUARTER);
vm.collectProductAndChange();
}
private long getTotal(List<Coin> change) {
long total = 0;
for (Coin c : change) {
total = total + c.getDenomination();
}
return total;
}
}
|
package com.baidu.camera.template.db;
import com.baidu.camera.app.CameraApp;
import com.j256.ormlite.android.apptools.OpenHelperManager;
import com.j256.ormlite.dao.Dao;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
/**
* Created by yangmengrong on 14-8-27.
*/
public class DaoManagerImpl<T> implements DaoManager<T> {
protected DAOHelper helper;
protected Dao dao;
public DAOHelper getHelper() {
return helper;
}
public DaoManagerImpl() {
helper = OpenHelperManager.getHelper(CameraApp.getInstance(), DAOHelper.class);
Class<T> entityClass = null;
Type modelType = getClass().getGenericSuperclass();
if ((modelType instanceof ParameterizedType))
{
Type[] modelTypes = ((ParameterizedType)modelType).getActualTypeArguments();
entityClass = ((Class)modelTypes[0]);
}
System.out.println("entityClass = " + entityClass);
dao = helper.getHelperDao(entityClass);
}
@Override
public void close() {
dao = null;
}
@Override
public void add(T t) throws SQLException {
dao.create(t);
}
@Override
public void addAll(Collection<T> ts) throws SQLException {
for (T t : ts) {
add(t);
}
}
@Override
public void delete(T t) throws SQLException {
dao.delete(t);
}
@Override
public void deleteAll(Collection<T> ts) throws SQLException {
for (T t : ts) {
delete(t);
}
}
@Override
public void update(T t) throws SQLException {
dao.update(t);
}
@Override
public void updateALl(Collection<T> ts) throws SQLException {
for (T t : ts) {
update(t);
}
}
@Override
public List<T> findByKey(String key,Object value) throws SQLException {
return dao.queryForEq(key,value);
}
@Override
public List<T> findAll() throws SQLException {
return dao.queryForAll();
}
}
|
package com.ricex.cartracker.common.entity.auth;
import com.ricex.cartracker.common.entity.AbstractEntity;
import com.ricex.cartracker.common.viewmodel.auth.UserViewModel;
public class RegistrationKeyUse extends AbstractEntity {
private long keyId;
private long userId;
private UserViewModel user;
public RegistrationKeyUse() {
keyId = INVALID_ID;
userId = INVALID_ID;
}
/**
* @return the keyId
*/
public long getKeyId() {
return keyId;
}
/**
* @param keyId the keyId to set
*/
public void setKeyId(long keyId) {
this.keyId = keyId;
}
/**
* @return the userId
*/
public long getUserId() {
return userId;
}
/**
* @param userId the userId to set
*/
public void setUserId(long userId) {
this.userId = userId;
}
/**
* @return the user
*/
public UserViewModel getUser() {
return user;
}
/**
* @param user the user to set
*/
public void setUser(UserViewModel user) {
if (null != user) {
userId = user.getId();
}
this.user = user;
}
}
|
package tw.org.iii.java;
import java.util.HashSet;
public class Brad71 {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Brad");
//set.add(123);
set.add("Chao");
}
}
|
class Pizza extends DecoratedPizza{
private Crust crust;
public Pizza(Crust crust){
super();
this.crust = crust;
}
public double pizzaCost(){
return crust.crustCost();
}
public String toString(){
return crust.toString() + "Toppings:\n";
}
public String getImage(){
return String.valueOf(crust.getCrust());
}
/*public void setCrust(Crust crust){
this.crust = crust;
}*/
}
|
// punto 4
import java.util.*;
public class punto_04 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int cantidad = 0;
System.out.println("ingrese la cantidad de numeros primos a averiguar: ");
cantidad = sc.nextInt();
sc.nextLine();
Integer[] primos = new Integer[cantidad];
List<Integer> listaPrimos = new ArrayList<Integer>();
for(int i = 1; listaPrimos.size() < cantidad; i++) {
int divisibles = 0;
for(int j = 1; j <= i ; j++){
if(i % j == 0){
divisibles ++;
}
}
if (divisibles == 2){
listaPrimos.add(i);
}
}
System.out.println("----");
for(int i = 0; i < listaPrimos.size(); i ++) {
primos[i] = listaPrimos.get(i);
System.out.println(primos[i]);
}
}
}
|
package com.tencent.mm.plugin.card.ui;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.tencent.mm.plugin.card.a$a;
import com.tencent.mm.plugin.card.a$e;
import com.tencent.mm.plugin.card.a.b;
import com.tencent.mm.plugin.card.a.c;
import com.tencent.mm.plugin.card.a.d;
import com.tencent.mm.plugin.card.a.f;
import com.tencent.mm.ui.statusbar.DrawStatusBarActivity;
import com.tencent.mm.ui.y;
public abstract class CardDetailBaseUI extends DrawStatusBarActivity {
private TextView gsY;
private View gxg;
private ImageView hBu;
private TextView hBv;
ImageView hBw;
private View hBx;
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
this.gxg = y.gq(this.mController.tml).inflate(a$e.card_detail_action_bar, null);
this.gxg.setBackgroundColor(getResources().getColor(a$a.action_bar_color));
this.gsY = (TextView) this.gxg.findViewById(d.title_area);
this.hBv = (TextView) this.gxg.findViewById(d.sub_title_area);
this.hBu = (ImageView) this.gxg.findViewById(d.arrow_area_btn);
this.hBw = (ImageView) this.gxg.findViewById(d.menu_icon);
this.hBx = this.gxg.findViewById(d.divider);
if (this.mController.contentView != null && ((ViewGroup) this.mController.contentView).getChildCount() > 0) {
View childAt = ((ViewGroup) this.mController.contentView).getChildAt(0);
((ViewGroup) this.mController.contentView).removeView(childAt);
View linearLayout = new LinearLayout(this);
linearLayout.setLayoutParams(new LayoutParams(-1, -1));
linearLayout.setOrientation(1);
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
linearLayout.addView(this.gxg, new LinearLayout.LayoutParams(-1, displayMetrics.widthPixels > displayMetrics.heightPixels ? getResources().getDimensionPixelSize(b.DefaultActionbarHeightLand) : getResources().getDimensionPixelSize(b.DefaultActionbarHeightPort)));
linearLayout.addView(childAt);
((ViewGroup) this.mController.contentView).addView(linearLayout);
}
}
protected final void onCreateBeforeSetContentView() {
super.onCreateBeforeSetContentView();
supportRequestWindowFeature(10);
supportRequestWindowFeature(1);
}
public final void setBackBtn(OnMenuItemClickListener onMenuItemClickListener) {
this.hBu.setOnClickListener(new 1(this, onMenuItemClickListener));
}
public final void setMMTitle(String str) {
this.gsY.setText(str);
}
public final void nS(int i) {
this.gsY.setTextColor(i);
}
public final void setMMSubTitle(String str) {
this.hBv.setText(str);
}
public final void G(int i, boolean z) {
this.gxg.setBackgroundColor(i);
if (z) {
this.gsY.setTextColor(getResources().getColor(a$a.black));
this.hBv.setTextColor(getResources().getColor(a$a.black));
this.hBu.setImageResource(f.actionbar_icon_dark_back);
this.hBw.setImageResource(c.card_mm_title_btn_menu);
this.hBx.setBackgroundColor(getResources().getColor(a$a.actionbar_devider_color));
return;
}
this.gsY.setTextColor(getResources().getColor(a$a.white));
this.hBv.setTextColor(getResources().getColor(a$a.white));
this.hBu.setImageResource(f.actionbar_icon_dark_back);
this.hBw.setImageResource(c.mm_title_btn_menu);
this.hBx.setBackgroundColor(getResources().getColor(a$a.half_alpha_white));
}
public final void dQ(boolean z) {
this.hBw.setVisibility(z ? 0 : 8);
}
public final boolean noActionBar() {
return false;
}
}
|
/**
*
*/
/**
* @author 123
*
*/
package model;
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package mvirtual.catalog.heritage;
import mvirtual.catalog.SessionNames;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ActionContext;
import org.hibernate.Session;
import org.mvirtual.persistence.entity.Heritage;
import java.util.Map;
/**
*
* @author fabricio
*/
public class SaveDescriptionTab extends ActionSupport {
private String to;
private String heritageContent;
private String heritageNote;
private String heritageDimensions;
private String heritagePhysicalFeatures;
private String heritageSupport;
private String heritageCondition;
public void setTo(String to) {
this.to = to;
}
public void setHeritageCondition(String heritageCondition) {
this.heritageCondition = heritageCondition;
}
public void setHeritageContent(String heritageContent) {
this.heritageContent = heritageContent;
}
public void setHeritageDimensions(String heritageDimensions) {
this.heritageDimensions = heritageDimensions;
}
public void setHeritageNote(String heritageNote) {
this.heritageNote = heritageNote;
}
public void setHeritagePhysicalFeatures(String heritagePhysicalFeatures) {
this.heritagePhysicalFeatures = heritagePhysicalFeatures;
}
public void setHeritageSupport(String heritageSupport) {
this.heritageSupport = heritageSupport;
}
@Override
public String execute () {
Map <String, Object> httpSession = ActionContext.getContext().getSession();
Session dbSession = (Session) httpSession.get (SessionNames.HERITAGE_DB_SESSION);
Heritage heritage = (Heritage) httpSession.get (SessionNames.HERITAGE);
heritage.setContent(this.heritageContent);
heritage.setNote(this.heritageNote);
heritage.setDimensions(this.heritageDimensions);
heritage.setPhysicalFeatures(this.heritagePhysicalFeatures);
heritage.setSupport(this.heritageSupport);
heritage.setCondition(this.heritageCondition);
dbSession.flush();
return this.to;
}
}
|
package com.espendwise.manta.web.validator;
import com.espendwise.manta.util.validation.ValidationResult;
import com.espendwise.manta.web.forms.AccountSiteHierarchyManageFilterForm;
import com.espendwise.manta.web.util.WebErrors;
public class AccountSiteHierarchyManageFilterFormValidator extends AbstractFormValidator{
@Override
public ValidationResult validate(Object obj) {
AccountSiteHierarchyManageFilterForm valueObj = (AccountSiteHierarchyManageFilterForm) obj;
WebErrors errors = new WebErrors();
SimpleFilterFormFieldValidator validator = new SimpleFilterFormFieldValidator(
"admin.account.siteHierarchy.label.levelName",
"admin.account.siteHierarchy.label.levelId"
);
ValidationResult vr = validator.validate(valueObj);
if (vr != null) {
errors.putErrors(vr.getResult());
}
return new MessageValidationResult(errors.get());
}
}
|
package com.pybeta.daymatter.ui;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.pybeta.daymatter.BuildConfig;
import com.pybeta.daymatter.CategoryItem;
import com.pybeta.daymatter.IContants;
import com.pybeta.daymatter.R;
import com.pybeta.daymatter.core.DLAService;
import com.pybeta.daymatter.db.DatabaseManager;
import com.pybeta.daymatter.utils.LogUtil;
import com.pybeta.daymatter.utils.UtilityHelper;
import com.pybeta.util.ChangeLogDialog;
import com.pybeta.util.DMToast;
import com.umeng.fb.NotificationType;
import com.umeng.fb.UMFeedbackService;
import com.umeng.update.UmengUpdateAgent;
import net.simonvt.menudrawer.MenuDrawer;
import net.simonvt.menudrawer.MenuDrawer.OnDrawerStateChangeListener;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class HomeActivity extends LockBaseActivity implements OnDrawerStateChangeListener {
private static final String STATE_ACTIVE_POSITION = "com.pybeta.daymatter.HomeActivity.activePosition";
private final static int REQUEST_SETTINGS_CODE = 1000;
private MenuDrawer mMenuDrawer;
private int mActivePosition = 1;
private MenuAdapter mAdapter;
private ListView mList;
private DatabaseManager mDatebaseMgr;
@Override
protected void onCreate(Bundle inState) {
super.onCreate(inState);
getSupportActionBar().setTitle(R.string.app_name);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
if (inState != null) {
mActivePosition = inState.getInt(STATE_ACTIVE_POSITION, 1);
}
if (checkCurrentLocale()) {
showChangeLogDialog();
UmengUpdateAgent.update(this);
UMFeedbackService.enableNewReplyNotification(this, NotificationType.NotificationBar);
mDatebaseMgr = DatabaseManager.getInstance(this);
mMenuDrawer = MenuDrawer.attach(this, MenuDrawer.MENU_DRAG_CONTENT);
mMenuDrawer.setOnDrawerStateChangeListener(this);
mMenuDrawer.setContentView(R.layout.activity_main);
mMenuDrawer.setTouchMode(MenuDrawer.TOUCH_MODE_FULLSCREEN);
mList = new ListView(this);
mAdapter = new MenuAdapter(buildMenuList());
mList.setAdapter(mAdapter);
mList.setOnItemClickListener(mItemClickListener);
mList.setCacheColorHint(Color.TRANSPARENT);
mMenuDrawer.setMenuView(mList);
setupBasicFragment();
UtilityHelper.showStartBarNotification(this);
}
startService(new Intent(this, DLAService.class));
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_SETTINGS_CODE) {
mAdapter.setMenuItems(buildMenuList());
mAdapter.notifyDataSetChanged();
}
super.onActivityResult(requestCode, resultCode, data);
}
private void setupBasicFragment() {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment fragment = getMatterListFragment(0);
if (fragment != null) {
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
}
private void instantiateItem(int position, Object object) {
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
Fragment fragment = getFragment(position, object);
if (fragment != null) {
fragmentTransaction.replace(R.id.fragment_container, fragment);
fragmentTransaction.commit();
}
}
@SuppressWarnings("unchecked")
private Fragment getFragment(int position, Object object) {
Fragment fragment = null;
if (object != null && object instanceof Item) {
Item item = (Item) object;
if (item.mData instanceof CategoryItem) {
fragment = getMatterListFragment(((CategoryItem) item.mData).getId());
} else if(item.mData instanceof Class) {
Class<Fragment> calzz = (Class<Fragment>) item.mData;
try {
fragment = (Fragment) calzz.newInstance();
} catch (InstantiationException e) {
if (BuildConfig.DEBUG) e.printStackTrace();
} catch (IllegalAccessException e) {
if (BuildConfig.DEBUG) e.printStackTrace();
}
}
}
return fragment;
}
private Fragment getMatterListFragment(int id) {
Fragment fragment = new MatterListFragment();
Bundle args = new Bundle();
args.putInt(MatterListFragment.ARG_SECTION_NUMBER, id);
fragment.setArguments(args);
return fragment;
}
private List<Object> buildMenuList() {
List<CategoryItem> categoryList = mDatebaseMgr.queryCategoryList();
List<Object> items = new ArrayList<Object>();
items.add(new Category(getString(R.string.category_title)));
if (categoryList != null && categoryList.size() > 0) {
for (int index = 0; index < categoryList.size(); index++) {
CategoryItem category = categoryList.get(index);
items.add(new Item(category.getName(), R.drawable.ic_action_select_all_dark, category));
LogUtil.Sysout("category: "+category.getName());
}
}
items.add(new Category(getString(R.string.menu_common_feature)));
items.add(new Item(getString(R.string.title_activity_holiday), R.drawable.ic_action_select_all_dark, HolidayRecActivity.class));
items.add(new Item(getString(R.string.title_activity_count_down), R.drawable.ic_action_select_all_dark, CountdownRecActivity.class));
items.add(new Item(getString(R.string.title_activity_history_today), R.drawable.ic_action_select_all_dark, HistoryTodayFragement.class));
items.add(new Item(getString(R.string.title_activity_worldtime), R.drawable.ic_action_select_all_dark, WorldTimeFragment.class));
items.add(new Item(getString(R.string.otherfunction), R.drawable.ic_action_select_all_dark, OtherFunctionActivity.class));
items.add(new Category(getString(R.string.copyright)));
items.add(new Item(getString(R.string.copyright_content), 0, null));
return items;
}
private AdapterView.OnItemClickListener mItemClickListener = new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (mActivePosition != position) {
mActivePosition = position;
mMenuDrawer.setActiveView(view, position);
instantiateItem(mActivePosition, mAdapter.getItem(position));
Handler h = new Handler();
h.postDelayed(new Runnable() {
public void run() {
mMenuDrawer.closeMenu();
}
}, 100);
} else {
mMenuDrawer.closeMenu();
}
}
};
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_ACTIVE_POSITION, mActivePosition);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.activity_home, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home: {
mMenuDrawer.toggleMenu();
return true;
}
case R.id.menu_item_action_add: {
Intent intent = null;
CharSequence mCharSequence = getSupportActionBar().getTitle();
LogUtil.Sysout(" R.id.menu_item_action_add mCharSequence: "+mCharSequence);
if(mCharSequence != null){
String title = getSupportActionBar().getTitle().toString().trim();
if(title.equals(getResources().getString(R.string.title_activity_worldtime))){
intent = new Intent(this, AddWorldTimeActivity.class);
}
else
intent = new Intent(this, AddMatterActivity.class);
}else{
intent = new Intent(this, AddMatterActivity.class);
}
startActivity(intent);
break;
}
case R.id.menu_item_action_setting: {
Intent intent = new Intent(this, SettingsActivity.class);
startActivityForResult(intent, REQUEST_SETTINGS_CODE);
break;
}
case R.id.menu_item_action_share: {
takeScreenshotAndShare();
break;
}
case R.id.menu_item_action_feedback: {
UMFeedbackService.openUmengFeedbackSDK(this);
break;
}
default:
break;
}
return super.onOptionsItemSelected(item);
}
private void takeScreenshotAndShare() {
new ScreenshotShare().execute();
}
class ScreenshotShare extends AsyncTask<String, String, String> {
private ProgressDialog progressDlg = null;
@Override
protected void onPreExecute() {
Resources res = HomeActivity.this.getResources();
progressDlg = ProgressDialog.show(HomeActivity.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(HomeActivity.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 = HomeActivity.this.getString(R.string.screen_shot_save_path);
DMToast.makeText(HomeActivity.this, tips + result, Toast.LENGTH_SHORT).show();
UtilityHelper.share(HomeActivity.this, getString(R.string.share_intent_subject), "#"
+ getString(R.string.app_name) + "#", result);
super.onPostExecute(result);
}
}
@Override
public void onDrawerStateChange(int oldState, int newState) {
if (newState == MenuDrawer.STATE_OPEN) {
getSupportActionBar().setDisplayHomeAsUpEnabled(false);
} else {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
}
@Override
public void onBackPressed() {
final int drawerState = mMenuDrawer.getDrawerState();
if (drawerState == MenuDrawer.STATE_OPEN || drawerState == MenuDrawer.STATE_OPENING) {
mMenuDrawer.closeMenu();
return;
}
super.onBackPressed();
}
private void showChangeLogDialog() {
if (UtilityHelper.getChangeLogShow(this, IContants.CURRENT_VERSION)) {
ChangeLogDialog _ChangelogDialog = new ChangeLogDialog(this);
_ChangelogDialog.show();
UtilityHelper.setChangeLogShow(this, IContants.CURRENT_VERSION);
}
}
private boolean checkCurrentLocale() {
Resources resources = getResources();
Configuration config = resources.getConfiguration();
Locale locale = UtilityHelper.getCurrentLocale(this);
if (!config.locale.equals(locale)) {
UtilityHelper.switchLanguage(this);
return false;
} else {
return true;
}
}
private static class Item {
String mTitle;
int mIconRes;
Object mData;
Item(String title, int iconRes, Object data) {
mTitle = title;
mIconRes = iconRes;
mData = data;
}
}
private static class Category {
String mTitle;
Category(String title) {
mTitle = title;
}
}
private class MenuAdapter extends BaseAdapter {
private List<Object> mItems;
MenuAdapter(List<Object> items) {
mItems = items;
}
public void setMenuItems(List<Object> items) {
mItems = items;
}
@Override
public int getCount() {
return mItems.size();
}
@Override
public Object getItem(int position) {
return mItems.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public int getItemViewType(int position) {
return getItem(position) instanceof Item ? 0 : 1;
}
@Override
public int getViewTypeCount() {
return 2;
}
@Override
public boolean isEnabled(int position) {
return getItem(position) instanceof Item;
}
@Override
public boolean areAllItemsEnabled() {
return false;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
Object item = getItem(position);
if (item instanceof Category) {
if (v == null) {
v = getLayoutInflater().inflate(R.layout.menu_row_category, parent, false);
}
((TextView) v).setText(((Category) item).mTitle);
} else {
if (v == null) {
v = getLayoutInflater().inflate(R.layout.menu_row_item, parent, false);
}
TextView tv = (TextView) v;
tv.setText(((Item) item).mTitle);
tv.setCompoundDrawablesWithIntrinsicBounds(((Item) item).mIconRes, 0, 0, 0);
}
v.setTag(R.id.mdActiveViewPosition, position);
if (position == mActivePosition) {
mMenuDrawer.setActiveView(v, position);
}
return v;
}
}
}
|
/*
* 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 herramientas;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import java.util.Date;
/**
*
* @author abfd
*/
public class CargaLoteSVHT
{
private Logger logger = Logger.getLogger(CargaLoteSVHT.class);
private java.sql.ResultSet rs = null;
private java.sql.ResultSet rs2 = null;
//private String sUrlExcel = "/data/informes/cargapretasaExcel/LoteSVHT/Stock_L3T_VALTECNIC_v04072017.xls"; 1º excel que se cargo en lotesvht
//private String sUrlExcel = "/data/informes/cargapretasaExcel/LoteSVHT/Stock_ACT_BC-CABK 10082017 VALTECNIC_ID.xls"; 2º excel que se cargo en lotesvht
//private String sUrlExcel = "/data/informes/cargapretasaExcel/LoteSVHT/Stock_ACT_BC-CABK 29082017 VALTECNIC_ID.xls";
//private String sUrlExcel = "/data/informes/cargapretasaExcel/LoteSVHT/Stock_ACT_BC-CABK 29082017 VALTECNIC_ID_2.xls";
//private String sUrlExcel = "/data/informes/cargapretasaExcel/LoteSVHT/Stock_ACT_BC-CABK 29082017 VALTECNIC_ID_2_mio.xls";
private String sUrlExcel = "/data/informes/cargapretasaExcel/LoteSVHT/VALTECNIC_Perímetro_L2T_0731_13042018_mio.xls";
private Utilidades.Excel oExcel = null;
private org.apache.poi.hssf.usermodel.HSSFCell celda = null;
private String HojaActual = "Hoja1";
//campos recibidos en el excel
private String numexp = null;
private Integer sociedad = null;
private String ur = null;
private String cartera = null;
private String direccion = null;
private String poblacion = null;
private Integer codposta = null;
private String zona = null;
private String provincia = null;
private String tipoinm = null;
private String refcatastral = null;
private Integer numregistro = null;
private String finca = null;
private String tomo = null;
private String libro = null;
private String folio = null;
private String promoconjunta = null;
private String promobra = null;
private String agrupacion = null;
private String tipoagrupacion = null;
private Integer ursagrupacon = null;
private Date fchtasreferencia = null;
private Double valtasreferencia = null;
private String tipovaloracion = null;
private String tipotasacion = null;
private String lote = null;
private String tasadora = null;
private String instruccion = null;
public static void main(String[] args)
{
//CargaLoteSVHT carga = new CargaLoteSVHT("7108");
CargaLoteSVHT carga = new CargaLoteSVHT();
carga.actualizaExpedienteLote("7108");
carga = null;
System.gc();
}
/**
* Realiza la carga de datos del lote recibidos en el excel en la tabla LOTESVHT
*/
public void CargaLoteSVHT(String loteActual)
{
java.sql.Connection conexion = null;
int totalURS = 0;
int inicioURS = 0;
java.text.SimpleDateFormat formatoFecha = new java.text.SimpleDateFormat("dd-MM-yyyy");
String sInsert = null;
String sUpdate = null;
int insertadas = 0;
int noInsertadas = 0;
int nuevas = 0;
int actualizadas = 0;
java.sql.ResultSet rs = null;
String sConsulta = "";
try
{
//FICHERO LOG4J
PropertyConfigurator.configure("/data/informes/cargapretasaExcel/LoteSVHT/" + "Log4j.properties");
conexion = Utilidades.Conexion.getConnection("jdbc:oracle:thin:valtecnic2/valtecnic2@oraserver03:1521:rvtn3");
//conexion = Utilidades.Conexion.getConnection("jdbc:oracle:thin:desarrollo/des0329@oraserver04:1521:rvtn4");
conexion.setAutoCommit(false);
oExcel = new Utilidades.Excel(sUrlExcel);
//totalURS = oExcel.getMaximaFila(HojaActual);
totalURS = 3791;
logger.info("Iniciamos carga del lote: "+sUrlExcel);
for (int fila = inicioURS; fila <totalURS; fila ++)
{
clear();
sInsert = "";
try
{
//0.-Sociedad
celda = oExcel.getCeldaFilaHoja(HojaActual,fila,0);
sociedad = new Double(celda.getNumericCellValue()).intValue();
//1.- UR
celda = oExcel.getCeldaFilaHoja(HojaActual,fila,1);
ur = new Integer (new Double(celda.getNumericCellValue()).intValue()).toString();
//2.- Cartera
celda = oExcel.getCeldaFilaHoja(HojaActual,fila,2);
cartera = celda.getStringCellValue();
//3.- Direccion
celda = oExcel.getCeldaFilaHoja(HojaActual,fila,3);
direccion = Utilidades.Cadenas.procesarComillasConsulta(celda.getStringCellValue());
//4.- Poblacion
celda = oExcel.getCeldaFilaHoja(HojaActual,fila,4);
poblacion = Utilidades.Cadenas.procesarComillasConsulta(celda.getStringCellValue());
//5.- CP
celda = oExcel.getCeldaFilaHoja(HojaActual,fila,5);
codposta = new Double(celda.getNumericCellValue()).intValue();
//6.- Zona
celda = oExcel.getCeldaFilaHoja(HojaActual,fila,6);
zona = celda.getStringCellValue();
//7.- Provincia
celda = oExcel.getCeldaFilaHoja(HojaActual,fila,7);
provincia = Utilidades.Cadenas.procesarComillasConsulta(celda.getStringCellValue());
//8.- tipo inmueble
celda = oExcel.getCeldaFilaHoja(HojaActual,fila,8);
tipoinm = celda.getStringCellValue();
//9.- ref. catastral
celda = oExcel.getCeldaFilaHoja(HojaActual,fila,9);
try
{
refcatastral = celda.getStringCellValue();
}
catch (Exception e)
{
refcatastral = new Integer (new Double(celda.getNumericCellValue()).intValue()).toString();
}
//10.- nº registro
celda = oExcel.getCeldaFilaHoja(HojaActual,fila,10);
try
{
numregistro = new Integer (new Double(celda.getNumericCellValue()).intValue());
}
catch (Exception e)
{
numregistro = null;
}
//11.- finca
celda = oExcel.getCeldaFilaHoja(HojaActual,fila,11);
try
{
finca = celda.getStringCellValue();
}
catch(Exception e)
{
finca = new Integer (new Double(celda.getNumericCellValue()).intValue()).toString();
}
//12.- tomo
celda = oExcel.getCeldaFilaHoja(HojaActual,fila,12);
tomo = new Integer (new Double(celda.getNumericCellValue()).intValue()).toString();
//13.- libro
celda = oExcel.getCeldaFilaHoja(HojaActual,fila,13);
libro = new Integer (new Double(celda.getNumericCellValue()).intValue()).toString();
//14.- folio
celda = oExcel.getCeldaFilaHoja(HojaActual,fila,14);
folio = new Integer (new Double(celda.getNumericCellValue()).intValue()).toString();
//15.- promocion conjunta
celda = oExcel.getCeldaFilaHoja(HojaActual,fila,15);
try
{
if (new Double(celda.getNumericCellValue()) != null)
{
promoconjunta = new Integer (new Double(celda.getNumericCellValue()).intValue()).toString();
}
}
catch (Exception e)
{
promoconjunta = celda.getStringCellValue();
}
//16.- promocional obra
celda = oExcel.getCeldaFilaHoja(HojaActual,fila,16);
try
{
if (new Double (celda.getNumericCellValue()) != null )
{
promobra = new Integer (new Double(celda.getNumericCellValue()).intValue()).toString();
}
}
catch (Exception e)
{
promobra = celda.getStringCellValue();
}
//17.- agrupacion
celda = oExcel.getCeldaFilaHoja(HojaActual,fila,17);
try
{
if (new Double(celda.getNumericCellValue()) != null )
{
agrupacion = new Integer (new Double(celda.getNumericCellValue()).intValue()).toString();
}
}
catch (Exception e)
{
agrupacion = celda.getStringCellValue();
}
//18.- tipo agrupacion
celda = oExcel.getCeldaFilaHoja(HojaActual,fila,18);
tipoagrupacion = celda.getStringCellValue();
//19.- urs agrupacion
celda = oExcel.getCeldaFilaHoja(HojaActual,fila,19);
ursagrupacon = new Integer (new Double(celda.getNumericCellValue()).intValue());
//20.- fecha tasacion referencia
celda = oExcel.getCeldaFilaHoja(HojaActual,fila,20);
fchtasreferencia = celda.getDateCellValue();
//22.- Importe TAS Referencia
celda = oExcel.getCeldaFilaHoja(HojaActual,fila,22);
try
{
valtasreferencia = celda.getNumericCellValue();
}
catch (Exception e)
{
valtasreferencia = new Double("0");
}
//23.- Tipo valoracion referencia
celda = oExcel.getCeldaFilaHoja(HojaActual,fila,23);
try
{
tipovaloracion = celda.getStringCellValue();
}
catch (Exception e)
{
tipovaloracion = new Integer (new Double(celda.getNumericCellValue()).intValue()).toString();
}
//25.- tipo tasacion
celda = oExcel.getCeldaFilaHoja(HojaActual,fila,25);
tipotasacion = celda.getStringCellValue();
//26.- lotes de solicitud
celda = oExcel.getCeldaFilaHoja(HojaActual,fila,26);
lote = celda.getStringCellValue();
//27.- tasadora
celda = oExcel.getCeldaFilaHoja(HojaActual,fila,27);
tasadora = celda.getStringCellValue();
//28.- instruccion de solicitudes
celda = oExcel.getCeldaFilaHoja(HojaActual,fila,28);
instruccion = celda.getStringCellValue();
sConsulta = "SELECT * FROM lotesvht WHERE ur = '"+ur+"' and lotevt = '"+loteActual+"'";
rs = Utilidades.Conexion.select(sConsulta, conexion);
if (!rs.next())
{
nuevas ++;
sInsert = "INSERT INTO lotesvht VALUES (null,"+sociedad+",'"+ur+"','"+cartera+"','"+direccion+"','"+poblacion+"',"+codposta+",'"+zona+"','"+provincia+"','"+tipoinm+"','"+refcatastral+"',"+numregistro;
sInsert += ",'"+finca+"','"+tomo+"','"+libro+"','"+folio+"','"+promoconjunta+"','"+promobra+"','"+agrupacion+"','"+tipoagrupacion+"',"+ursagrupacon+",'"+formatoFecha.format(fchtasreferencia)+"',"+valtasreferencia;
sInsert += ",'"+tipovaloracion+"','"+tipotasacion+"','"+lote+"','"+tasadora+"','"+instruccion+"','"+loteActual+"')";
if (Utilidades.Conexion.insert(sInsert, conexion) == 1) insertadas ++;
else noInsertadas ++;
}
else if (rs.getString("valtasreferencia") == null || rs.getDouble("valtasreferencia") == new Double(0))
{
actualizadas ++;
sUpdate = "UPDATE lotesvht SET valtasreferencia = "+valtasreferencia+" WHERE ur= '"+ur+"'";
if (Utilidades.Conexion.update(sUpdate, conexion) == 1)
{
logger.info("Actualizado valor de tasación de la UR: "+ur+". Fila: "+fila);
insertadas ++;
}
else
{
logger.error ("NO se ha Actualizado valor de tasación de la UR: "+ur+". Fila: "+fila);
}
}
else insertadas ++;
rs.close();
rs = null;
}
catch (Exception e)
{
noInsertadas ++;
logger.error("Excepción en la inserción de la UR: "+ur+". Fila: "+fila+". Descripción: "+e.toString());
}
}// for
if (insertadas == totalURS)
{
conexion.commit();
logger.info("Insertadas: "+insertadas+" filas");
}
else
{
conexion.rollback();
logger.info("Insertadas: "+insertadas+" .Fallidad: "+noInsertadas);
}
logger.info("Nuevas: "+nuevas);
logger.info("Actualizadas: "+actualizadas);
conexion.close();
conexion = null;
}
catch (Exception e)
{
logger.error("Excepción en la carga del lote: "+sUrlExcel+". Descripción: "+e.toString());
}
finally
{
try
{
if (conexion != null && !conexion.isClosed()) conexion.close();
}
catch (java.sql.SQLException sqlException)
{
logger.error("Imposible cerrar conexión con la B.D");
}
logger.info("Finalizamos carga del lote: "+sUrlExcel);
}
}
public void actualizaExpedienteLote(String loteActual)
{
java.sql.Connection conexion02 = null;
//java.sql.Connection conexion03 = null;
java.sql.ResultSet rsLotesvht = null;
java.sql.ResultSet rsUrDadasdeAlta = null;
String sConsulta = "";
String sConsulta2 = "";
String sUpdate = "";
int numurdadasdealta = 0;
String numexpvt = "";
try
{
PropertyConfigurator.configure("/data/informes/cargapretasaExcel/LoteSVHT/" + "Log4j.properties");
conexion02 = Utilidades.Conexion.getConnection("jdbc:oracle:thin:valtecnic2/valtecnic2@oraserver03:1521:rvtn3");
conexion02.setAutoCommit(false);
//conexion03 = Utilidades.Conexion.getConnection("jdbc:oracle:thin:desarrollo/des0329@oraserver03:1521:rvtn3");
//conexion03.setAutoCommit(false);
sConsulta = "SELECT * FROM lotesvht WHERE numexp is null and lotevt = '"+loteActual+"'";
rsLotesvht = Utilidades.Conexion.select(sConsulta, conexion02);
while (rsLotesvht.next())
{
numurdadasdealta = 0;
numexpvt = "";
sConsulta2 = "select s.numexp,s.fchenc,d.numseguim from datosreg d join solicitudes s on d.numexp = s.numexp where s.codcli in (255,355,755,888,1055) and s.fchenc > '17042018' and s.codest != 5 and d.numseguim is not null and d.numseguim = '"+rsLotesvht.getString("ur")+"'";
rsUrDadasdeAlta = Utilidades.Conexion.select(sConsulta2, conexion02);
while (rsUrDadasdeAlta.next())
{
numurdadasdealta ++;
numexpvt = rsUrDadasdeAlta.getString("numexp");
}
if (numurdadasdealta == 1)
{
sUpdate = "update lotesvht set numexp = '"+numexpvt+"' where ur = '"+rsLotesvht.getString("ur")+"' and lotevt = '"+loteActual+"'";
if (Utilidades.Conexion.update(sUpdate, conexion02) == 1)
{
conexion02.commit();
logger.info("Actualizado numexp: "+numexpvt+" para la ur: "+rsLotesvht.getString("ur"));
}
else
{
conexion02.rollback();
logger.error("Imposible actualizar numexp: "+numexpvt+" para la ur: "+rsLotesvht.getString("ur"));
}
}
else
{
if (numurdadasdealta > 1) logger.error("La ur: "+rsLotesvht.getString("ur")+" está asignada a mas de 1 expediente. Total en: "+numurdadasdealta);
}
}
conexion02.close();
conexion02 = null;
//conexion03.close();
//conexion03 = null;
}
catch (Exception e)
{
logger.error("Excepción en la carga del lote: "+sUrlExcel+". Descripción: "+e.toString());
}
finally
{
try
{
if (conexion02 != null && !conexion02.isClosed()) conexion02.close();
}
catch (java.sql.SQLException sqlException)
{
logger.error("Imposible cerrar conexión con la B.D conexion02");
}
/*
try
{
if (conexion03 != null && !conexion03.isClosed()) conexion03.close();
}
catch (java.sql.SQLException sqlException)
{
logger.error("Imposible cerrar conexión con la B.D conexion03");
}
*/
}
}
private void clear()
{
sociedad = null;
ur = null;
cartera = null;
direccion = null;
poblacion = null;
codposta = null;
zona = null;
provincia = null;
tipoinm = null;
refcatastral = null;
numregistro = null;
finca = null;
tomo = null;
libro = null;
folio = null;
promoconjunta = null;
promobra = null;
agrupacion = null;
tipoagrupacion = null;
ursagrupacon = null;
fchtasreferencia = null;
valtasreferencia = null;
tipovaloracion = null;
tipotasacion = null;
lote = null;
tasadora = null;
instruccion = null;
}
}
|
package com.nju.edu.cn.model;
import com.nju.edu.cn.entity.FuturesUpdating;
/**
* Created by shea on 2018/10/19.
*/
public class FuturesUpdatingBean extends FuturesUpdating {
private String timeStr;
public String getTimeStr() {
return timeStr;
}
public void setTimeStr(String timeStr) {
this.timeStr = timeStr;
}
public Long futuresId;
public Long getFuturesId() {
return futuresId;
}
public void setFuturesId(Long futuresId) {
this.futuresId = futuresId;
}
}
|
public class Vehicle {
private String brand; // Vehicle parent class
public void setBrand(String brand) {
this.brand = brand;
}
public String getBrand() {
return brand;
}
public void honk() { // Vehicle method
System.out.println("honk, honkkk!");
}
}
class Car extends Vehicle { //extend parent class and attributes
private String modelName; // Car attribute
public void setModelName(String modelName) {
this.modelName = modelName;
}
public String getModelName() {
return modelName;
}
}
|
package br.ufc.ong.model;
import javax.persistence.*;
import java.io.Serializable;
@Entity
@Table(name = "animal")
public class Animal implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id_animal")
private Long id;
private String nome;
private String especie;
private String raça;
private String caracteristicas;
public Animal() {
}
public Animal(Long id, String nome, String especie, String raça, String caracteristicas) {
this.id = id;
this.nome = nome;
this.especie = especie;
this.raça = raça;
this.caracteristicas = caracteristicas;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getEspecie() {
return especie;
}
public void setEspecie(String especie) {
this.especie = especie;
}
public String getRaça() {
return raça;
}
public void setRaça(String raça) {
this.raça = raça;
}
public String getCaracteristicas() {
return caracteristicas;
}
public void setCaracteristicas(String caracteristicas) {
this.caracteristicas = caracteristicas;
}
}
|
public class Chapter07 {
public static void main (String[] args) {
int lunchMoney = 800;
// if (lunchMoney >= 800 ) {
// System.out.println("チャーシューメンが食べられます");
// } else if (600 < lunchMoney) {
// System.out.println("ラーメンが食べられます");
// } else {
// System.out.println("どのラーメンも食べられません");
// }
switch (lunchMoney) {
// caseには、定数のみ設定できる。
case 800:
System.out.println("チャーシューメンが食べられます");
break;
case 600:
System.out.println("ラーメンが食べられます");
break;
default:
System.out.println("どのラーメンも食べられません");
}
}
}
|
package mars.model;
import mars.exceptions.IllegalMovementException;
/**
* Contém as funções basicas que um robo deve implementar.
*
* @author gabriel
*
*/
public interface Robot {
/**
* Um robo sempre estará virado para uma das posições representadas por este Enum, Norte, Sul, Leste ou Oeste.
*
* @author gabriel
*
*/
enum Face {
N,
E,
S,
W;
};
/**
*
* Realiza um movimento do robo.
*
* @param c O movimento que o robo deverá realizar.
* @return A posição do robo após a execução do movimento
*
* @throws IllegalArgumentException Caso seja um movimento incorreto ou se o movimento provocar a ida
* do robo para fora da área do terreno.
*/
public String move(char c) throws IllegalMovementException;
/**
*
* Retorna a posição atual do robo.
*
* @return A posição atual do robo.
*/
public String getPosition();
}
|
package com.zhonghui.auditcloud.core.provider;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;
@SpringBootApplication
@MapperScan("com.zhonghui.auditcloud.core.provider.mapper")
@ComponentScan(basePackages = { "com.zhonghui.auditcloud.core.provider" })
@EnableEurekaClient
@EnableTransactionManagement
@EnableFeignClients
@EnableScheduling
@EnableAutoConfiguration
@EnableAsync
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
|
/*
* 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.webbeans.configurator;
import jakarta.enterprise.inject.spi.BeanAttributes;
import jakarta.enterprise.inject.spi.configurator.BeanAttributesConfigurator;
import jakarta.enterprise.util.TypeLiteral;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;
import java.util.HashSet;
import java.util.Set;
import org.apache.webbeans.annotation.AnyLiteral;
import org.apache.webbeans.component.BeanAttributesImpl;
import org.apache.webbeans.config.WebBeansContext;
import org.apache.webbeans.util.GenericsUtil;
public class BeanAttributesConfiguratorImpl<T> implements BeanAttributesConfigurator<T>
{
private final WebBeansContext webBeansContext;
private Set<Type> types;
private Set<Annotation> qualifiers;
private Class<? extends Annotation> scope;
private String name;
private Set<Class<? extends Annotation>> stereotypes;
private boolean alternative;
public BeanAttributesConfiguratorImpl(WebBeansContext webBeansContext, BeanAttributes<T> originalBeanAttribute)
{
this.webBeansContext = webBeansContext;
this.types = new HashSet<>(originalBeanAttribute.getTypes());
this.qualifiers = new HashSet<>(originalBeanAttribute.getQualifiers());
this.scope = originalBeanAttribute.getScope();
this.name = originalBeanAttribute.getName();
this.stereotypes = new HashSet<>(originalBeanAttribute.getStereotypes());
this.alternative = originalBeanAttribute.isAlternative();
}
@Override
public BeanAttributesConfigurator<T> addType(Type type)
{
types.add(type);
return this;
}
@Override
public BeanAttributesConfigurator<T> addType(TypeLiteral typeLiteral)
{
types.add(typeLiteral.getType());
return this;
}
@Override
public BeanAttributesConfigurator<T> addTypes(Type... types)
{
for (Type type : types)
{
this.types.add(type);
}
return this;
}
@Override
public BeanAttributesConfigurator<T> addTypes(Set set)
{
types.addAll(set);
return this;
}
@Override
public BeanAttributesConfigurator<T> addTransitiveTypeClosure(Type type)
{
Set<Type> typeClosure = GenericsUtil.getTypeClosure(type, type);
types.addAll(typeClosure);
return this;
}
@Override
public BeanAttributesConfigurator<T> types(Type... types)
{
this.types.clear();
addTypes(types);
return this;
}
@Override
public BeanAttributesConfigurator<T> types(Set<Type> set)
{
this.types.clear();
addTypes(set);
return this;
}
@Override
public BeanAttributesConfigurator<T> scope(Class<? extends Annotation> scope)
{
this.scope = scope;
return this;
}
@Override
public BeanAttributesConfigurator<T> addQualifier(Annotation qualifier)
{
qualifiers.add(qualifier);
return this;
}
@Override
public BeanAttributesConfigurator<T> addQualifiers(Annotation... qualifiers)
{
for (Annotation qualifier : qualifiers)
{
addQualifiers(qualifier);
}
return this;
}
@Override
public BeanAttributesConfigurator<T> addQualifiers(Set<Annotation> qualifiers)
{
this.qualifiers.addAll(qualifiers);
return this;
}
@Override
public BeanAttributesConfigurator<T> qualifiers(Annotation... qualifiers)
{
this.qualifiers.clear();
for (Annotation qualifier : qualifiers)
{
addQualifier(qualifier);
}
return this;
}
@Override
public BeanAttributesConfigurator<T> qualifiers(Set<Annotation> qualifiers)
{
this.qualifiers.clear();
addQualifiers(qualifiers);
return this;
}
@Override
public BeanAttributesConfigurator<T> addStereotype(Class<? extends Annotation> stereotype)
{
stereotypes.add(stereotype);
return this;
}
@Override
public BeanAttributesConfigurator<T> addStereotypes(Set<Class<? extends Annotation>> stereotypes)
{
this.stereotypes.addAll(stereotypes);
return this;
}
@Override
public BeanAttributesConfigurator<T> stereotypes(Set<Class<? extends Annotation>> stereotypes)
{
this.stereotypes.clear();
addStereotypes(stereotypes);
return this;
}
@Override
public BeanAttributesConfigurator<T> name(String name)
{
this.name = name;
return this;
}
@Override
public BeanAttributesConfigurator<T> alternative(boolean value)
{
this.alternative = value;
return this;
}
public BeanAttributes<T> getBeanAttributes()
{
// make sure we always have an @Any Qualifier as well.
qualifiers.add(AnyLiteral.INSTANCE);
return new BeanAttributesImpl<>(types, qualifiers, scope, name, stereotypes, alternative);
}
}
|
package pt.smartthought.url.shortner.api.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.validation.constraints.NotEmpty;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
@NoArgsConstructor
@AllArgsConstructor
@Data
public class UrlDto {
@NotNull
@NotEmpty
@Size(min = 1)
@Pattern(regexp = "((([A-Za-z]{3,9}:(?:\\/\\/)?)(?:[-;:&=\\+\\$,\\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\\+\\$,\\w]+@)[A-Za-z0-9.-]+)((?:\\/[\\+~%\\/.\\w-_]*)?\\??(?:[-\\+=&;%@.\\w_]*)#?(?:[\\w]*))?)")
private String url;
}
|
package com.showdy.hotfix;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class ReflectUtils {
public static Field findField(Object object, String name) throws NoSuchFieldException {
Class<?> clazz = object.getClass();
try {
while (clazz != Object.class) {
Field field = clazz.getDeclaredField(name);
if (field != null) {
//允许访问
field.setAccessible(true);
return field;
}
//可能属性在父类中...
clazz = clazz.getSuperclass();
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
throw new NoSuchFieldException(object.getClass().getSimpleName() + "not find field" + name);
}
public static Method findMethod(Object object, String name,Class<?>... paramsTypes) throws NoSuchMethodException {
Class<?> clazz = object.getClass();
try {
while (clazz != Object.class) {
Method method = clazz.getDeclaredMethod(name, paramsTypes);
if (method != null) {
//允许访问
method.setAccessible(true);
return method;
}
//可能属性在父类中...
clazz = clazz.getSuperclass();
}
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
throw new NoSuchMethodException(object.getClass().getSimpleName() + "not find method " + name);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.