text stringlengths 10 2.72M |
|---|
package UI;
import java.awt.Insets;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import com.sun.prism.Image;
public class MyButton extends JButton{
private ImageIcon enableIcon, disableIcon, normalIcon;
private String tip;
public MyButton(ImageIcon normalIcon, ImageIcon enableIcon, ImageIcon disableIcon, String tip) {
super(normalIcon);
this.enableIcon = enableIcon;
this.disableIcon = disableIcon;
this.tip = tip;
initialize();
setUp();
}
private void initialize() {
this.setBorderPainted(false);
this.setFocusPainted(false);
this.setContentAreaFilled(false);
this.setFocusable(true);
this.setMargin(new Insets(0, 0, 0, 0));
}
private void setUp() {
this.setRolloverIcon(enableIcon);
// this.setSelectedIcon(iconEnable);
this.setPressedIcon(enableIcon);
this.setDisabledIcon(enableIcon);
if (!tip.equals("")) {
this.setToolTipText(tip);
}
}
public void setIconEnable() {
this.setIcon(enableIcon);
}
public void setIconDisable() {
this.setIcon(disableIcon);
}
}
|
package com.chaoqian.webus.core;
import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import com.chaoqian.webus.R;
import com.chaoqian.webus.adapter.Menu2Adapter;
import com.chaoqian.webus.adapter.Menu4Adapter;
import com.chaoqian.webus.bean.InHouse;
import com.chaoqian.webus.bean.OutHouse;
import com.chaoqian.webus.utils.DialogUtils;
import com.chaoqian.webus.utils.MyApplication;
import com.chaoqian.webus.utils.MyCallBack;
import com.chaoqian.webus.utils.Tools;
import com.chaoqian.webus.utils.XUtils;
import com.chaoqian.webus.view.ListViewDecoration;
import com.google.gson.Gson;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@ContentView(R.layout.activity_meun4)
public class Meun4Activity extends BaseActivity {
private Activity mContext;
private Menu4Adapter mMenuAdapter;
@ViewInject(R.id.recycler_view)
private SwipeMenuRecyclerView mMenuRecyclerView;
@ViewInject(R.id.create_btn)
private ImageView create_btn;
private List<OutHouse> mDataList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
mDataList = new ArrayList<>();
mMenuRecyclerView.setLayoutManager(new LinearLayoutManager(this));// 布局管理器。
mMenuRecyclerView.setHasFixedSize(true);// 如果Item够简单,高度是确定的,打开FixSize将提高性能。
mMenuRecyclerView.setItemAnimator(new DefaultItemAnimator());// 设置Item默认动画,加也行,不加也行。
mMenuRecyclerView.addItemDecoration(new ListViewDecoration());// 添加分割线。*/
mMenuAdapter = new Menu4Adapter(mDataList);
mMenuRecyclerView.setAdapter(mMenuAdapter);
}
@Event(value = R.id.create_btn)
private void create(View v) {
Intent intent = new Intent(mContext, Modify4Activity.class);
startActivity(intent);
}
@Override
protected void onResume() {
super.onResume();
getData();
}
/**
* 查询数据
* @return
*/
private void getData() {
final Gson gson = new Gson();
/* for (int i = 0; i < 10; i++) {
Commodity c = new Commodity();
String jsonString = "{\"shangpinMingcheng\":\"阿司匹林" + i + "\"}";
c = gson.fromJson(jsonString, Commodity.class);
mDataList.add(c);
}
Message message = new Message();
message.what = 1;
handler.handleMessage(message);*/
String url = MyApplication.OUTHOUSE_QUERYURL;
Map<String, String> params = new HashMap<>();
DialogUtils.getInstance().show(this, "加载数据中...");
XUtils.Get(url, params, new MyCallBack<String>(){
@Override
public void onSuccess(String result) {
super.onSuccess(result);
final Gson gson = new Gson();
try {
DialogUtils.getInstance().close();
mDataList.clear();
JSONObject object = new JSONObject(result);
JSONArray array = object.getJSONArray("obj");
for (int i = 0; i < array.length(); i++) {
OutHouse outHouse = gson.fromJson(array.getJSONObject(i).toString(), OutHouse.class);
mDataList.add(outHouse);
}
Message message = new Message();
message.what = 1;
handler.handleMessage(message);
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(MyApplication.context, "连接超时,请重新登陆!", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(mContext, LoginActivity.class);
startActivity(intent);
finish();
}
}
@Override
public void onError(Throwable ex, boolean isOnCallback) {
super.onError(ex, isOnCallback);
Tools.requestError(ex);
}
});
}
/**
* 用于在子线程中更新UI
*/
Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 1:
mMenuAdapter.notifyDataSetChanged();
break;
default:
break;
}
}
};
@Event(value = R.id.tbar_back)
private void back(View v) {
finish();
}
}
|
import java.util.Scanner;
class circle
{
private int r;
private double area;
void firstInit(int r)
{
this.r = r;
}
void area()
{
area = 3.14*(r * r);
}
void show()
{
System.out.println("Area of Circle = "+area);
}
}
class prog34
{
public static void main(String[] args)
{
circle c = new circle();
Scanner sc = new Scanner(System.in);
System.out.println("Enter radius");
int x = sc.nextInt();
c.firstInit(x);
c.area();
c.show();
}
} |
package simulated_annealing;
public class SimulatedAnnealing {
private SingleTour actualRoot;
private SingleTour nextRoot;
private SingleTour bestRoot;
public void simulate(){
double temperature = Constants.MAX_TEMPERATURE;
actualRoot = new SingleTour();
actualRoot.generateTour();
bestRoot = new SingleTour(actualRoot.getTour());
System.out.println("Initial solution distance: " + actualRoot.calculateTourDistance());
while(temperature > Constants.MIN_TEMPERATURE){
nextRoot = generateAnotherTour(actualRoot);
double currentDistance = actualRoot.calculateTourDistance();
double neighbourDistance = nextRoot.calculateTourDistance();
if(acceptanceProbability(currentDistance, neighbourDistance, temperature) > Math.random()) {// if we get 1, next root becomes actual root
actualRoot = nextRoot;
currentDistance = neighbourDistance;
}
if(currentDistance < bestRoot.calculateTourDistance()){
bestRoot = actualRoot; // here we stock the best distance
}
temperature *= 1 - Constants.COOLING_RATE; // here we manage the number of iterations
}
}
// we swap 2 cities randomly
private SingleTour generateAnotherTour(SingleTour actualState) {
SingleTour newState = new SingleTour(actualState.getTour());
int randomIndex1 = (int) (Math.random() * newState.getTourSize());
int randomIndex2 = (int) (Math.random() * newState.getTourSize());
City city1 = newState.getCity(randomIndex1);
City city2 = newState.getCity(randomIndex2);
newState.setCity(randomIndex1, city2);
newState.setCity(randomIndex2, city1);
return newState;
}
public SingleTour getBest(){
return bestRoot;
}
private double acceptanceProbability(double currentDistance, double nextDistance, double temperature){
if(nextDistance < currentDistance ) return 1.0; // because we look for the shortest path
// otherwise we use the Metropolis function
double exp = Math.exp((currentDistance - nextDistance) / temperature);
System.out.println(" acceptance probability = ((" + currentDistance + " - " + nextDistance + ") / " + temperature + ") = " + exp);
return exp; // (currentDistance-neighbourDistance)/temperature
}
}
|
package spi.movieorganizer.data.genre;
import java.util.Locale;
import spi.movieorganizer.data.MovieOrganizerType;
import spi.movieorganizer.data.util.StringMultiLang;
import exane.osgi.jexlib.data.object.AbstractDataObject;
import exane.osgi.jexlib.data.object.ExaneDataType;
public class GenreDO extends AbstractDataObject<Integer> {
private final StringMultiLang name;
public GenreDO(final int id, final StringMultiLang name) {
super(id);
this.name = name;
}
public String getName(final Locale locale) {
return this.name.getValue(locale);
}
public void setName(final Locale locale, final String value) {
this.name.addValue(locale, value);
}
public StringMultiLang getNameMultiLang() {
return this.name;
}
@Override
public String toString() {
return "id: " + getIdentifier() + " " + this.name;
}
@Override
public ExaneDataType getDataType() {
return MovieOrganizerType.GENRE;
}
}
|
package com.vilio.nlbs.commonMapper.dao;
import com.vilio.nlbs.commonMapper.pojo.NlbsApplyLoanStatus;
import java.util.List;
/**
* Created by dell on 2017/5/26.
*/
public interface NlbsApplyLoanStatusMapper {
List<NlbsApplyLoanStatus> queryAllLocalStatus();
}
|
package com.dennistjahyadigotama.soaya.activities.ThreadEditActivity;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.dennistjahyadigotama.soaya.QuickstartPreferences;
import com.dennistjahyadigotama.soaya.R;
import com.dennistjahyadigotama.soaya.User;
import com.dennistjahyadigotama.soaya.activities.SelectCategoryActivity;
import com.dennistjahyadigotama.soaya.activities.ThreadEditActivity.adapter.ImageGetter;
import com.dennistjahyadigotama.soaya.activities.ThreadEditActivity.adapter.RecyclerImageAdapter;
import com.theartofdev.edmodo.cropper.CropImage;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Created by Denn on 7/4/2016.
*/
public class ThreadEditActivity extends AppCompatActivity {
TextView buttonSave,insertImage;
EditText etTitle,etCategory,etContent;
RecyclerView recyclerViewImages;
Toolbar toolbar;
RequestQueue requestQueue;
RecyclerImageAdapter adapter;
List<ImageGetter> imagesGetterList = new ArrayList<>();
String category;
String url= User.threadEditActivityUrl;
String threadId;
private ProgressBar progressBar;
private TextView txtPercentage;
private Uri mCropImageUri;
int orderPicForUpload = 0;
RelativeLayout loadingPanel;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.thread_edit_activity);
threadId=getIntent().getStringExtra("threadId");
SharedPreferences sharedPreferences = getSharedPreferences("prefs", Context.MODE_PRIVATE);
User.username=sharedPreferences.getString(QuickstartPreferences.USERNAME,null);
requestQueue = Volley.newRequestQueue(this);
toolbar = (Toolbar)findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("Edit");
SetAllView();
etTitle.setText(getIntent().getStringExtra("title"));
etCategory.setText(getIntent().getStringExtra("category"));
category = etCategory.getText().toString();
etContent.setText(getIntent().getStringExtra("content"));
GetThreadImagesForUpdate();
}
private void SetAllView()
{
progressBar = (ProgressBar)findViewById(R.id.progressBar);
txtPercentage = (TextView)findViewById(R.id.txtPercentage);
buttonSave = (TextView)findViewById(R.id.buttonSave);
loadingPanel = (RelativeLayout)findViewById(R.id.loadingPanel);
loadingPanel.setVisibility(View.GONE);
etTitle = (EditText)findViewById(R.id.editTextTitle);
etContent = (EditText)findViewById(R.id.editTextContent);
etCategory = (EditText)findViewById(R.id.editTextCategory);
etCategory.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
public void onDestroyActionMode(ActionMode mode) {
}
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
return false;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return false;
}
});
recyclerViewImages = (RecyclerView)findViewById(R.id.recycler_view);
adapter = new RecyclerImageAdapter(imagesGetterList);
LinearLayoutManager layoutManager = new LinearLayoutManager(this);
recyclerViewImages.setLayoutManager(layoutManager);
recyclerViewImages.setItemAnimator(new DefaultItemAnimator());
recyclerViewImages.setAdapter(adapter);
recyclerViewImages.setNestedScrollingEnabled(false);
insertImage = (TextView)findViewById(R.id.insertImage);
insertImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
CropImage.startPickImageActivity(ThreadEditActivity.this);
}
});
etCategory.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i =new Intent(getApplicationContext(),SelectCategoryActivity.class);
startActivityForResult(i,121);
}
});
buttonSave.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
loadingPanel.setVisibility(View.VISIBLE);
buttonSave.setEnabled(false);
etCategory.setEnabled(false);
etContent.setEnabled(false);
etTitle.setEnabled(false);
insertImage.setEnabled(false);
UploadContent();
}
});
}
private void GetThreadImagesForUpdate()
{
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(url+"?GetImagesForUpdate="+threadId, new Response.Listener<JSONArray>() {
@Override
public void onResponse(JSONArray response) {
String id,url;
try {
for(int i=0;i<response.length();i++){
final JSONObject jsonObject = response.getJSONObject(i);
final ImageGetter imageGetter = new ImageGetter();
id=jsonObject.getString("id");
url=jsonObject.getString("url");
imageGetter.setId(id);
imageGetter.setImageUrl(url);
imageGetter.setCaption(jsonObject.getString("caption"));
imagesGetterList.add(imageGetter);
adapter.notifyDataSetChanged();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonArrayRequest);
}
private void UploadContent(){
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(response);
if(jsonObject.names().get(0).equals("success"))
{
if (imagesGetterList.size() > 0) {
new UploadToServer().execute();
}
else
{
Toast.makeText(getApplicationContext(),jsonObject.getString("success"), Toast.LENGTH_SHORT).show();
finish();
}
}
else
{
Toast.makeText(getApplicationContext(),jsonObject.getString("error"), Toast.LENGTH_SHORT).show();
loadingPanel.setVisibility(View.GONE);
buttonSave.setEnabled(true);
etCategory.setEnabled(true);
etContent.setEnabled(true);
etTitle.setEnabled(true);
insertImage.setEnabled(true);
}
} catch (JSONException e) {
e.printStackTrace();
loadingPanel.setVisibility(View.GONE);
buttonSave.setEnabled(true);
etCategory.setEnabled(true);
etContent.setEnabled(true);
etTitle.setEnabled(true);
insertImage.setEnabled(true);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
loadingPanel.setVisibility(View.GONE);
buttonSave.setEnabled(true);
etCategory.setEnabled(true);
etContent.setEnabled(true);
etTitle.setEnabled(true);
insertImage.setEnabled(true);
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> hashMap = new HashMap<>();
hashMap.put("username", User.username);
hashMap.put("threadId",threadId);
hashMap.put("edittitle",etTitle.getText().toString());
hashMap.put("editcategory",category);
hashMap.put("editcontent",etContent.getText().toString());
return hashMap;
}
};
requestQueue.add(stringRequest);
}
@Override
@SuppressLint("NewApi")
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CropImage.PICK_IMAGE_CHOOSER_REQUEST_CODE && resultCode == AppCompatActivity.RESULT_OK) {
Uri imageUri = CropImage.getPickImageResultUri(this, data);
// For API >= 23 we need to check specifically that we have permissions to read external storage,
// but we don't know if we need to for the URI so the simplest is to try open the stream and see if we get error.
boolean requirePermissions = false;
if (CropImage.isReadExternalStoragePermissionsRequired(this, imageUri)) {
// request permissions and handle the result in onRequestPermissionsResult()
requirePermissions = true;
mCropImageUri = imageUri;
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, CropImage.PICK_IMAGE_PERMISSIONS_REQUEST_CODE);
} else {
/* Intent i = new Intent(this, CropActivity.class);
i.putExtra("imageUri",imageUri.toString());
startActivity(i);*/
SetImages(imageUri);
}
}else if(requestCode==121)
{
if(resultCode== Activity.RESULT_OK)
{
etCategory.setText(data.getStringExtra("category"));
category=data.getStringExtra("category");
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
if (requestCode == CropImage.CAMERA_CAPTURE_PERMISSIONS_REQUEST_CODE) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
CropImage.startPickImageActivity(this);
} else {
Toast.makeText(this, "Cancelling, required permissions are not granted", Toast.LENGTH_LONG).show();
}
}
if (requestCode == CropImage.PICK_IMAGE_PERMISSIONS_REQUEST_CODE) {
if (mCropImageUri != null && grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
/* Intent i = new Intent(this, CropActivity.class);
i.putExtra("imageUri",mCropImageUri.toString());
startActivity(i);*/
SetImages(mCropImageUri);
} else {
Toast.makeText(this, "Cancelling, required permissions are not granted", Toast.LENGTH_LONG).show();
}
}
}
private void SetImages(Uri uri){
ImageGetter imagesGetter = new ImageGetter();
imagesGetter.setUri(uri);
imagesGetter.setCaption("");
imagesGetterList.add(imagesGetter);
adapter.notifyDataSetChanged();
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId())
{
case android.R.id.home:
finish();
break;
}
return super.onOptionsItemSelected(item);
}
private class UploadToServer extends AsyncTask<Void,Integer,String> {
@Override
protected void onPreExecute() {
progressBar.setProgress(0);
super.onPreExecute();
}
@Override
protected void onProgressUpdate(Integer... values) {
progressBar.setVisibility(View.VISIBLE);
progressBar.setProgress(values[0]);
txtPercentage.setText(String.valueOf(values[0])+"%");
}
@Override
protected String doInBackground(Void... params) {
return UploadFile();
}
private String UploadFile(){
final String[] responseString = {null};
StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
responseString[0] = jsonObject.getString("success");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
responseString[0] =error.getMessage();
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String,String> hashMap = new HashMap<>();
hashMap.put("username", User.username);
hashMap.put("threadId",threadId);
hashMap.put("encoded",imagesGetterList.get(orderPicForUpload).getEncoded());
String caption;
if(imagesGetterList.get(orderPicForUpload).getCaption()==null)
{
caption = "";
}else
{
caption = imagesGetterList.get(orderPicForUpload).getCaption();
}
hashMap.put("caption",caption);
return hashMap;
}
};
requestQueue.add(stringRequest);
return responseString[0];
}
@Override
protected void onPostExecute(String s)
{
//Toast.makeText(getApplicationContext(),"upload images "+orderPicForUpload+" Success",Toast.LENGTH_SHORT).show();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
// Do something after 5s = 5000ms
orderPicForUpload +=1;
if(orderPicForUpload==imagesGetterList.size())
{
Toast.makeText(getApplicationContext(),"Success", Toast.LENGTH_SHORT).show();
orderPicForUpload = 0;
finish();
}else
{
new UploadToServer().execute();
}
}
}, 1000);
super.onPostExecute(s);
}
}
private void showAlert(String message) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message).setTitle("Response from Servers")
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// do nothing
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
|
package duke.command;
import duke.Storage;
import duke.Ui;
import duke.task.TaskList;
/**
* This command shows the welcome message.
*/
public class WelcomeCommand extends Command {
/**
* Shows the welcome message.
*
* @param tasks task list
* @param storage storage
* @param ui ui
* @return the welcome message.
*/
@Override
public String execute(TaskList tasks, Storage storage, Ui ui) {
return Ui.showWelcome();
}
}
|
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.event.KeyEvent;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import net.tinyos.message.Message;
import net.tinyos.message.MessageListener;
import net.tinyos.message.MoteIF;
public class TabbedView extends JPanel implements MessageListener {
private MoteIF moteif = new MoteIF();
protected JComponent makeTextPanel(String label) {
JPanel panel = new JPanel(false);
JLabel text = new JLabel(label);
text.setHorizontalAlignment(JLabel.CENTER);
panel.setLayout(new GridLayout(1, 1));
panel.add(text);
return panel;
}
public void messageReceived(int toAddr, Message msg) {
if (msg instanceof SensorMessage) {
SensorMessage sm = (SensorMessage) msg;
System.out.println("Time =" + System.currentTimeMillis());
System.out.println("\tVoltage: " + sm.get_voltage());
System.out.println("\tHumidity: " + sm.get_humidity());
System.out.println("\tTemperature: " + sm.get_temperature());
System.out.println("\tTSR: " + sm.get_solarRadiation());
System.out.println("\tPSR: " + sm.get_photoRadiation());
}
}
VoltageGraphPanel voltageGraphPanel = new VoltageGraphPanel();
JComponent humidityGraphPanel = makeTextPanel("Humidity");
JComponent temperatureGraphPanel = makeTextPanel("Temperature");
JComponent tsrGraphPanel = makeTextPanel("TSR");
JComponent psrGraphPanel = makeTextPanel("PSR");
public TabbedView() {
super(new GridLayout(1, 1));
moteif.registerListener(new SensorMessage(), this);
setPreferredSize(new Dimension(400, 400));
JTabbedPane tabbedPane = new JTabbedPane();
tabbedPane.addTab("Voltage", voltageGraphPanel);
tabbedPane.setMnemonicAt(0, KeyEvent.VK_1);
tabbedPane.addTab("Humidity", humidityGraphPanel);
tabbedPane.setMnemonicAt(1, KeyEvent.VK_2);
tabbedPane.addTab("Temperature", temperatureGraphPanel);
tabbedPane.setMnemonicAt(2, KeyEvent.VK_3);
tabbedPane.addTab("TSR", tsrGraphPanel);
tabbedPane.setMnemonicAt(3, KeyEvent.VK_4);
tabbedPane.addTab("PSR", psrGraphPanel);
tabbedPane.setMnemonicAt(4, KeyEvent.VK_5);
this.add(tabbedPane);
tabbedPane.setTabLayoutPolicy(JTabbedPane.SCROLL_TAB_LAYOUT);
}
private static void createAndShowGUI() {
JFrame frame = new JFrame("Sensor Grapher");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TabbedView(), BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
// Schedule a job for the event dispatch thread:
// creating and showing this application's GUI.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
UIManager.put("swing.boldMetal", Boolean.FALSE);
createAndShowGUI();
}
});
}
}
|
public class LecturerTest {
public static void main(String[] args) {
Lecturer lecturer = new Lecturer("Roger");
lecturer.doResearch("Java");
lecturer.teach("Ruby");
}
} |
package game.app.repositories;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import game.app.entities.Shop;
//AQUI REALIZAMOS NUESTRAS CONSULTAS
@Repository
public interface ShopRepository extends JpaRepository<Shop, Long>{
public Optional<Shop> findById(Long id);
public Optional<Shop> findByDireccion(String direccion);
}
|
package com.tt.miniapp.msg.sync;
import com.tt.miniapp.storage.Storage;
import com.tt.miniapp.util.ToolUtils;
import com.tt.miniapphost.AppBrandLogger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class GetStorageInfoSyncCtrl extends SyncMsgCtrl {
public GetStorageInfoSyncCtrl(String paramString) {
super(paramString);
}
private String buildMsg() {
long l1 = ToolUtils.byte2Kb(Storage.getStorageSize(), true);
long l2 = ToolUtils.byte2Kb(Storage.getLimitSize(), true);
JSONArray jSONArray = Storage.getKeys();
try {
JSONObject jSONObject = new JSONObject();
jSONObject.put("currentSize", l1);
jSONObject.put("limitSize", l2);
jSONObject.put("keys", jSONArray);
return makeOkMsg(jSONObject);
} catch (JSONException jSONException) {
AppBrandLogger.stacktrace(6, "SyncMsgCtrl", jSONException.getStackTrace());
return makeFailMsg((Throwable)jSONException);
}
}
public String act() {
return buildMsg();
}
public String getName() {
return "getStorageInfoSync";
}
}
/* Location: C:\Users\august\Desktop\tik\df_miniapp\classes.jar!\com\tt\miniapp\msg\sync\GetStorageInfoSyncCtrl.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 1.1.3
*/ |
package com.example.jeevanjyoti.customSpinner;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.example.jeevanjyoti.R;
import java.util.ArrayList;
import static android.graphics.Color.WHITE;
public class CustomAdapter extends ArrayAdapter<CustomItems> {
public CustomAdapter(@NonNull Context context, ArrayList<CustomItems> customList) {
super(context, 0, customList);
}
@NonNull
@Override
public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
return customView(position, convertView, parent);
}
public String add(String aString){
return aString;
}
@Override
public View getDropDownView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
return customView(position, convertView, parent);
}
public View customView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.custom_spinner_layout, parent, false);
}
CustomItems items = getItem(position);
// ImageView spinnerImage = convertView.findViewById(R.id.marital_status_image_view);
TextView spinnerName = convertView.findViewById(R.id.marital_status_name);
if (items != null) {
Log.w("CustomAdapter", "Name Of State: ");
// spinnerImage.setVisibility(View.VISIBLE);
// spinnerImage.setImageResource(items.getSpinnerImage());
spinnerName.setText(items.getSpinnerText());
}else {
spinnerName.setText(items != null ? items.getSpinnerText() : null);
}
return convertView;
}
}
|
import unitserver.*;
/**
* Created by troy on 22.11.2016.
*/
public class UnitServerHC {
public static void main(String[] args) throws InterruptedException {
UnitMap unitMap = new UnitMap();
unitMap.clear();
SettingManager settingManager = new SettingManager();
settingManager.setUnitMap(unitMap);
settingManager.clear();
DataManager dataManager = new DataManager();
dataManager.setUnitMap(unitMap);
dataManager.setSettingManager(settingManager);
ConnectorNet connectorNet = new ConnectorNet();
QueryManager queryManager = new QueryManager();
queryManager.setSettingManager(settingManager);
queryManager.setUnitMap(unitMap);
queryManager.setConnector(connectorNet);
queryManager.setDataManager(dataManager);
connectorNet.startConnector();
OutSocketServer outSocketServer = new OutSocketServer();
outSocketServer.setDataManager(dataManager);
outSocketServer.startServer();
}
}
|
package com.yixin.dsc.dto;
import java.io.Serializable;
import java.util.List;
/**
* 电子签约信息
* Package : com.yixin.dsc.dto
*
* @author YixinCapital -- wangwenlong
* 2018年7月4日 下午5:20:44
*
*/
public class DscElecActionInfoDto implements Serializable{
/**
*
*/
private static final long serialVersionUID = 2975328827945365978L;
/**
* 合同协议
*/
private List<DscSignContractDto> signContractList;
/**
* 用户行为
*/
private DscUserActionDto userActionDto;
/**
* 操作环境
*/
private DscOperateEnvDto operateEnvDto;
public List<DscSignContractDto> getSignContractList() {
return signContractList;
}
public void setSignContractList(List<DscSignContractDto> signContractList) {
this.signContractList = signContractList;
}
public DscUserActionDto getUserActionDto() {
return userActionDto;
}
public void setUserActionDto(DscUserActionDto userActionDto) {
this.userActionDto = userActionDto;
}
public DscOperateEnvDto getOperateEnvDto() {
return operateEnvDto;
}
public void setOperateEnvDto(DscOperateEnvDto operateEnvDto) {
this.operateEnvDto = operateEnvDto;
}
}
|
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
public class WebDriverSettings {
public ChromeDriver driver;
@BeforeTest
public void stUp(){
System.setProperty("webdriver.chrome.driver", "c:\\Program Files\\chromedriver\\chromedriver.exe");
driver = new ChromeDriver();
}
@AfterTest
public void close(){
// driver.quit();
}
}
|
package de.unidue.langtech.teaching.rp.pipeline;
import static org.apache.uima.fit.factory.AnalysisEngineFactory.createEngineDescription;
import static org.apache.uima.fit.factory.ExternalResourceFactory.createExternalResourceDescription;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.uima.analysis_engine.AnalysisEngineDescription;
import org.apache.uima.collection.CollectionReaderDescription;
import org.apache.uima.fit.factory.AnalysisEngineFactory;
import org.apache.uima.fit.factory.CollectionReaderFactory;
import org.apache.uima.fit.pipeline.SimplePipeline;
import de.tudarmstadt.ukp.dkpro.core.api.resources.DkproContext;
import de.tudarmstadt.ukp.dkpro.core.arktools.ArktweetTokenizer;
import de.tudarmstadt.ukp.dkpro.core.frequency.resources.Web1TFrequencyCountResource;
import de.unidue.langtech.teaching.rp.detector.JLangDetect;
import de.unidue.langtech.teaching.rp.detector.LanguageDetectorWeb1T;
import de.unidue.langtech.teaching.rp.detector.LanguageIdentifier;
import de.unidue.langtech.teaching.rp.detector.Optimaize;
import de.unidue.langtech.teaching.rp.detector.TikaLanguageIdentifier;
import de.unidue.langtech.teaching.rp.evaluator.LanguageEvaluatorConfMatrix;
import de.unidue.langtech.teaching.rp.reader.CorpusReader;
import de.unidue.langtech.teaching.rp.tools.ResultStore;
import de.unidue.langtech.teaching.rp.uimatools.Stopwatch;
import de.unidue.langtech.teaching.rp.uimatools.Writer;
/**
* Pipeline can only run for one corpus. No arrays/list of reader descriptions possible!
* Reason: Each corpora needs a different set of configuration files, languages, models.
* Reader descriptions for three corpora are already configured.
* Please configure the string array in line 76 according to the languages supported by the corpus.
* Also please set the config file for TextCat LanguageIdentifier in lines 132 - 133.
* TikaLanguageIdentifier can only load one config property file! So please edit the property file
* in src/main/resources/org/apache/tika/language accordingly!
* @author Onur
*
*/
public class MainPipeline
{
public static void main(String[] args)
throws Exception
{
String web1TBaseDir = new DkproContext().getWorkspace("Web1T").getAbsolutePath();
String twitterlidBaseDir = new DkproContext().getWorkspace("TwitterLID").getAbsolutePath();
String ligaBaseDir = new DkproContext().getWorkspace("LIGA").getAbsolutePath();
String textCatModelsBaseDir = new DkproContext().getWorkspace("textcat_models").getAbsolutePath();
//TwitterLID Corpus, Languages: de, en, fr, nl, es
CollectionReaderDescription twitterCorpus = CollectionReaderFactory.createReaderDescription(
CorpusReader.class,
CorpusReader.PARAM_INPUT_FILE, twitterlidBaseDir + "/ground-truth_full.trn"
);
//LIGA Corpus, Languages: de, en, fr, it, nl, es
@SuppressWarnings("unused")
CollectionReaderDescription ligaCorpus = CollectionReaderFactory.createReaderDescription(
CorpusReader.class,
CorpusReader.PARAM_INPUT_FILE, ligaBaseDir + "/corpus_LIGA.txt"
);
CorpusConfiguration corpus = new CorpusConfiguration(twitterCorpus, "TwitterLID_Training");
String[] languages = new String[] {"de", "en", "fr", "nl", "es"};
List<File> resultFiles = new ArrayList<File>();
List<File> scoreFiles = new ArrayList<File>();
List<File> timeFiles = new ArrayList<File>();
List<AnalysisEngineDescription> description = new ArrayList<AnalysisEngineDescription>();
description.add(AnalysisEngineFactory.createEngineDescription(JLangDetect.class,
JLangDetect.PARAM_LANGUAGES, languages));
description.add(createEngineDescription(
LanguageDetectorWeb1T.class,
LanguageDetectorWeb1T.PARAM_FREQUENCY_PROVIDER_RESOURCES,
Arrays.asList(
createExternalResourceDescription(
Web1TFrequencyCountResource.class,
Web1TFrequencyCountResource.PARAM_INDEX_PATH, web1TBaseDir + "/Euro/de",
Web1TFrequencyCountResource.PARAM_MIN_NGRAM_LEVEL, "1",
Web1TFrequencyCountResource.PARAM_MAX_NGRAM_LEVEL, "1",
Web1TFrequencyCountResource.PARAM_LANGUAGE, "de"
),
createExternalResourceDescription(
Web1TFrequencyCountResource.class,
Web1TFrequencyCountResource.PARAM_INDEX_PATH, web1TBaseDir + "/Euro/fr",
Web1TFrequencyCountResource.PARAM_MIN_NGRAM_LEVEL, "1",
Web1TFrequencyCountResource.PARAM_MAX_NGRAM_LEVEL, "1",
Web1TFrequencyCountResource.PARAM_LANGUAGE, "fr"
),
createExternalResourceDescription(
Web1TFrequencyCountResource.class,
Web1TFrequencyCountResource.PARAM_INDEX_PATH, web1TBaseDir + "/Euro/en",
Web1TFrequencyCountResource.PARAM_MIN_NGRAM_LEVEL, "1",
Web1TFrequencyCountResource.PARAM_MAX_NGRAM_LEVEL, "1",
Web1TFrequencyCountResource.PARAM_LANGUAGE, "en"
),
createExternalResourceDescription(
Web1TFrequencyCountResource.class,
Web1TFrequencyCountResource.PARAM_INDEX_PATH, web1TBaseDir + "/Euro/nl",
Web1TFrequencyCountResource.PARAM_MIN_NGRAM_LEVEL, "1",
Web1TFrequencyCountResource.PARAM_MAX_NGRAM_LEVEL, "1",
Web1TFrequencyCountResource.PARAM_LANGUAGE, "nl"
),
createExternalResourceDescription(
Web1TFrequencyCountResource.class,
Web1TFrequencyCountResource.PARAM_INDEX_PATH, web1TBaseDir + "/Euro/es",
Web1TFrequencyCountResource.PARAM_MIN_NGRAM_LEVEL, "1",
Web1TFrequencyCountResource.PARAM_MAX_NGRAM_LEVEL, "1",
Web1TFrequencyCountResource.PARAM_LANGUAGE, "es"
)//,
// createExternalResourceDescription(
// Web1TFrequencyCountResource.class,
// Web1TFrequencyCountResource.PARAM_INDEX_PATH, web1TBaseDir + "/Euro/it",
// Web1TFrequencyCountResource.PARAM_MIN_NGRAM_LEVEL, "1",
// Web1TFrequencyCountResource.PARAM_MAX_NGRAM_LEVEL, "1",
// Web1TFrequencyCountResource.PARAM_LANGUAGE, "it"
// )
)
));
String twitterLIDModel = textCatModelsBaseDir + "/textcat_tweetlid.conf";
//String ligaModel = textCatModelsBaseDir + "/textcat_liga.conf";
description.add(createEngineDescription(LanguageIdentifier.class,
LanguageIdentifier.PARAM_CONFIG_FILE, twitterLIDModel));
description.add(createEngineDescription(Optimaize.class,
Optimaize.PARAM_LANGUAGES, languages));
description.add(createEngineDescription(TikaLanguageIdentifier.class));
String tempResultsDirectory = "src/main/resources/temp_results/";
for (AnalysisEngineDescription desc : description) {
String descName = desc.getImplementationName();
String detectorName = descName.substring(descName.lastIndexOf(".") + 1);
File resultFile = new File(tempResultsDirectory + corpus.getCorpusName() + "-" + detectorName + ".txt");
File scoreFile = new File(tempResultsDirectory + corpus.getCorpusName() + "-" + detectorName + "_scores.txt");
File timerFile = new File(tempResultsDirectory + corpus.getCorpusName() + "-" + detectorName + "_times.txt");
SimplePipeline.runPipeline(
corpus.readerDescription,
AnalysisEngineFactory.createEngineDescription(ArktweetTokenizer.class),
AnalysisEngineFactory.createEngineDescription(Stopwatch.class,
Stopwatch.PARAM_TIMER_NAME, "t1"),
desc,
AnalysisEngineFactory.createEngineDescription(Stopwatch.class,
Stopwatch.PARAM_TIMER_NAME, "t1",
Stopwatch.PARAM_OUTPUT_FILE, timerFile),
AnalysisEngineFactory.createEngineDescription(LanguageEvaluatorConfMatrix.class,
LanguageEvaluatorConfMatrix.PARAM_LANGUAGES, languages,
LanguageEvaluatorConfMatrix.PARAM_SCORE_FILE, scoreFile),
AnalysisEngineFactory.createEngineDescription(Writer.class,
Writer.PARAM_RESULT_FILE, resultFile));
resultFiles.add(resultFile);
scoreFiles.add(scoreFile);
timeFiles.add(timerFile);
}
ResultStore.saveResults(resultFiles, corpus.getCorpusName() + "-");
ResultStore.saveScores(scoreFiles, timeFiles, corpus.getCorpusName() + "-");
FileUtils.cleanDirectory(new File(tempResultsDirectory)); //WARNING: Does not work occasionally. Reason unknown.
}
public static class CorpusConfiguration
{
CollectionReaderDescription readerDescription;
String corpusName;
public CorpusConfiguration(CollectionReaderDescription aReaderDescription, String aReaderName)
{
readerDescription = aReaderDescription;
corpusName = aReaderName;
}
public String getCorpusName()
{
return corpusName;
}
}
}
|
package kr.ds.parcelable;
import android.os.Parcel;
import android.os.Parcelable;
public class ParcelableMapData implements Parcelable {
private String mName, mAddress, mLat, mLon;
public ParcelableMapData(String name, String address, String lat, String lon){
mName = name;
mAddress = address;
mLat = lat;
mLon = lon;
}
public ParcelableMapData(Parcel src){
mName = src.readString();
mAddress = src.readString();
mLat = src.readString();
mLon = src.readString();
}
public String getmName() {
return mName;
}
public void setmName(String mName) {
this.mName = mName;
}
public String getmAddress() {
return mAddress;
}
public void setmAddress(String mAddress) {
this.mAddress = mAddress;
}
public String getmLat() {
return mLat;
}
public void setmLat(String mLat) {
this.mLat = mLat;
}
public String getmLon() {
return mLon;
}
public void setmLon(String mLon) {
this.mLon = mLon;
}
@Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
// TODO Auto-generated method stub
dest.writeString(mName);
dest.writeString(mAddress);
dest.writeString(mLat);
dest.writeString(mLon);
}
public static final Parcelable.Creator CREATOR = new Creator() {
@Override
public Object createFromParcel(Parcel in) {
// TODO Auto-generated method stub
return new ParcelableMapData(in);
}
@Override
public Object[] newArray(int size) {
// TODO Auto-generated method stub
return new ParcelableMapData[size];
}
};
}
|
package labs;
public class Kata1 {
public static String replaceNth(String text, int n, char oldValue, char newValue)
{
String salida="";
int coincidencia=0;
if(n>=1){
for(int i=0;i<text.length();i++){
if(oldValue==text.charAt(i)){
coincidencia++;
if(coincidencia%n==0){
salida+=newValue;
}else{
salida+=text.charAt(i);
}
}else{salida+=text.charAt(i);}
}}else{ salida=text;}
return salida;
}
}
|
/*
* Copyright (c) 2014 Anthony Benavente
*
* 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.ambenavente.origins.ui;
import com.ambenavente.origins.gameplay.entities.interfaces.Renderable;
import com.ambenavente.origins.ui.events.ActionArgs;
import com.ambenavente.origins.ui.events.ActionDoer;
import com.ambenavente.origins.ui.events.MouseEventArgs;
import com.ambenavente.origins.ui.events.MouseEventListener;
import org.newdawn.slick.Color;
import org.newdawn.slick.Font;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Input;
import org.newdawn.slick.geom.Rectangle;
import org.newdawn.slick.geom.Vector2f;
/**
* Created with IntelliJ IDEA.
*
* @author Anthony Benavente
* @version 2/19/14
*/
public abstract class Control implements Renderable, MouseEventListener {
private String name;
private String text;
private Vector2f pos;
private int width;
private int height;
private Object value;
private boolean hasFocus;
private boolean isEnabled;
private boolean isVisible;
private Font font;
private Color foreColor;
private Color backColor;
private Rectangle bounds;
protected ActionDoer doer;
public Control() {
this("");
}
public Control(String name) {
this(name, new Vector2f(0, 0));
}
public Control(String name, Vector2f pos) {
this(name, pos, 0, 0);
}
public Control(String name,
Vector2f pos,
int width,
int height) {
this.name = name;
this.pos = pos;
this.width = width;
this.height = height;
this.text = "";
this.value = null;
this.hasFocus = false;
this.isEnabled = true;
this.isVisible = true;
this.font = null;
this.foreColor = Color.white;
this.backColor = Color.black;
this.bounds = new Rectangle(pos.x, pos.y, width, height);
}
public abstract void update(Input input, int delta);
@Override
public void render(Graphics g) {
}
@Override
public void onClick(MouseEventArgs e) {
}
@Override
public void onHover(MouseEventArgs e) {
}
@Override
public void onMouseLeave(MouseEventArgs e) {
if (hasFocus) hasFocus = false;
}
@Override
public void onMouseEnter(MouseEventArgs e) {
if (!hasFocus) hasFocus = true;
}
@Override
public void onMouseDown(MouseEventArgs e) {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public Vector2f getPos() {
return pos;
}
public void setPos(Vector2f pos) {
this.pos = pos;
updateBounds();
}
public float getX() {
return pos.x;
}
public void setX(float x) {
pos.x = x;
updateBounds();
}
public float getY() {
return pos.y;
}
public void setY(float y) {
pos.y = y;
updateBounds();
}
public int getWidth() {
return width;
}
public void setWidth(int width) {
this.width = width;
updateBounds();
}
public int getHeight() {
return height;
}
public void setHeight(int height) {
this.height = height;
updateBounds();
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public boolean isHasFocus() {
return hasFocus;
}
public void setHasFocus(boolean hasFocus) {
this.hasFocus = hasFocus;
}
public boolean isEnabled() {
return isEnabled;
}
public void setEnabled(boolean isEnabled) {
this.isEnabled = isEnabled;
}
public boolean isVisible() {
return isVisible;
}
public void setVisible(boolean isVisible) {
this.isVisible = isVisible;
}
public Font getFont() {
return font;
}
public void setFont(Font font) {
this.font = font;
}
public Color getForeColor() {
return foreColor;
}
public void setForeColor(Color foreColor) {
this.foreColor = foreColor;
}
public Color getBackColor() {
return backColor;
}
public void setBackColor(Color backColor) {
this.backColor = backColor;
}
public Rectangle getBounds() {
return bounds;
}
private void updateBounds() {
bounds.setBounds(pos.x, pos.y, width, height);
}
public void setActionDoer(ActionDoer doer) {
this.doer = doer;
}
protected boolean mouseInBounds(Vector2f mousePos) {
return bounds.contains(mousePos.x, mousePos.y);
}
}
|
package net.somethingnew.kawatan.flower;
import android.content.Context;
import net.somethingnew.kawatan.flower.util.LogUtility;
import java.util.ArrayList;
import java.util.Random;
/**
* 各Category毎にアイコンのリソースIDをArrayListに保持
*/
public class IconManager {
private static ArrayList<Integer>[] mIconResourceIdListArray;
private static int[] mAutoIconResourceIds;
private static int[] mDefaultIconResourceIds;
private static Context mContext;
public static void init(Context context) {
mContext = context;
LogUtility.d("Loading Icons...");
mIconResourceIdListArray = new ArrayList[Constants.NUM_OF_ICON_TAB];
for (int category = 0; category < Constants.NUM_OF_ICON_TAB; category++) {
mIconResourceIdListArray[category] = new ArrayList<>();
mAutoIconResourceIds = new int[Constants.NUM_OF_CATEGORY];
mDefaultIconResourceIds = new int[Constants.NUM_OF_CATEGORY];
// Resource名をR.drawable.名前としてintに変換してarrayに登録
// 各カテゴリ先頭のxxxx_000はAuto画像なので、それはmIconResourceIdListArrayには登録しない
for (int i = 1; i <= Constants.NUM_OF_ICONS_IN_CATEGORY[category]; i++) {
String iconName = Constants.ICON_TAB_ARRAY[category] + "_" + String.format("%03d", i);
int imageId = mContext.getResources().getIdentifier(iconName, "drawable", mContext.getPackageName());
mIconResourceIdListArray[category].add(imageId);
}
// 各カテゴリのAutoアイコンとDefaultアイコンのResourceIdを事前に配列に用意しておく
for (int i = 0; i < Constants.NUM_OF_CATEGORY; i++) {
mAutoIconResourceIds[i] = mContext.getResources().getIdentifier(Constants.ICON_AUTO_IMAGE_ID[i], "drawable", mContext.getPackageName());
mDefaultIconResourceIds[i] = mContext.getResources().getIdentifier(Constants.ICON_DEFAULT_IMAGE_ID[i], "drawable", mContext.getPackageName());
}
}
}
public static int getResIdAtRandom(int category) {
return mIconResourceIdListArray[category].get(new Random().nextInt(Constants.NUM_OF_ICONS_IN_CATEGORY[category] - 1) + 1);
}
public static ArrayList<Integer> getIconResourceIdList(int category) {
return mIconResourceIdListArray[category];
}
public static int getAutoIconResId(int category) {
return mAutoIconResourceIds[category];
}
public static int getDefaultIconResId(int category) {
return mDefaultIconResourceIds[category];
}
} |
package tema13.estrutura;
import tema13.interfaces.IMensagem;
public class EnviaEmail {
private static String SERVER_MAIL = "servidor@ilegra.com";
public EnviaEmail() {
}
public void enviaEmail(IMensagem iMensagem) {
String emailRemetente;
String emailDestinatario;
if (iMensagem.getEmailRemetente().isEmpty()) {
emailRemetente = EnviaEmail.getServerMail();
} else {
emailRemetente = iMensagem.getEmailRemetente();
}
emailRemetente = iMensagem.getEmailDestinatario();
System.out.println(iMensagem.getAssunto() + ":\n" + iMensagem.getMensagem());
}
public static String getServerMail() {
return SERVER_MAIL;
}
public static void setServerMail(String serverMail) {
SERVER_MAIL = serverMail;
}
}
|
/**
* Copyright (c) 2016, 指端科技.
*/
package com.rofour.baseball.service.manager;
import java.util.List;
import java.util.Map;
import com.rofour.baseball.controller.model.ResultInfo;
import com.rofour.baseball.controller.model.manager.RolePermissionInfo;
import com.rofour.baseball.dao.manager.bean.RolePermissionBean;
/**
* @ClassName: RolePermissionService
* @Description: 管理中心--角色权限管理接口
* @author ww
* @date 2016年3月27日 下午2:01:51
*
*/
public interface RolePermissionService {
/**
* @Description: 添加角色权限接口
* @param permission
* @return
*/
public int addRolePermission(RolePermissionInfo permission);
/**
* @Description: 按角色权限ID删除角色权限
* @param rolePermissionId
* @return
*/
public int deleteRolePermission(Long rolePermissionId);
/**
* @Description:更新角色权限信息
* @param rolePermission
* @return
*/
public int updateRolePermission(RolePermissionInfo rolePermission);
/**
* @Description: 按主键ID查询角色权限信息
* @param rolePermissionId
* @return
*/
public RolePermissionInfo selectRolePermission(Long rolePermissionId);
/**
* @Description: 按角色ID查询角色所有权限
* @return
*/
public List<RolePermissionBean> selectAll();
/**
* @Description: 验证重复
* @param map
* @return
*/
boolean isRolePermissionExists(Map<String, Long> map);
/**
* @Description: 批量添加角色权限信息
* @param list
* @return
*/
public ResultInfo batchAdd(List<RolePermissionInfo> list);
List<RolePermissionBean> selectRolePermissionByUserName(String userName);
Integer getTotal();
}
|
package com.darglk.todolist.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import com.darglk.todolist.entity.User;
import com.darglk.todolist.service.PasswordResetTokenService;
import com.darglk.todolist.service.TaskService;
import com.darglk.todolist.service.UserService;
@Controller
@RequestMapping("/admin/users")
public class AdminUsersController {
@Autowired
private UserService userService;
@Autowired
private TaskService taskService;
@Autowired
private PasswordResetTokenService passwordResetTokenService;
@GetMapping("/list")
public String listUsers(Model model, @RequestParam(name="page", defaultValue="0", required=false) Integer page,
@RequestParam(name="searchTerm", defaultValue="", required=false) String searchTerm) {
Pageable pageable = new PageRequest(page,3);
Page<User> users = userService.getUsersByTerm(searchTerm, pageable);
model.addAttribute("users", users);
model.addAttribute("page", page);
model.addAttribute("searchTerm", searchTerm);
return "list-users";
}
@GetMapping("/toggleAdminRole")
public String toggleUserAdminRole(Model model, @RequestParam(name="userId") Integer userId) {
User user = userService.getUser(userId);
userService.toggleUserAdminRole(user);
return "redirect:/admin/users/list";
}
@GetMapping("/toggleEnableUser")
public String toggleUserEnabled(Model model, @RequestParam(name="userId") Integer userId) {
User user = userService.getUser(userId);
userService.toggleIsEnabled(user.getId(), !user.getIsEnabled());
return "redirect:/admin/users/list";
}
@GetMapping("/deleteUser")
public String deleteUser(Model model, @RequestParam(name="userId") Integer userId) {
User user = userService.getUser(userId);
taskService.deleteTasksWithUserId(user.getId());
passwordResetTokenService.deleteUserTokens(user.getId());
userService.deleteUserRoles(user.getId());
userService.deleteUser(user.getId());
userService.deleteUserAvatar(user);
return "redirect:/admin/users/list";
}
}
|
package karin;
import kuvamine.*;
import java.io.*;
import java.io.IOException;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@SpringBootApplication
public class Rakendus{
@RequestMapping("/aprilliuudis")
String uudis1(String pealkiri, String sisu){
PealkirjagaTekst pt1 = new PealkirjagaTekst(pealkiri, sisu);
return "<!doctype html><html><body>"+pt1.html()+"</body></html>";
}
@RequestMapping("/valuutakursid")
String valuutakursid()throws IOException{
TabelVeebist tulp1 = new TabelVeebist("http://www.seb.ee/valuutakursid", "Valuuta nimetus");
TabelVeebist tulp2 = new TabelVeebist("http://www.seb.ee/valuutakursid", "Valuuta tähis");
TabelVeebist tulp3 = new TabelVeebist("http://www.seb.ee/valuutakursid", "Euroopa Keskpanga kurss");
PealkirjagaTulp esimene = new PealkirjagaTulp(tulp1.tulp);
PealkirjagaTulp teine = new PealkirjagaTulp(tulp2.tulp);
PealkirjagaTulp kolmas = new PealkirjagaTulp(tulp3.tulp);
ReasPaigutus valuutakursid= new ReasPaigutus();
valuutakursid.lisaElement(esimene);
valuutakursid.lisaElement(teine);
valuutakursid.lisaElement(kolmas);
return "<!doctype html><html><body>"+valuutakursid.html()+"</body></html>";
}
@RequestMapping("/katse")
/*näiteks
katse?url=https://fp.lhv.ee/market,,&pealkiri=Nimetus,Viimane,Muutus
katse?url=http://www.seb.ee/valuutakursid,,&pealkiri=Valuuta nimetus,Pank müüb Ülekanne,Pank ostab Ülekanne
*/
String valuutakursid(String url, String pealkiri)throws IOException{
String[] urliabi = url.split(",",-1);
String[] pealkirjaabi = pealkiri.split(",",-1);
int sisestusi = 0; //url v pealkiri sisestuste arv aadressireal
ReasPaigutus valuutakursid = new ReasPaigutus();
if(urliabi.length < pealkirjaabi.length){
sisestusi = urliabi.length;
}else{
sisestusi = pealkirjaabi.length;
}
for(int i = 0; i < sisestusi; i++){
if(urliabi[0] == null || urliabi[0].equals("")){
urliabi[0] = "http://www.seb.ee/valuutakursid";
}
if(urliabi[i] == null || urliabi[i].equals("")){
urliabi[i] = urliabi[0]; //esimesena sisestatud aadress, kui teisi pole määratud
}
if(pealkirjaabi[i] == null || pealkirjaabi[i].equals("")){
pealkirjaabi[i] = "";
}
valuutakursid.lisaElement(new PealkirjagaTulp(new TabelVeebist(urliabi[i].trim(), pealkirjaabi[i].trim()).tulp));
}
return "<!doctype html><html><body>"+valuutakursid.html()+"</body></html>";
}
public static void main(String[] args){
//System.getProperties().put("server.port", 2412);
SpringApplication.run(Rakendus.class, args);
}
}
//scl enable rh-maven33 bash
//mvn package
//java -jar target/kodune-0.0.1-SNAPSHOT.jar
|
package com.joydigit.mirror_processor.entity;
import lombok.Data;
import java.util.List;
/**
* create by 75442 on 2019/11/28
*/
@Data
public class Devices {
private String dev_name; //设备名称
private String dev_examid; //体检ID
private String dev_advice; //修改后的疾病建议
private String dev_analyse; //疾病解析
private String dev_kind; //设备类型
private String dev_id; //设备ID
private String dev_corrresult; //修改后的体检结果
private String c_orgid; //组织ID
private String dev_corranalyse; //修改后的疾病解析
private String dev_image; //图像
private String dev_appendix;
private String dev_mode;
private String dev_corradvice; //疾病建议
private List<Items> items;
private String dev_result;
}
|
package com.github.marenwynn.waypoints.commands;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import com.github.marenwynn.waypoints.SelectionManager;
import com.github.marenwynn.waypoints.data.DataManager;
import com.github.marenwynn.waypoints.data.Msg;
import com.github.marenwynn.waypoints.data.Waypoint;
public class WPMoveCmd implements PluginCommand {
@Override
public void execute(CommandSender sender, String[] args) {
Player p = (Player) sender;
Waypoint wp = SelectionManager.getManager().getSelectedWaypoint(p);
if (wp == null) {
Msg.WP_NOT_SELECTED_ERROR.sendTo(p);
Msg.WP_NOT_SELECTED_ERROR_USAGE.sendTo(p);
return;
}
wp.setLocation(p.getLocation());
DataManager.getManager().saveWaypoint(sender, wp);
Msg.WP_LOCATION_UPDATED.sendTo(p, wp.getName());
}
@Override
public boolean isConsoleExecutable() {
return false;
}
@Override
public boolean hasRequiredPerm(CommandSender sender) {
return sender.hasPermission("wp.move");
}
}
|
package cn.leo.produce.decode;
import com.google.zxing.ResultPoint;
import com.google.zxing.ResultPointCallback;
/**
* ResultPointCallback delegating the ResultPoints to a decoder.
*/
public class DecoderResultPointCallback implements ResultPointCallback {
private Decoder decoder;
public DecoderResultPointCallback(Decoder decoder) {
this.decoder = decoder;
}
public DecoderResultPointCallback() {
}
public Decoder getDecoder() {
return decoder;
}
public void setDecoder(Decoder decoder) {
this.decoder = decoder;
}
@Override
public void foundPossibleResultPoint(ResultPoint point) {
if(decoder != null) {
decoder.foundPossibleResultPoint(point);
}
}
}
|
/**
* 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.hadoop.mapred;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.LocalFileSystem;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapred.CleanupQueue.PathDeletionContext;
import org.apache.hadoop.mapred.JvmManager.JvmEnv;
import org.apache.hadoop.util.StringUtils;
import org.apache.hadoop.util.Shell.ExitCodeException;
import org.apache.hadoop.util.Shell.ShellCommandExecutor;
/**
* A {@link TaskController} that runs the task JVMs as the user
* who submits the job.
*
* This class executes a setuid executable to implement methods
* of the {@link TaskController}, including launching the task
* JVM and killing it when needed, and also initializing and
* finalizing the task environment.
* <p> The setuid executable is launched using the command line:</p>
* <p>task-controller mapreduce.job.user.name command command-args, where</p>
* <p>mapreduce.job.user.name is the name of the owner who submits the job</p>
* <p>command is one of the cardinal value of the
* {@link LinuxTaskController.TaskControllerCommands} enumeration</p>
* <p>command-args depends on the command being launched.</p>
*
* In addition to running and killing tasks, the class also
* sets up appropriate access for the directories and files
* that will be used by the tasks.
*/
class LinuxTaskController extends TaskController {
private static final Log LOG =
LogFactory.getLog(LinuxTaskController.class);
// Name of the executable script that will contain the child
// JVM command line. See writeCommand for details.
private static final String COMMAND_FILE = "taskjvm.sh";
// Path to the setuid executable.
private static String taskControllerExe;
static {
// the task-controller is expected to be under the $HADOOP_PREFIX/bin
// directory.
File hadoopBin = new File(System.getenv("HADOOP_PREFIX"), "bin");
taskControllerExe =
new File(hadoopBin, "task-controller").getAbsolutePath();
}
public LinuxTaskController() {
super();
}
/**
* List of commands that the setuid script will execute.
*/
enum TaskControllerCommands {
INITIALIZE_USER,
INITIALIZE_JOB,
INITIALIZE_DISTRIBUTEDCACHE_FILE,
LAUNCH_TASK_JVM,
INITIALIZE_TASK,
TERMINATE_TASK_JVM,
KILL_TASK_JVM,
RUN_DEBUG_SCRIPT,
SIGQUIT_TASK_JVM,
ENABLE_TASK_FOR_CLEANUP,
ENABLE_JOB_FOR_CLEANUP
}
@Override
public void setup() throws IOException {
super.setup();
// Check the permissions of the task-controller binary by running it plainly.
// If permissions are correct, it returns an error code 1, else it returns
// 24 or something else if some other bugs are also present.
String[] taskControllerCmd =
new String[] { getTaskControllerExecutablePath() };
ShellCommandExecutor shExec = new ShellCommandExecutor(taskControllerCmd);
try {
shExec.execute();
} catch (ExitCodeException e) {
int exitCode = shExec.getExitCode();
if (exitCode != 1) {
LOG.warn("Exit code from checking binary permissions is : " + exitCode);
logOutput(shExec.getOutput());
throw new IOException("Task controller setup failed because of invalid"
+ "permissions/ownership with exit code " + exitCode, e);
}
}
}
/**
* Launch a task JVM that will run as the owner of the job.
*
* This method launches a task JVM by executing a setuid executable that will
* switch to the user and run the task. Also does initialization of the first
* task in the same setuid process launch.
*/
@Override
void launchTaskJVM(TaskController.TaskControllerContext context)
throws IOException {
JvmEnv env = context.env;
// get the JVM command line.
String cmdLine =
TaskLog.buildCommandLine(env.setup, env.vargs, env.stdout, env.stderr,
env.logSize, true);
StringBuffer sb = new StringBuffer();
//export out all the environment variable before child command as
//the setuid/setgid binaries would not be getting, any environmental
//variables which begin with LD_*.
for(Entry<String, String> entry : env.env.entrySet()) {
sb.append("export ");
sb.append(entry.getKey());
sb.append("=");
sb.append(entry.getValue());
sb.append("\n");
}
sb.append(cmdLine);
// write the command to a file in the
// task specific cache directory
writeCommand(sb.toString(), getTaskCacheDirectory(context,
context.env.workDir));
// Call the taskcontroller with the right parameters.
List<String> launchTaskJVMArgs = buildLaunchTaskArgs(context,
context.env.workDir);
ShellCommandExecutor shExec = buildTaskControllerExecutor(
TaskControllerCommands.LAUNCH_TASK_JVM,
env.conf.getUser(),
launchTaskJVMArgs, env.workDir, env.env);
context.shExec = shExec;
try {
shExec.execute();
} catch (Exception e) {
int exitCode = shExec.getExitCode();
LOG.warn("Exit code from task is : " + exitCode);
// 143 (SIGTERM) and 137 (SIGKILL) exit codes means the task was
// terminated/killed forcefully. In all other cases, log the
// task-controller output
if (exitCode != 143 && exitCode != 137) {
LOG.warn("Exception thrown while launching task JVM : "
+ StringUtils.stringifyException(e));
LOG.info("Output from LinuxTaskController's launchTaskJVM follows:");
logOutput(shExec.getOutput());
}
throw new IOException(e);
}
if (LOG.isDebugEnabled()) {
LOG.info("Output from LinuxTaskController's launchTaskJVM follows:");
logOutput(shExec.getOutput());
}
}
/**
* Launch the debug script process that will run as the owner of the job.
*
* This method launches the task debug script process by executing a setuid
* executable that will switch to the user and run the task.
*/
@Override
void runDebugScript(DebugScriptContext context) throws IOException {
String debugOut = FileUtil.makeShellPath(context.stdout);
String cmdLine = TaskLog.buildDebugScriptCommandLine(context.args, debugOut);
writeCommand(cmdLine, getTaskCacheDirectory(context, context.workDir));
// Call the taskcontroller with the right parameters.
List<String> launchTaskJVMArgs = buildLaunchTaskArgs(context, context.workDir);
runCommand(TaskControllerCommands.RUN_DEBUG_SCRIPT, context.task.getUser(),
launchTaskJVMArgs, context.workDir, null);
}
/**
* Helper method that runs a LinuxTaskController command
*
* @param taskControllerCommand
* @param user
* @param cmdArgs
* @param env
* @throws IOException
*/
private void runCommand(TaskControllerCommands taskControllerCommand,
String user, List<String> cmdArgs, File workDir, Map<String, String> env)
throws IOException {
ShellCommandExecutor shExec =
buildTaskControllerExecutor(taskControllerCommand, user, cmdArgs,
workDir, env);
try {
shExec.execute();
} catch (Exception e) {
LOG.warn("Exit code from " + taskControllerCommand.toString() + " is : "
+ shExec.getExitCode());
LOG.warn("Exception thrown by " + taskControllerCommand.toString() + " : "
+ StringUtils.stringifyException(e));
LOG.info("Output from LinuxTaskController's "
+ taskControllerCommand.toString() + " follows:");
logOutput(shExec.getOutput());
throw new IOException(e);
}
if (LOG.isDebugEnabled()) {
LOG.info("Output from LinuxTaskController's "
+ taskControllerCommand.toString() + " follows:");
logOutput(shExec.getOutput());
}
}
/**
* Returns list of arguments to be passed while initializing a new task. See
* {@code buildTaskControllerExecutor(TaskControllerCommands, String,
* List<String>, JvmEnv)} documentation.
*
* @param context
* @return Argument to be used while launching Task VM
*/
private List<String> buildInitializeTaskArgs(TaskExecContext context) {
List<String> commandArgs = new ArrayList<String>(3);
String taskId = context.task.getTaskID().toString();
String jobId = getJobId(context);
commandArgs.add(jobId);
if (!context.task.isTaskCleanupTask()) {
commandArgs.add(taskId);
} else {
commandArgs.add(taskId + TaskTracker.TASK_CLEANUP_SUFFIX);
}
return commandArgs;
}
@Override
void initializeTask(TaskControllerContext context)
throws IOException {
if (LOG.isDebugEnabled()) {
LOG.debug("Going to do "
+ TaskControllerCommands.INITIALIZE_TASK.toString()
+ " for " + context.task.getTaskID().toString());
}
runCommand(TaskControllerCommands.INITIALIZE_TASK,
context.env.conf.getUser(),
buildInitializeTaskArgs(context), context.env.workDir, context.env.env);
}
/**
* Builds the args to be passed to task-controller for enabling of task for
* cleanup. Last arg in this List is either $attemptId or $attemptId/work
*/
private List<String> buildTaskCleanupArgs(
TaskControllerTaskPathDeletionContext context) {
List<String> commandArgs = new ArrayList<String>(3);
commandArgs.add(context.mapredLocalDir.toUri().getPath());
commandArgs.add(context.task.getJobID().toString());
String workDir = "";
if (context.isWorkDir) {
workDir = "/work";
}
if (context.task.isTaskCleanupTask()) {
commandArgs.add(context.task.getTaskID() + TaskTracker.TASK_CLEANUP_SUFFIX
+ workDir);
} else {
commandArgs.add(context.task.getTaskID() + workDir);
}
return commandArgs;
}
/**
* Builds the args to be passed to task-controller for enabling of job for
* cleanup. Last arg in this List is $jobid.
*/
private List<String> buildJobCleanupArgs(
TaskControllerJobPathDeletionContext context) {
List<String> commandArgs = new ArrayList<String>(2);
commandArgs.add(context.mapredLocalDir.toUri().getPath());
commandArgs.add(context.jobId.toString());
return commandArgs;
}
/**
* Enables the task for cleanup by changing permissions of the specified path
* in the local filesystem
*/
@Override
void enableTaskForCleanup(PathDeletionContext context)
throws IOException {
if (context instanceof TaskControllerTaskPathDeletionContext) {
TaskControllerTaskPathDeletionContext tContext =
(TaskControllerTaskPathDeletionContext) context;
enablePathForCleanup(tContext,
TaskControllerCommands.ENABLE_TASK_FOR_CLEANUP,
buildTaskCleanupArgs(tContext));
}
else {
throw new IllegalArgumentException("PathDeletionContext provided is not "
+ "TaskControllerTaskPathDeletionContext.");
}
}
/**
* Enables the job for cleanup by changing permissions of the specified path
* in the local filesystem
*/
@Override
void enableJobForCleanup(PathDeletionContext context)
throws IOException {
if (context instanceof TaskControllerJobPathDeletionContext) {
TaskControllerJobPathDeletionContext tContext =
(TaskControllerJobPathDeletionContext) context;
enablePathForCleanup(tContext,
TaskControllerCommands.ENABLE_JOB_FOR_CLEANUP,
buildJobCleanupArgs(tContext));
} else {
throw new IllegalArgumentException("PathDeletionContext provided is not "
+ "TaskControllerJobPathDeletionContext.");
}
}
/**
* Enable a path for cleanup
* @param c {@link TaskControllerPathDeletionContext} for the path to be
* cleaned up
* @param command {@link TaskControllerCommands} for task/job cleanup
* @param cleanupArgs arguments for the {@link LinuxTaskController} to enable
* path cleanup
*/
private void enablePathForCleanup(TaskControllerPathDeletionContext c,
TaskControllerCommands command,
List<String> cleanupArgs) {
if (LOG.isDebugEnabled()) {
LOG.debug("Going to do " + command.toString() + " for " + c.fullPath);
}
if ( c.user != null && c.fs instanceof LocalFileSystem) {
try {
runCommand(command, c.user, cleanupArgs, null, null);
} catch(IOException e) {
LOG.warn("Unable to change permissions for " + c.fullPath);
}
}
else {
throw new IllegalArgumentException("Either user is null or the "
+ "file system is not local file system.");
}
}
private void logOutput(String output) {
String shExecOutput = output;
if (shExecOutput != null) {
for (String str : shExecOutput.split("\n")) {
LOG.info(str);
}
}
}
private String getJobId(TaskExecContext context) {
String taskId = context.task.getTaskID().toString();
TaskAttemptID tId = TaskAttemptID.forName(taskId);
String jobId = tId.getJobID().toString();
return jobId;
}
/**
* Returns list of arguments to be passed while launching task VM.
* See {@code buildTaskControllerExecutor(TaskControllerCommands,
* String, List<String>, JvmEnv)} documentation.
* @param context
* @return Argument to be used while launching Task VM
*/
private List<String> buildLaunchTaskArgs(TaskExecContext context,
File workDir) {
List<String> commandArgs = new ArrayList<String>(3);
LOG.debug("getting the task directory as: "
+ getTaskCacheDirectory(context, workDir));
LOG.debug("getting the tt_root as " +getDirectoryChosenForTask(
new File(getTaskCacheDirectory(context, workDir)),
context) );
commandArgs.add(getDirectoryChosenForTask(
new File(getTaskCacheDirectory(context, workDir)),
context));
commandArgs.addAll(buildInitializeTaskArgs(context));
return commandArgs;
}
// Get the directory from the list of directories configured
// in Configs.LOCAL_DIR chosen for storing data pertaining to
// this task.
private String getDirectoryChosenForTask(File directory,
TaskExecContext context) {
String jobId = getJobId(context);
String taskId = context.task.getTaskID().toString();
for (String dir : mapredLocalDirs) {
File mapredDir = new File(dir);
File taskDir =
new File(mapredDir, TaskTracker.getTaskWorkDir(context.task
.getUser(), jobId, taskId, context.task.isTaskCleanupTask()))
.getParentFile();
if (directory.equals(taskDir)) {
return dir;
}
}
LOG.error("Couldn't parse task cache directory correctly");
throw new IllegalArgumentException("invalid task cache directory "
+ directory.getAbsolutePath());
}
/**
* Builds the command line for launching/terminating/killing task JVM.
* Following is the format for launching/terminating/killing task JVM
* <br/>
* For launching following is command line argument:
* <br/>
* {@code mapreduce.job.user.name command tt-root job_id task_id}
* <br/>
* For terminating/killing task jvm.
* {@code mapreduce.job.user.name command tt-root task-pid}
*
* @param command command to be executed.
* @param userName mapreduce.job.user.name
* @param cmdArgs list of extra arguments
* @param workDir working directory for the task-controller
* @param env JVM environment variables.
* @return {@link ShellCommandExecutor}
* @throws IOException
*/
private ShellCommandExecutor buildTaskControllerExecutor(
TaskControllerCommands command, String userName, List<String> cmdArgs,
File workDir, Map<String, String> env)
throws IOException {
String[] taskControllerCmd = new String[3 + cmdArgs.size()];
taskControllerCmd[0] = getTaskControllerExecutablePath();
taskControllerCmd[1] = userName;
taskControllerCmd[2] = String.valueOf(command.ordinal());
int i = 3;
for (String cmdArg : cmdArgs) {
taskControllerCmd[i++] = cmdArg;
}
if (LOG.isDebugEnabled()) {
for (String cmd : taskControllerCmd) {
LOG.debug("taskctrl command = " + cmd);
}
}
ShellCommandExecutor shExec = null;
if(workDir != null && workDir.exists()) {
shExec = new ShellCommandExecutor(taskControllerCmd,
workDir, env);
} else {
shExec = new ShellCommandExecutor(taskControllerCmd);
}
return shExec;
}
// Return the task specific directory under the cache.
private String getTaskCacheDirectory(TaskExecContext context,
File workDir) {
// In the case of JVM reuse, the task specific directory
// is different from what is set with respect with
// env.workDir. Hence building this from the taskId everytime.
String taskId = context.task.getTaskID().toString();
File cacheDirForJob = workDir.getParentFile().getParentFile();
if(context.task.isTaskCleanupTask()) {
taskId = taskId + TaskTracker.TASK_CLEANUP_SUFFIX;
}
return new File(cacheDirForJob, taskId).getAbsolutePath();
}
// Write the JVM command line to a file under the specified directory
// Note that the JVM will be launched using a setuid executable, and
// could potentially contain strings defined by a user. Hence, to
// prevent special character attacks, we write the command line to
// a file and execute it.
private void writeCommand(String cmdLine,
String directory) throws IOException {
PrintWriter pw = null;
String commandFile = directory + File.separator + COMMAND_FILE;
LOG.info("Writing commands to " + commandFile);
LOG.info("--------Commands Begin--------");
LOG.info(cmdLine);
LOG.info("--------Commands End--------");
try {
FileWriter fw = new FileWriter(commandFile);
BufferedWriter bw = new BufferedWriter(fw);
pw = new PrintWriter(bw);
pw.write(cmdLine);
} catch (IOException ioe) {
LOG.error("Caught IOException while writing JVM command line to file. "
+ ioe.getMessage());
} finally {
if (pw != null) {
pw.close();
}
// set execute permissions for all on the file.
File f = new File(commandFile);
if (f.exists()) {
f.setReadable(true, false);
f.setExecutable(true, false);
}
}
}
private List<String> buildInitializeJobCommandArgs(
JobInitializationContext context) {
List<String> initJobCmdArgs = new ArrayList<String>();
initJobCmdArgs.add(context.jobid.toString());
return initJobCmdArgs;
}
@Override
void initializeJob(JobInitializationContext context)
throws IOException {
LOG.debug("Going to initialize job " + context.jobid.toString()
+ " on the TT");
runCommand(TaskControllerCommands.INITIALIZE_JOB, context.user,
buildInitializeJobCommandArgs(context), context.workDir, null);
}
@Override
public void initializeDistributedCacheFile(DistributedCacheFileContext context)
throws IOException {
if (LOG.isDebugEnabled()) {
LOG.debug("Going to initialize distributed cache for " + context.user
+ " with localizedBaseDir " + context.localizedBaseDir +
" and uniqueString " + context.uniqueString);
}
List<String> args = new ArrayList<String>();
// Here, uniqueString might start with '-'. Adding -- in front of the
// arguments indicates that they are non-option parameters.
args.add("--");
args.add(context.localizedBaseDir.toString());
args.add(context.uniqueString);
runCommand(TaskControllerCommands.INITIALIZE_DISTRIBUTEDCACHE_FILE,
context.user, args, context.workDir, null);
}
@Override
public void initializeUser(InitializationContext context)
throws IOException {
LOG.debug("Going to initialize user directories for " + context.user
+ " on the TT");
runCommand(TaskControllerCommands.INITIALIZE_USER, context.user,
new ArrayList<String>(), context.workDir, null);
}
/**
* API which builds the command line to be pass to LinuxTaskController
* binary to terminate/kill the task. See
* {@code buildTaskControllerExecutor(TaskControllerCommands,
* String, List<String>, JvmEnv)} documentation.
*
*
* @param context context of task which has to be passed kill signal.
*
*/
private List<String> buildKillTaskCommandArgs(TaskControllerContext
context){
List<String> killTaskJVMArgs = new ArrayList<String>();
killTaskJVMArgs.add(context.pid);
return killTaskJVMArgs;
}
/**
* Convenience method used to sending appropriate signal to the task
* VM
* @param context
* @param command
* @throws IOException
*/
protected void signalTask(TaskControllerContext context,
TaskControllerCommands command) throws IOException{
if(context.task == null) {
LOG.info("Context task is null; not signaling the JVM");
return;
}
ShellCommandExecutor shExec = buildTaskControllerExecutor(
command, context.env.conf.getUser(),
buildKillTaskCommandArgs(context), context.env.workDir,
context.env.env);
try {
shExec.execute();
} catch (Exception e) {
LOG.warn("Output from task-contoller is : " + shExec.getOutput());
throw new IOException(e);
}
}
@Override
void terminateTask(TaskControllerContext context) {
try {
signalTask(context, TaskControllerCommands.TERMINATE_TASK_JVM);
} catch (Exception e) {
LOG.warn("Exception thrown while sending kill to the Task VM " +
StringUtils.stringifyException(e));
}
}
@Override
void killTask(TaskControllerContext context) {
try {
signalTask(context, TaskControllerCommands.KILL_TASK_JVM);
} catch (Exception e) {
LOG.warn("Exception thrown while sending destroy to the Task VM " +
StringUtils.stringifyException(e));
}
}
@Override
void dumpTaskStack(TaskControllerContext context) {
try {
signalTask(context, TaskControllerCommands.SIGQUIT_TASK_JVM);
} catch (Exception e) {
LOG.warn("Exception thrown while sending SIGQUIT to the Task VM " +
StringUtils.stringifyException(e));
}
}
protected String getTaskControllerExecutablePath() {
return taskControllerExe;
}
@Override
String getRunAsUser(JobConf conf) {
return conf.getUser();
}
} |
package com.ch.web.gateway.session;
import java.io.Serializable;
/**
* 用户会话
*
* @author caich
**/
public class UserSession<T> implements Serializable {
/**
* 会话id 用于确定数据唯一性
*/
private String sessionId;
/**
* 令牌
*/
private String accessToken;
/**
* 会话数据
*/
private T data;
public UserSession(String accessToken, String sessionId, T data) {
this.accessToken = accessToken;
this.sessionId = sessionId;
this.data = data;
}
public String getAccessToken() {
return accessToken;
}
public T getData() {
return data;
}
public String getSessionId() {
return sessionId;
}
}
|
package org.sonar.plugins.profiler;
import org.sonar.api.batch.AbstractSumChildrenDecorator;
import org.sonar.api.batch.DependedUpon;
import org.sonar.api.measures.Metric;
import java.util.Arrays;
import java.util.List;
/**
* @author Evgeny Mandrikov
*/
public class ProfilerDecorator extends AbstractSumChildrenDecorator {
@DependedUpon
public List<Metric> generatesMetrics() {
return Arrays.asList(ProfilerMetrics.TESTS);
}
@Override
protected boolean shouldSaveZeroIfNoChildMeasures() {
return false;
}
}
|
package leet;
import java.util.HashMap;
import java.util.Map;
/**
* Created by kreddy on 4/19/18.
*/
public class MaxWidthOfBinaryTree {
int ans;
Map<Integer, Integer> left;
public int widthOfBinaryTree(TreeNode root) {
ans = 0;
left = new HashMap<>();
dfs(root, 0, 0);
return ans;
}
public void dfs(TreeNode root, int depth, int pos) {
if (root == null) return;
left.computeIfAbsent(depth, x-> pos);
ans = Math.max(ans, pos - left.get(depth) + 1);
dfs(root.left, depth + 1, 2 * pos);
dfs(root.right, depth + 1, 2 * pos + 1);
}
public static void main(String[] args) {
}
}
class AnnotatedNode {
TreeNode node;
int depth, pos;
AnnotatedNode(TreeNode n, int d, int p) {
node = n;
depth = d;
pos = p;
}
}
|
package org.motechproject.server.svc.impl;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.motechproject.server.model.Email;
import org.motechproject.server.model.IncomingMessage;
import org.motechproject.server.model.MailTemplate;
import org.motechproject.server.model.SupportCase;
import org.motechproject.server.service.ContextService;
import org.motechproject.server.strategy.MessageContentExtractionStrategy;
import org.motechproject.server.svc.MailingService;
import org.motechproject.server.svc.OpenmrsBean;
import org.motechproject.server.svc.SupportCaseService;
import org.motechproject.server.util.MailingConstants;
import org.motechproject.server.util.MotechConstants;
import org.motechproject.ws.Response;
import org.openmrs.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import java.util.HashMap;
import java.util.Map;
public class SupportCaseServiceImpl implements SupportCaseService {
private static Log log = LogFactory.getLog(SupportCaseServiceImpl.class);
@Autowired
private MailingService mailingService;
@Autowired
private MessageContentExtractionStrategy messageContentExtractionStrategy;
@Autowired
private MailTemplate mailTemplate;
@Autowired
private ContextService contextService;
@Autowired
@Qualifier("registrarBeanProxy")
private OpenmrsBean openmrsBean;
public Response mailToSupport(IncomingMessage incomingMessage) {
log.info("Received support case request " + incomingMessage);
try {
if (incomingMessage.hasSufficientInformation() && incomingMessage.isFor("SUPPORT")) {
return sendSupportMail(incomingMessage);
}
} catch (Exception ex) {
log.fatal("Could not raise support mail for " + incomingMessage, ex);
return new Response(MailingConstants.FAILED_TO_RAISE_SUPPORT_CASE);
}
return new Response(MailingConstants.INSUFFICIENT_INFO_FOR_SUPPORT_CASE);
}
private Response sendSupportMail(IncomingMessage incomingMessage) {
SupportCase supportCase = (SupportCase) messageContentExtractionStrategy.extractFrom(incomingMessage);
User staff = openmrsBean.getStaffBySystemId(supportCase.getRaisedBy());
Map data = new HashMap();
data.put("staff", staff);
data.put("case", supportCase);
mailingService.send(new Email(to(), from(), mailTemplate.subject(data), mailTemplate.text(data)));
log.info("mail sent successfully");
return new Response(MailingConstants.SUPPORT_CASE_CREATION_ACKNOWLEDGEMENT);
}
public void setMailingService(MailingService mailingService) {
this.mailingService = mailingService;
}
public void setMessageContentExtractionStrategy(MessageContentExtractionStrategy messageContentExtractionStrategy) {
this.messageContentExtractionStrategy = messageContentExtractionStrategy;
}
public void setMailTemplate(MailTemplate mailTemplate) {
this.mailTemplate = mailTemplate;
}
public void setContextService(ContextService contextService) {
this.contextService = contextService;
}
public void setOpenmrsBean(OpenmrsBean openmrsBean) {
this.openmrsBean = openmrsBean;
}
private String to() {
return contextService.getAdministrationService().getGlobalProperty(MotechConstants.GLOBAL_PROPERTY_SUPPORT_CASE_MAIL_TO);
}
private String from() {
return contextService.getAdministrationService().getGlobalProperty(MotechConstants.GLOBAL_PROPERTY_SUPPORT_CASE_MAIL_FROM);
}
}
|
package prueba.servicios;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/invertir")
public class Controlador {
@Autowired
private Servicio servicio;
@GetMapping
public String mostrar(@RequestParam (value="texto") String txt) {
return servicio.traerInverso(txt);
}
@GetMapping("/permutar")
public List<String> mostrarLista(@RequestParam (value="lista") String txt){
return servicio.traerPermutacion(txt);
}
}
|
package com.research.hadoop.mutiljob;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import java.io.IOException;
/**
* @fileName: TwoJobMapper.java
* @description: TwoJobMapper.java类说明
* @author: by echo huang
* @date: 2020-07-26 00:12
*/
public class TwoJobMapper extends Mapper<LongWritable, Text, Text, Text> {
private Text k = new Text();
private Text v = new Text();
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
// hsm-a.txt 3
// wy-b.txt 2
String line = value.toString();
String[] fields = "--".split(line);
k.set(fields[0]);
v.set(fields[1]);
context.write(k, v);
}
}
|
package org.nyer.sns.test;
import java.io.Serializable;
import java.util.Scanner;
import org.apache.commons.io.IOUtils;
import org.junit.Assert;
import org.junit.Test;
import org.nyer.sns.core.OAuth2Weibo;
import org.nyer.sns.core.WeiboResponse;
import org.nyer.sns.core.WeiboUser;
import org.nyer.sns.pooled.OAuth2UserPoolWeibo;
import org.nyer.sns.usrpool.MemoryUserPool;
import org.nyer.sns.util.page.Page;
import org.nyer.sns.util.page.PageEnumeration;
public class AbstractOAuth2WeiboTestCase {
protected static OAuth2Weibo weibo;
protected static OAuth2UserPoolWeibo userPoolWeibo;
protected static Serializable userId = "wello";
protected static void init() throws Exception {
userPoolWeibo = new OAuth2UserPoolWeibo(new MemoryUserPool(), weibo);
String url = userPoolWeibo.authorizeUrl("", "basic");
System.out.println(url);
System.out.println("enter the code if exists: ");
String code = new Scanner(System.in).nextLine();
userPoolWeibo.fetchAccessToken(userId, code, "", "");
}
@Test
public void testPublish() {
System.out.println("test publish ");
WeiboResponse response = null;
try {
response = userPoolWeibo.publish(userId, "haha", "it is a weibo", "", "");
} catch (Exception e) {
}
Assert.assertNotNull(response);
Assert.assertTrue(response.isStatusOK());
}
@Test
public void testPublishWithImage() {
System.out.println("test publish with a image");
WeiboResponse response = null;
try {
byte[] imgBytes = IOUtils.toByteArray(
NeteaseWeiboTestCase.class.getResourceAsStream("/20131015152402.jpg"));
String imgName = "20131015152402.jpg";
response = userPoolWeibo.publishWithImage(userId, "haha", "haha a post with a image", imgBytes, imgName, "", "");
System.out.println(response);
} catch (Exception e) {
e.printStackTrace();
}
Assert.assertNotNull(response);
Assert.assertTrue(response.isStatusOK());
}
@Test
public void testGetFollowers() {
System.out.println("test get followers");
PageEnumeration<WeiboUser> pageEnumerator = userPoolWeibo.getFollowerEnumerator(userId, 30);
Page<WeiboUser> pageFollowers = null;
while ((pageFollowers = pageEnumerator.nextPage()) != null) {
System.out.println(pageFollowers);
}
}
@Test
public void testGetFriends() {
System.out.println("test get friends");
PageEnumeration<WeiboUser> pageEnumerator = userPoolWeibo.getFriendEnumerator(userId, 30);
Page<WeiboUser> pageFollowers = null;
while ((pageFollowers = pageEnumerator.nextPage()) != null) {
System.out.println(pageFollowers);
}
}
}
|
package com.dazhi.authdemo.modules.auth.dao;
import com.dazhi.authdemo.modules.auth.entity.ProductModelEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface ProductModelRepository extends JpaRepository<ProductModelEntity, Integer> {
List<ProductModelEntity> findAllByProductIdAndModelContains(Integer productId,String model);
}
|
package com.tencent.mm.plugin.webview.stub;
import android.content.Intent;
import android.os.Bundle;
import android.os.IInterface;
import java.util.List;
import java.util.Map;
public interface d extends IInterface {
void Ar(int i);
Bundle At(int i);
boolean Au(int i);
void Av(int i);
void Aw(int i);
void Ax(int i);
String Dp(String str);
void H(String str, String str2, int i);
boolean Hm();
List<String> MM();
boolean MN();
String QO(String str);
String QP(String str);
void QQ(String str);
String QR(String str);
boolean QS(String str);
String QT(String str);
void QU(String str);
int QV(String str);
void QW(String str);
void QX(String str);
String QY(String str);
b S(Bundle bundle);
boolean T(Bundle bundle);
void a(int i, Bundle bundle, int i2);
void a(e eVar, int i);
void a(String str, Bundle bundle, int i);
boolean a(String str, String str2, String str3, Bundle bundle, Bundle bundle2, int i);
boolean a(String str, boolean z, Bundle bundle);
boolean aSn();
String aU(int i, String str);
void ab(int i, int i2, int i3);
void aj(Intent intent);
void b(Bundle bundle, int i);
boolean bVA();
List<String> bVB();
int bVC();
boolean bVD();
String[] bVE();
String[] bVp();
String bVq();
String bVr();
String bVs();
Map bVt();
int bVu();
int bVv();
void bVw();
void bVx();
boolean bVy();
boolean bVz();
void be(String str, boolean z);
void c(String str, int[] iArr);
void cw(String str, int i);
String cx(String str, int i);
void cy(String str, int i);
boolean da(String str);
int ej(int i, int i2);
void ek(int i, int i2);
void favEditTag();
String fq(String str, String str2);
Bundle g(int i, Bundle bundle);
void g(int i, List<String> list);
String gT(String str);
String getLanguage();
void h(String str, String str2, String str3, int i, int i2);
boolean hO(String str);
boolean he(String str);
boolean hf(String str);
void i(String str, boolean z, int i);
boolean isSDCardAvailable();
void j(int i, Bundle bundle);
Bundle p(int i, Bundle bundle);
void r(int i, Bundle bundle);
boolean s(int i, Bundle bundle);
boolean s(long j, String str);
void z(int i, String str, String str2);
boolean zZ();
}
|
package model;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
*
* @Sting
*
* */
public class Veiculo implements Serializable {
private String modelo;
private String marca;
private int ano;
private String placa;
private String nomeProprietario;
private String endereco;
private Date dataNascimento;
public String getModelo() {
return modelo;
}
public void setModelo(String modelo) {
this.modelo = modelo;
}
public String getMarca() {
return marca;
}
public void setMarca(String marca) {
this.marca = marca;
}
public int getAno() {
return ano;
}
public void setAno(int ano) {
this.ano = ano;
}
public String getPlaca() {
return placa;
}
public void setPlaca(String placa) {
this.placa = placa;
}
public String getNomeProprietario() {
return nomeProprietario;
}
public void setNomeProprietario(String nomeProprietario) {
this.nomeProprietario = nomeProprietario;
}
public String getEndereco() {
return endereco;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
public Date getDataNascimento() {
return dataNascimento;
}
public void setDataNascimento(Date dataNascimento) {
this.dataNascimento = dataNascimento;
}
@Override
public String toString() {
DateFormat df = new SimpleDateFormat("dd-MM-YYYY");
return "Veiculo :\n" + " Modelo : " + this.modelo + "\n Marca : " + this.marca
+ "\n Ano : " + this.ano + "\n Placa : " + this.placa + "\n Propietario : "
+ this.nomeProprietario + "\n Nascimento : " + df.format(dataNascimento) + "\n Endereço : "
+ this.endereco;
}
}
|
package com.tuitaking.point2offer;
import org.junit.Test;
public class Fib_10T {
@Test
public void test(){
Fib_10 fib_10=new Fib_10();
System.out.println(fib_10.fib(48)) ;
}
}
|
package client;
import java.awt.Container;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.ByteArrayInputStream;
import java.math.BigDecimal;
import java.rmi.RemoteException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.AbstractButton;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.SpringLayout;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.axis2.AxisFault;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import gov.weather.graphical.xml.dwmlgen.wsdl.ndfdxml_wsdl.NdfdXMLStub;
/**
* NationalWeatherSvcClient is a client for the National Weather Service web service defined by wsdl
* file located at https://graphical.weather.gov/xml/DWMLgen/wsdl/ndfdXML.wsdl
* Includes a swing client to get the latitude and longitude information from the user and gets the weather information
* for that latitude, longitude location and displays it to the user.
* @author Gautam Shetty
* UTA ID : 1001446742
*/
public class NationalWeatherSvcClient implements ActionListener {
/**
* Main function.
* @param args command parameters.
*/
public static void main(String[] args) {
NationalWeatherSvcClient client = new NationalWeatherSvcClient();
//Creates and launches the GUI.
client.createGUI();
}
/**
* Sends a SOAP request to the web service on website http://w1.weather.gov and displays
* the current weather conditions for the latitude and longitude location on the GUI.
* Stubs are generated for Web Service defined by the wsdl file at https://graphical.weather.gov/xml/DWMLgen/wsdl/ndfdXML.wsdl
* @param latitude latitude of the location
* @param longitude longitude of the location
* @return current weather conditions for the latitude and longitude location.
*/
private String getWeatherConditions(BigDecimal latitude, BigDecimal longitude) {
String ndfdXmlResponse = new String();
try {
NdfdXMLStub stub = new NdfdXMLStub();
stub._getServiceClient().getOptions().setProperty(org.apache.axis2.transport
.http.HTTPConstants.CHUNKED, Boolean.FALSE);
//Use the stub generated for the web services, set the latitude, longitude values.
NdfdXMLStub.NDFDgen request = new NdfdXMLStub.NDFDgen();
request.setLatitude(latitude);
request.setLongitude(longitude);
request.setProduct(NdfdXMLStub.ProductType.value1);
//call the web service function and get the xml response.
NdfdXMLStub.NDFDgenResponse response = stub.nDFDgen(request);
ndfdXmlResponse = response.getDwmlOut();
} catch (AxisFault af) {
af.printStackTrace();
} catch (RemoteException re) {
re.printStackTrace();
}
System.out.println(ndfdXmlResponse);
return parseXMLResponse(ndfdXmlResponse);
}
/**
* Parse the xml response from the weather service.
* @param xmlResponse xml response
* @return values of the parameters.
*/
private String parseXMLResponse(String xmlResponse) {
StringBuffer weatherConditions = new StringBuffer("Weather Conditions : \n\n");
try {
Document document = DocumentBuilderFactory.newInstance()
.newDocumentBuilder()
.parse(new ByteArrayInputStream(xmlResponse.getBytes()));
XPath xPath = XPathFactory.newInstance().newXPath();
DateFormat dtf = new SimpleDateFormat("yyyy-MM-dd");
String currentDate = dtf.format(new Date());
String expression = "/dwml/data/time-layout[@time-coordinate='local']/start-valid-time";
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(document, XPathConstants.NODESET);
int number = 0;
for (int i = 0; i < 7; i++) {
if (currentDate.equals(nodeList.item(i).getFirstChild().getNodeValue().substring(0, 10))) {
number = i;
break;
}
}
//Parse the xml file using XPath and get the values of various parameters.
weatherConditions.append("Maximum Temperature = ")
.append(getParameterValue(document, xPath,
"/dwml/data/parameters/temperature[@type='maximum']/value", number))
.append("\n");
weatherConditions.append("Minimum Temperature = ")
.append(getParameterValue(document, xPath,
"/dwml/data/parameters/temperature[@type='minimum']/value", number))
.append("\n");
weatherConditions.append("Dew Point Temperature = ")
.append(getParameterValue(document, xPath,
"/dwml/data/parameters/temperature[@type='dew point']/value", number))
.append("\n");
weatherConditions.append("12 Hourly Probability of Precipitation = ")
.append(getParameterValue(document, xPath,
"/dwml/data/parameters/probability-of-precipitation[@type='12 hour']/value", number))
.append("\n");
weatherConditions.append("Cloud Cover Amount = ")
.append(getParameterValue(document, xPath,
"/dwml/data/parameters/cloud-amount[@type='total']/value", number))
.append("\n");
weatherConditions.append("Wind Speed = ")
.append(getParameterValue(document, xPath,
"/dwml/data/parameters/wind-speed[@type='sustained']/value", number))
.append("\n");
weatherConditions.append("Wind Direction = ")
.append(getParameterValue(document, xPath,
"/dwml/data/parameters/direction[@type='wind']/value", number))
.append("\n");
weatherConditions.append("Wave Height = ")
.append(getParameterValue(document, xPath,
"/dwml/data/parameters/water-state/waves[@type='significant']/value", number))
.append("\n");
} catch (Exception e) {
e.printStackTrace();
}
return weatherConditions.toString();
}
/**
* Gets the value of the parameter represented by the expression.
* @param document xml document
* @param xPath XPath object
* @param expression expression for the parameter whose value is to be retrieved.
* @param number the index of the data.
* @return the value for the parameter expression.
* @throws XPathExpressionException
*/
private String getParameterValue(Document document, XPath xPath, String expression, int number)
throws XPathExpressionException {
String parameterValue = "";
NodeList nodeList = (NodeList) xPath.compile(expression).evaluate(document, XPathConstants.NODESET);
if (nodeList != null && nodeList.item(number) != null && nodeList.item(number).getFirstChild() != null)
parameterValue = nodeList.item(number).getFirstChild().getNodeValue();
return parameterValue;
}
/**
* Text field to input the latitude.
*/
private JTextField latitudeTextField = new JTextField(10);
/**
* Text field to input the longitude.
*/
private JTextField longitudeTextField = new JTextField(10);
/**
* Text Area to display the weather conditions.
*/
private JTextArea weatherCondTextArea = new JTextArea(25, 28);
/**
* Creates the client GUI which takes input of latitude and longitude of the location from the user and
* displays the current weather conditions for the location in the text area on the GUI.
*/
private void createGUI() {
JFrame frame = new JFrame();
frame.setTitle("Lab 3 - National Weather Service");
Container contentPane = frame.getContentPane();
SpringLayout paneLayout = new SpringLayout();
contentPane.setLayout(paneLayout);
//Creates the label for location.
JLabel locationLabel = new JLabel("Location: ", JLabel.TRAILING);
contentPane.add(locationLabel);
//Creates the label for textfield to entering the latitude.
JLabel latitudeLabel = new JLabel("Latitude: ", JLabel.TRAILING);
contentPane.add(latitudeLabel);
//Creates the textfield for entering the latitude.
latitudeLabel.setLabelFor(latitudeTextField);
contentPane.add(latitudeTextField);
//Creates the label for textfield to entering the longitude.
JLabel longitudeLabel = new JLabel("Longitude: ", JLabel.TRAILING);
contentPane.add(longitudeLabel);
//Creates the textfield for entering the longitude.
longitudeLabel.setLabelFor(longitudeTextField);
contentPane.add(longitudeTextField);
//Refresh button, on clicking sends a soap request to the server and
//refreshes the data on GUI.
JButton refreshButton = new JButton("REFRESH");
refreshButton.setVerticalTextPosition(AbstractButton.CENTER);
refreshButton.setHorizontalTextPosition(AbstractButton.CENTER);
contentPane.add(refreshButton);
refreshButton.addActionListener(this);
//Exit button to close the client window.
JButton exitButton = new JButton("EXIT");
exitButton.setVerticalTextPosition(AbstractButton.CENTER);
exitButton.setHorizontalTextPosition(AbstractButton.CENTER);
contentPane.add(exitButton);
exitButton.addActionListener(this);
//Label for the weather conditions textArea.
JLabel weatherCondLabel = new JLabel("Weather Conditions: ", JLabel.TRAILING);
contentPane.add(weatherCondLabel);
//Weather Conditions textArea used to display the response received from server.
JScrollPane weatherCondTextAScroll = new JScrollPane(weatherCondTextArea);
weatherCondTextArea.setEditable(false);
weatherCondTextArea.setLineWrap(true);
contentPane.add(weatherCondTextAScroll);
//Layout all the components above on the frame.
paneLayout.putConstraint(SpringLayout.WEST, locationLabel, 25, SpringLayout.WEST, contentPane);
paneLayout.putConstraint(SpringLayout.NORTH, locationLabel, 20, SpringLayout.NORTH, contentPane);
paneLayout.putConstraint(SpringLayout.WEST, latitudeLabel, 25, SpringLayout.WEST, locationLabel);
paneLayout.putConstraint(SpringLayout.NORTH, latitudeLabel, 27, SpringLayout.NORTH, locationLabel);
paneLayout.putConstraint(SpringLayout.WEST, latitudeTextField, 5, SpringLayout.EAST, latitudeLabel);
paneLayout.putConstraint(SpringLayout.NORTH, latitudeTextField, 25, SpringLayout.NORTH, locationLabel);
paneLayout.putConstraint(SpringLayout.WEST, longitudeLabel, 25, SpringLayout.EAST, latitudeTextField);
paneLayout.putConstraint(SpringLayout.NORTH, longitudeLabel, 27, SpringLayout.NORTH, locationLabel);
paneLayout.putConstraint(SpringLayout.WEST, longitudeTextField, 5, SpringLayout.EAST, longitudeLabel);
paneLayout.putConstraint(SpringLayout.NORTH, longitudeTextField, 25, SpringLayout.NORTH, locationLabel);
paneLayout.putConstraint(SpringLayout.WEST, refreshButton, 100, SpringLayout.WEST, contentPane);
paneLayout.putConstraint(SpringLayout.NORTH, refreshButton, 10, SpringLayout.SOUTH, longitudeTextField);
paneLayout.putConstraint(SpringLayout.WEST, exitButton, 10, SpringLayout.EAST, refreshButton);
paneLayout.putConstraint(SpringLayout.NORTH, exitButton, 10, SpringLayout.SOUTH, longitudeTextField);
paneLayout.putConstraint(SpringLayout.WEST, weatherCondLabel, 25, SpringLayout.WEST, contentPane);
paneLayout.putConstraint(SpringLayout.NORTH, weatherCondLabel, 15, SpringLayout.SOUTH, exitButton);
paneLayout.putConstraint(SpringLayout.WEST, weatherCondTextAScroll, 10, SpringLayout.EAST, weatherCondLabel);
paneLayout.putConstraint(SpringLayout.NORTH, weatherCondTextAScroll, 15, SpringLayout.SOUTH, exitButton);
paneLayout.putConstraint(SpringLayout.EAST, contentPane, 15, SpringLayout.EAST, weatherCondTextAScroll);
paneLayout.putConstraint(SpringLayout.SOUTH, contentPane, 15, SpringLayout.SOUTH, weatherCondTextAScroll);
contentPane.setVisible(true);
frame.pack();
frame.setVisible(true);
}
/**
* Handles the events created by clicking the buttons REFRESH and EXIT on the GUI.
* On clicking REFRESH sends the inputed latitude and longitude of location using SOAP request to the web service
* on website http://w1.weather.gov and displays the current weather conditions in the text area on GUI.
* On clicking EXIT, shutdowns the client.
* @param actEvent The click REFRESH and EXIT events object.
*/
public void actionPerformed(ActionEvent actEvent) {
//Handles the event generated on clicking REFRESH button on the GUI.
if ("REFRESH".equals(actEvent.getActionCommand())) {
//On refresh, get the data again from the web service and display on UI.
String weatherConditions = getWeatherConditions(new BigDecimal(latitudeTextField.getText()),
new BigDecimal(longitudeTextField.getText()));
weatherCondTextArea.setText(weatherConditions);
//Handles the event generated on clicking the EXIT button on GUI.
} else if ("EXIT".equals(actEvent.getActionCommand().trim())) {
System.exit(0);
}
}
}
|
package ip7.bathuniapp;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.Collections;
/*
* Stores stops and their associated times for a single bus route
* The times are stored in the form hours * 60 + minutes, where
* the hours are taken from midnight. So 13:23 would be stored as
* 13 * 60 + 23 = 803.
*/
public class BusRoute {
// A map to link between a stop name and a list of times
// The bus stops at this point.
private Map<String, ArrayList<Integer>> stops;
public BusRoute(String name, String type) {
this.stops = new HashMap<String, ArrayList<Integer>>();
}
// Adds a stop to this bus route with the given ArrayList of times
public void addStop(String stopName, ArrayList<Integer> times) {
// Make sure all times are correct
for (int i = 0; i < times.size(); i++) {
times.set(i, times.get(i) % 1440);
}
stops.put(stopName, times);
}
// Adds the given time to the given stopName
// If time is >= 1440, it is in the next day.
public void addStopTime(String stopName, int time) {
stops.get(stopName).add(time % 1400);
}
// Returns an ArrayList of all the times for this stop
public ArrayList<Integer> getAllTimes(String stopName) {
return stops.get(stopName);
}
// Get an ArrayList of the next hour starting from the given time
public ArrayList<Integer> getTimesAt(String stopName, int startTime) {
ArrayList<Integer> stopTimes = stops.get(stopName);
ArrayList<Integer> returnTimes = new ArrayList<Integer>();
if(stopTimes != null) {
Collections.sort(stopTimes);
for (int i = 0; i < stopTimes.size(); i++) {
int testTime = stopTimes.get(i);
if ((testTime >= startTime) && (testTime <= ((startTime + 60) % 1440))) {
returnTimes.add(testTime);
}
}
}
return returnTimes;
}
// Returns an ArrayList of all the stops on a route
public ArrayList<String> getAllStops() {
return new ArrayList<String>(stops.keySet());
}
// Returns the next bus time for the given stopName on this route.
// If no next time is found, returns -1
public int getNextTime(String stopName, int currentTime) {
// Make sure current time is correct
currentTime = currentTime % 1440;
ArrayList<Integer> stopTimes = stops.get(stopName);
if(stopTimes != null) {
Collections.sort(stopTimes);
for (int i = 0; i < stopTimes.size(); i++) {
int testTime = stopTimes.get(i);
if (testTime >= currentTime) {
return testTime;
}
}
}
return -1;
}
}
|
package com.shangcai.action.manager.material;
public interface ICompanyAction {
/**
* 获取鞋企业列表信息
*/
public void list() throws Exception;
}
|
package com.wentongwang.mysports.views.viewholder;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.widget.ImageView;
import com.wentongwang.mysports.R;
import com.wangwentong.sports_api.model.SportEvents;
import butterknife.BindView;
/**
* Created by Wentong WANG on 2017/4/2.
*/
public class SportTypeViewHolder extends ItemViewHolder<SportEvents> {
@BindView(R.id.event_icon)
ImageView eventIcon;
@BindView(R.id.iv_selected)
ImageView selected;
private SportEvents event;
public SportTypeViewHolder(View view) {
super(view);
}
@Override
public void setItem(SportEvents sportEvents) {
this.event = sportEvents;
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), sportEvents.getEventImage());
eventIcon.setImageBitmap(bitmap);
if (sportEvents.isSelected()) {
selected.setVisibility(View.VISIBLE);
} else {
selected.setVisibility(View.INVISIBLE);
}
}
public void setOnIconSelectListener(View.OnClickListener listener){
eventIcon.setOnClickListener(listener);
}
public boolean isEventSelected(){
return event.isSelected();
}
public void setSelectedIconVisibility(boolean visibility){
if (visibility){
selected.setVisibility(View.INVISIBLE);
event.setIsSelected(false);
}else{
selected.setVisibility(View.VISIBLE);
event.setIsSelected(true);
}
}
}
|
package com.project.database.entities;
import lombok.*;
import javax.persistence.*;
@Entity
@Table(name = "tutor")
@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class TutorEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "tutor_no")
private Integer tutorNo;
@Column(name = "tutor_name")
private String tutorName;
@Column(name = "tutor_surname")
private String tutorSurname;
@Column(name = "tutor_patronymic")
private String tutorPatronymic;
@Column(name = "science_degree")
private String scienceDegree;
@Column(name = "academ_status")
private String academStatus;
@Column(name = "position")
private String position;
}
|
package com.example.demo.controller;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import com.example.demo.command.EmpCommand;
import com.example.demo.command.LoginCmd;
import com.example.demo.dao.EmployeeRepo;
import com.example.demo.model.Employee;
import com.example.demo.services.EmployeeServices;
@Controller
public class DashboardController {
@Autowired
EmployeeServices es;
@Autowired
EmployeeRepo e_repo;
@RequestMapping("/vms")
public String loginPage(Model m) {
LoginCmd cmd= new LoginCmd();
m.addAttribute("login",cmd);
return "index";
}
@RequestMapping("/reg_form")
public String registerEmp(Model m) {
EmpCommand emp= new EmpCommand();
m.addAttribute("command", emp);
return "reg_form";
}
@RequestMapping("/register")
public String registerEmp(@ModelAttribute ("command") EmpCommand empCommand, Model m, HttpSession session) {
Integer eid= (Integer) session.getAttribute("e_id");
if(eid==null) {
Employee e=new Employee();
e=empCommand.getEmp();
e.setErole(es.ROLE_USER);
e_repo.save(e);
return "redirect:/vms?act=reg";
} else{
empCommand.getEmp().setEid(eid);
empCommand.getEmp().setErole(es.ROLE_USER);
e_repo.save(empCommand.getEmp());
return "redirect:/admin";
}
}
@RequestMapping("/admin")
public String adminDashboard(Model m) {
List<Employee> emplist= e_repo.findByErole(es.ROLE_USER);
m.addAttribute("emplist", emplist);
return "adminUI";
}
}
|
package com.example.weather;
import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.location.Address;
import android.location.Geocoder;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import com.example.weather.Common.Constant;
import com.example.weather.Common.PreferenceHelper;
import com.example.weather.Model.WeatherDetails;
import com.example.weather.NetworkRequest.RequestInterface;
import com.example.weather.NetworkRequest.RetrofitController;
import com.example.weather.Utils.CheckInternetConnectivity;
import com.example.weather.Utils.Utils;
import org.apache.commons.io.FileUtils;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class TaskSchedular extends Service {
public RequestInterface requestInterface;
@Override
public int onStartCommand(final Intent intent, int flags, int startId) {
final Bundle bundle = intent.getExtras();
assert bundle != null;
try {
requestWeatherAPI(bundle.getString(Constant.LATITUDE), bundle.getString(Constant.LONGITUDE));
} catch (IOException e) {
e.printStackTrace();
}
return Service.START_NOT_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
public void requestWeatherAPI(final String lat, final String lon) throws IOException {
if (CheckInternetConnectivity.checkConnectivity(this)) {
if (getCacheDir().exists()) {
FileUtils.deleteDirectory(getCacheDir());
}
requestInterface = RetrofitController.getInstance(this).create(RequestInterface.class);
Call<WeatherDetails> calleque = requestInterface.getWeatherDetails(lat, lon, Constant.TEMP_UNITS, Constant.API_KEY);
calleque.enqueue(new Callback<WeatherDetails>() {
@Override
public void onResponse(Call<WeatherDetails> call, Response<WeatherDetails> response) {
if (CheckInternetConnectivity.checkConnectivity(getBaseContext())) {
if (response.body() != null) {
if (response.body().getCod().equals(Constant.SUCCESS_RESPONSE)) {
PreferenceHelper.getInstance().setLatitude(Utils.getConvertedDecimal(lat));
} else {
Toast.makeText(getBaseContext(), getResources().getText(R.string.msg_api_error, response.body().getCod()), Toast.LENGTH_SHORT).show();
}
}
}
}
@Override
public void onFailure(Call<WeatherDetails> call, Throwable t) {
Toast.makeText(getBaseContext(), getResources().getText(R.string.msg_call_failed, t.getMessage()), Toast.LENGTH_SHORT).show();
}
});
}
}
}
|
package com.yaochen.address.web.controllers;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.easyooo.framework.support.mybatis.Pagination;
import com.yaochen.address.dto.db.NoticeQueryForm;
import com.yaochen.address.service.NoticeService;
import com.yaochen.address.web.support.ReturnValueUtil;
import com.yaochen.address.web.support.Root;
@Controller
@RequestMapping("/notice")
public class NoticeController {
@Autowired private NoticeService noticeService;
/**
* @throws Throwable
*/
@RequestMapping(value="/query")
@ResponseBody
public Root<Pagination> query(NoticeQueryForm notice,Integer start,Integer limit) throws Throwable{
return ReturnValueUtil.getJsonRoot(noticeService.query(notice,start,limit));
}
/**
* @throws Throwable
*/
@RequestMapping(value="/queryCities")
@ResponseBody
public Root<List<String>> queryCities(Integer noticeId) throws Throwable{
return ReturnValueUtil.getJsonRoot(noticeService.queryCities(noticeId));
}
/**
* @throws Throwable
*/
@RequestMapping(value="/countUnRead")
@ResponseBody
public Root<Integer> countUnRead() throws Throwable{
Integer countUnChecked = noticeService.countUnChecked();
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("cnt", countUnChecked);
return ReturnValueUtil.getJsonRoot(countUnChecked);
}
/**
* @throws Throwable
*/
@RequestMapping(value="/save")
@ResponseBody
public Root<Void> save(NoticeQueryForm notice,String [] countyIds) throws Throwable{
noticeService.save(notice,countyIds);
return ReturnValueUtil.getVoidRoot();
}
/**
* @param noticeId
* @throws Throwable
*/
@RequestMapping(value="/remove")
@ResponseBody
public Root<Void> remove(Integer noticeId) throws Throwable{
noticeService.remove(noticeId);
return ReturnValueUtil.getVoidRoot();
}
/**
* @throws Throwable
*/
@RequestMapping(value="/checkRead")
@ResponseBody
public Root<Void> checkRead(Integer noticeId) throws Throwable{
noticeService.saveCheckRead(noticeId);
return ReturnValueUtil.getVoidRoot();
}
}
|
package org.codeaholics.testing.mock.resultset;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.URL;
import java.sql.Array;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Date;
import java.sql.NClob;
import java.sql.Ref;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.RowId;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Statement;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Map;
import javax.sql.rowset.CachedRowSet;
import org.codeaholics.testing.mock.resultset.impl.DataProvider;
import org.codeaholics.testing.mock.resultset.impl.ResultSetSyncProvider;
import org.codeaholics.testing.mock.resultset.impl.WrappedCachedRowSet;
public class MockResultSet implements ResultSet {
private final CachedRowSet cachedRowSet;
public MockResultSet(final DataProvider dataProvider) throws SQLException {
cachedRowSet = new WrappedCachedRowSet(dataProvider);
cachedRowSet.setSyncProvider(ResultSetSyncProvider.getProviderId());
cachedRowSet.execute();
cachedRowSet.beforeFirst();
}
public boolean absolute(final int row) throws SQLException {
return cachedRowSet.absolute(row);
}
public void afterLast() throws SQLException {
cachedRowSet.afterLast();
}
public void beforeFirst() throws SQLException {
cachedRowSet.beforeFirst();
}
public void cancelRowUpdates() throws SQLException {
cachedRowSet.cancelRowUpdates();
}
public void clearWarnings() throws SQLException {
cachedRowSet.clearWarnings();
}
public void close() throws SQLException {
cachedRowSet.close();
}
public void deleteRow() throws SQLException {
cachedRowSet.deleteRow();
}
public int findColumn(final String columnLabel) throws SQLException {
return cachedRowSet.findColumn(columnLabel);
}
public boolean first() throws SQLException {
return cachedRowSet.first();
}
public Array getArray(final int columnIndex) throws SQLException {
return cachedRowSet.getArray(columnIndex);
}
public Array getArray(final String columnLabel) throws SQLException {
return cachedRowSet.getArray(columnLabel);
}
public InputStream getAsciiStream(final int columnIndex) throws SQLException {
return cachedRowSet.getAsciiStream(columnIndex);
}
public InputStream getAsciiStream(final String columnLabel) throws SQLException {
return cachedRowSet.getAsciiStream(columnLabel);
}
@Deprecated
public BigDecimal getBigDecimal(final int columnIndex, final int scale) throws SQLException {
return cachedRowSet.getBigDecimal(columnIndex, scale);
}
public BigDecimal getBigDecimal(final int columnIndex) throws SQLException {
return cachedRowSet.getBigDecimal(columnIndex);
}
@Deprecated
public BigDecimal getBigDecimal(final String columnLabel, final int scale) throws SQLException {
return cachedRowSet.getBigDecimal(columnLabel, scale);
}
public BigDecimal getBigDecimal(final String columnLabel) throws SQLException {
return cachedRowSet.getBigDecimal(columnLabel);
}
public InputStream getBinaryStream(final int columnIndex) throws SQLException {
return cachedRowSet.getBinaryStream(columnIndex);
}
public InputStream getBinaryStream(final String columnLabel) throws SQLException {
return cachedRowSet.getBinaryStream(columnLabel);
}
public Blob getBlob(final int columnIndex) throws SQLException {
return cachedRowSet.getBlob(columnIndex);
}
public Blob getBlob(final String columnLabel) throws SQLException {
return cachedRowSet.getBlob(columnLabel);
}
public boolean getBoolean(final int columnIndex) throws SQLException {
return cachedRowSet.getBoolean(columnIndex);
}
public boolean getBoolean(final String columnLabel) throws SQLException {
return cachedRowSet.getBoolean(columnLabel);
}
public byte getByte(final int columnIndex) throws SQLException {
return cachedRowSet.getByte(columnIndex);
}
public byte getByte(final String columnLabel) throws SQLException {
return cachedRowSet.getByte(columnLabel);
}
public byte[] getBytes(final int columnIndex) throws SQLException {
return cachedRowSet.getBytes(columnIndex);
}
public byte[] getBytes(final String columnLabel) throws SQLException {
return cachedRowSet.getBytes(columnLabel);
}
public Reader getCharacterStream(final int columnIndex) throws SQLException {
return cachedRowSet.getCharacterStream(columnIndex);
}
public Reader getCharacterStream(final String columnLabel) throws SQLException {
return cachedRowSet.getCharacterStream(columnLabel);
}
public Clob getClob(final int columnIndex) throws SQLException {
return cachedRowSet.getClob(columnIndex);
}
public Clob getClob(final String columnLabel) throws SQLException {
return cachedRowSet.getClob(columnLabel);
}
public int getConcurrency() throws SQLException {
return cachedRowSet.getConcurrency();
}
public String getCursorName() throws SQLException {
return cachedRowSet.getCursorName();
}
public Date getDate(final int columnIndex, final Calendar cal) throws SQLException {
return cachedRowSet.getDate(columnIndex, cal);
}
public Date getDate(final int columnIndex) throws SQLException {
return cachedRowSet.getDate(columnIndex);
}
public Date getDate(final String columnLabel, final Calendar cal) throws SQLException {
return cachedRowSet.getDate(columnLabel, cal);
}
public Date getDate(final String columnLabel) throws SQLException {
return cachedRowSet.getDate(columnLabel);
}
public double getDouble(final int columnIndex) throws SQLException {
return cachedRowSet.getDouble(columnIndex);
}
public double getDouble(final String columnLabel) throws SQLException {
return cachedRowSet.getDouble(columnLabel);
}
public int getFetchDirection() throws SQLException {
return cachedRowSet.getFetchDirection();
}
public int getFetchSize() throws SQLException {
return cachedRowSet.getFetchSize();
}
public float getFloat(final int columnIndex) throws SQLException {
return cachedRowSet.getFloat(columnIndex);
}
public float getFloat(final String columnLabel) throws SQLException {
return cachedRowSet.getFloat(columnLabel);
}
public int getHoldability() throws SQLException {
return cachedRowSet.getHoldability();
}
public int getInt(final int columnIndex) throws SQLException {
return cachedRowSet.getInt(columnIndex);
}
public int getInt(final String columnLabel) throws SQLException {
return cachedRowSet.getInt(columnLabel);
}
public long getLong(final int columnIndex) throws SQLException {
return cachedRowSet.getLong(columnIndex);
}
public long getLong(final String columnLabel) throws SQLException {
return cachedRowSet.getLong(columnLabel);
}
public ResultSetMetaData getMetaData() throws SQLException {
return cachedRowSet.getMetaData();
}
public Reader getNCharacterStream(final int columnIndex) throws SQLException {
return cachedRowSet.getNCharacterStream(columnIndex);
}
public Reader getNCharacterStream(final String columnLabel) throws SQLException {
return cachedRowSet.getNCharacterStream(columnLabel);
}
public NClob getNClob(final int columnIndex) throws SQLException {
return cachedRowSet.getNClob(columnIndex);
}
public NClob getNClob(final String columnLabel) throws SQLException {
return cachedRowSet.getNClob(columnLabel);
}
public String getNString(final int columnIndex) throws SQLException {
return cachedRowSet.getNString(columnIndex);
}
public String getNString(final String columnLabel) throws SQLException {
return cachedRowSet.getNString(columnLabel);
}
public Object getObject(final int columnIndex, final Map<String, Class<?>> map) throws SQLException {
return cachedRowSet.getObject(columnIndex, map);
}
public Object getObject(final int columnIndex) throws SQLException {
return cachedRowSet.getObject(columnIndex);
}
public Object getObject(final String columnLabel, final Map<String, Class<?>> map) throws SQLException {
return cachedRowSet.getObject(columnLabel, map);
}
public Object getObject(final String columnLabel) throws SQLException {
return cachedRowSet.getObject(columnLabel);
}
public Ref getRef(final int columnIndex) throws SQLException {
return cachedRowSet.getRef(columnIndex);
}
public Ref getRef(final String columnLabel) throws SQLException {
return cachedRowSet.getRef(columnLabel);
}
public int getRow() throws SQLException {
return cachedRowSet.getRow();
}
public RowId getRowId(final int columnIndex) throws SQLException {
return cachedRowSet.getRowId(columnIndex);
}
public RowId getRowId(final String columnLabel) throws SQLException {
return cachedRowSet.getRowId(columnLabel);
}
public short getShort(final int columnIndex) throws SQLException {
return cachedRowSet.getShort(columnIndex);
}
public short getShort(final String columnLabel) throws SQLException {
return cachedRowSet.getShort(columnLabel);
}
public SQLXML getSQLXML(final int columnIndex) throws SQLException {
return cachedRowSet.getSQLXML(columnIndex);
}
public SQLXML getSQLXML(final String columnLabel) throws SQLException {
return cachedRowSet.getSQLXML(columnLabel);
}
public Statement getStatement() throws SQLException {
return cachedRowSet.getStatement();
}
public String getString(final int columnIndex) throws SQLException {
return cachedRowSet.getString(columnIndex);
}
public String getString(final String columnLabel) throws SQLException {
return cachedRowSet.getString(columnLabel);
}
public Time getTime(final int columnIndex, final Calendar cal) throws SQLException {
return cachedRowSet.getTime(columnIndex, cal);
}
public Time getTime(final int columnIndex) throws SQLException {
return cachedRowSet.getTime(columnIndex);
}
public Time getTime(final String columnLabel, final Calendar cal) throws SQLException {
return cachedRowSet.getTime(columnLabel, cal);
}
public Time getTime(final String columnLabel) throws SQLException {
return cachedRowSet.getTime(columnLabel);
}
public Timestamp getTimestamp(final int columnIndex, final Calendar cal) throws SQLException {
return cachedRowSet.getTimestamp(columnIndex, cal);
}
public Timestamp getTimestamp(final int columnIndex) throws SQLException {
return cachedRowSet.getTimestamp(columnIndex);
}
public Timestamp getTimestamp(final String columnLabel, final Calendar cal) throws SQLException {
return cachedRowSet.getTimestamp(columnLabel, cal);
}
public Timestamp getTimestamp(final String columnLabel) throws SQLException {
return cachedRowSet.getTimestamp(columnLabel);
}
public int getType() throws SQLException {
return cachedRowSet.getType();
}
@Deprecated
public InputStream getUnicodeStream(final int columnIndex) throws SQLException {
return cachedRowSet.getUnicodeStream(columnIndex);
}
@Deprecated
public InputStream getUnicodeStream(final String columnLabel) throws SQLException {
return cachedRowSet.getUnicodeStream(columnLabel);
}
public URL getURL(final int columnIndex) throws SQLException {
return cachedRowSet.getURL(columnIndex);
}
public URL getURL(final String columnLabel) throws SQLException {
return cachedRowSet.getURL(columnLabel);
}
public SQLWarning getWarnings() throws SQLException {
return cachedRowSet.getWarnings();
}
public void insertRow() throws SQLException {
cachedRowSet.insertRow();
}
public boolean isAfterLast() throws SQLException {
return cachedRowSet.isAfterLast();
}
public boolean isBeforeFirst() throws SQLException {
return cachedRowSet.isBeforeFirst();
}
public boolean isClosed() throws SQLException {
return cachedRowSet.isClosed();
}
public boolean isFirst() throws SQLException {
return cachedRowSet.isFirst();
}
public boolean isLast() throws SQLException {
return cachedRowSet.isLast();
}
public boolean isWrapperFor(final Class<?> iface) throws SQLException {
return cachedRowSet.isWrapperFor(iface);
}
public boolean last() throws SQLException {
return cachedRowSet.last();
}
public void moveToCurrentRow() throws SQLException {
cachedRowSet.moveToCurrentRow();
}
public void moveToInsertRow() throws SQLException {
cachedRowSet.moveToInsertRow();
}
public boolean next() throws SQLException {
return cachedRowSet.next();
}
public boolean previous() throws SQLException {
return cachedRowSet.previous();
}
public void refreshRow() throws SQLException {
cachedRowSet.refreshRow();
}
public boolean relative(final int rows) throws SQLException {
return cachedRowSet.relative(rows);
}
public boolean rowDeleted() throws SQLException {
return cachedRowSet.rowDeleted();
}
public boolean rowInserted() throws SQLException {
return cachedRowSet.rowInserted();
}
public boolean rowUpdated() throws SQLException {
return cachedRowSet.rowUpdated();
}
public void setFetchDirection(final int direction) throws SQLException {
cachedRowSet.setFetchDirection(direction);
}
public void setFetchSize(final int rows) throws SQLException {
cachedRowSet.setFetchSize(rows);
}
public <T> T unwrap(final Class<T> iface) throws SQLException {
return cachedRowSet.unwrap(iface);
}
public void updateArray(final int columnIndex, final Array x) throws SQLException {
cachedRowSet.updateArray(columnIndex, x);
}
public void updateArray(final String columnLabel, final Array x) throws SQLException {
cachedRowSet.updateArray(columnLabel, x);
}
public void updateAsciiStream(final int columnIndex, final InputStream x, final int length) throws SQLException {
cachedRowSet.updateAsciiStream(columnIndex, x, length);
}
public void updateAsciiStream(final int columnIndex, final InputStream x, final long length) throws SQLException {
cachedRowSet.updateAsciiStream(columnIndex, x, length);
}
public void updateAsciiStream(final int columnIndex, final InputStream x) throws SQLException {
cachedRowSet.updateAsciiStream(columnIndex, x);
}
public void updateAsciiStream(final String columnLabel, final InputStream x, final int length) throws SQLException {
cachedRowSet.updateAsciiStream(columnLabel, x, length);
}
public void updateAsciiStream(final String columnLabel, final InputStream x, final long length) throws SQLException {
cachedRowSet.updateAsciiStream(columnLabel, x, length);
}
public void updateAsciiStream(final String columnLabel, final InputStream x) throws SQLException {
cachedRowSet.updateAsciiStream(columnLabel, x);
}
public void updateBigDecimal(final int columnIndex, final BigDecimal x) throws SQLException {
cachedRowSet.updateBigDecimal(columnIndex, x);
}
public void updateBigDecimal(final String columnLabel, final BigDecimal x) throws SQLException {
cachedRowSet.updateBigDecimal(columnLabel, x);
}
public void updateBinaryStream(final int columnIndex, final InputStream x, final int length) throws SQLException {
cachedRowSet.updateBinaryStream(columnIndex, x, length);
}
public void updateBinaryStream(final int columnIndex, final InputStream x, final long length) throws SQLException {
cachedRowSet.updateBinaryStream(columnIndex, x, length);
}
public void updateBinaryStream(final int columnIndex, final InputStream x) throws SQLException {
cachedRowSet.updateBinaryStream(columnIndex, x);
}
public void updateBinaryStream(final String columnLabel, final InputStream x, final int length) throws SQLException {
cachedRowSet.updateBinaryStream(columnLabel, x, length);
}
public void updateBinaryStream(final String columnLabel, final InputStream x, final long length) throws SQLException {
cachedRowSet.updateBinaryStream(columnLabel, x, length);
}
public void updateBinaryStream(final String columnLabel, final InputStream x) throws SQLException {
cachedRowSet.updateBinaryStream(columnLabel, x);
}
public void updateBlob(final int columnIndex, final Blob x) throws SQLException {
cachedRowSet.updateBlob(columnIndex, x);
}
public void updateBlob(final int columnIndex, final InputStream inputStream, final long length) throws SQLException {
cachedRowSet.updateBlob(columnIndex, inputStream, length);
}
public void updateBlob(final int columnIndex, final InputStream inputStream) throws SQLException {
cachedRowSet.updateBlob(columnIndex, inputStream);
}
public void updateBlob(final String columnLabel, final Blob x) throws SQLException {
cachedRowSet.updateBlob(columnLabel, x);
}
public void updateBlob(final String columnLabel, final InputStream inputStream, final long length) throws SQLException {
cachedRowSet.updateBlob(columnLabel, inputStream, length);
}
public void updateBlob(final String columnLabel, final InputStream inputStream) throws SQLException {
cachedRowSet.updateBlob(columnLabel, inputStream);
}
public void updateBoolean(final int columnIndex, final boolean x) throws SQLException {
cachedRowSet.updateBoolean(columnIndex, x);
}
public void updateBoolean(final String columnLabel, final boolean x) throws SQLException {
cachedRowSet.updateBoolean(columnLabel, x);
}
public void updateByte(final int columnIndex, final byte x) throws SQLException {
cachedRowSet.updateByte(columnIndex, x);
}
public void updateByte(final String columnLabel, final byte x) throws SQLException {
cachedRowSet.updateByte(columnLabel, x);
}
public void updateBytes(final int columnIndex, final byte[] x) throws SQLException {
cachedRowSet.updateBytes(columnIndex, x);
}
public void updateBytes(final String columnLabel, final byte[] x) throws SQLException {
cachedRowSet.updateBytes(columnLabel, x);
}
public void updateCharacterStream(final int columnIndex, final Reader x, final int length) throws SQLException {
cachedRowSet.updateCharacterStream(columnIndex, x, length);
}
public void updateCharacterStream(final int columnIndex, final Reader x, final long length) throws SQLException {
cachedRowSet.updateCharacterStream(columnIndex, x, length);
}
public void updateCharacterStream(final int columnIndex, final Reader x) throws SQLException {
cachedRowSet.updateCharacterStream(columnIndex, x);
}
public void updateCharacterStream(final String columnLabel, final Reader reader, final int length) throws SQLException {
cachedRowSet.updateCharacterStream(columnLabel, reader, length);
}
public void updateCharacterStream(final String columnLabel, final Reader reader, final long length) throws SQLException {
cachedRowSet.updateCharacterStream(columnLabel, reader, length);
}
public void updateCharacterStream(final String columnLabel, final Reader reader) throws SQLException {
cachedRowSet.updateCharacterStream(columnLabel, reader);
}
public void updateClob(final int columnIndex, final Clob x) throws SQLException {
cachedRowSet.updateClob(columnIndex, x);
}
public void updateClob(final int columnIndex, final Reader reader, final long length) throws SQLException {
cachedRowSet.updateClob(columnIndex, reader, length);
}
public void updateClob(final int columnIndex, final Reader reader) throws SQLException {
cachedRowSet.updateClob(columnIndex, reader);
}
public void updateClob(final String columnLabel, final Clob x) throws SQLException {
cachedRowSet.updateClob(columnLabel, x);
}
public void updateClob(final String columnLabel, final Reader reader, final long length) throws SQLException {
cachedRowSet.updateClob(columnLabel, reader, length);
}
public void updateClob(final String columnLabel, final Reader reader) throws SQLException {
cachedRowSet.updateClob(columnLabel, reader);
}
public void updateDate(final int columnIndex, final Date x) throws SQLException {
cachedRowSet.updateDate(columnIndex, x);
}
public void updateDate(final String columnLabel, final Date x) throws SQLException {
cachedRowSet.updateDate(columnLabel, x);
}
public void updateDouble(final int columnIndex, final double x) throws SQLException {
cachedRowSet.updateDouble(columnIndex, x);
}
public void updateDouble(final String columnLabel, final double x) throws SQLException {
cachedRowSet.updateDouble(columnLabel, x);
}
public void updateFloat(final int columnIndex, final float x) throws SQLException {
cachedRowSet.updateFloat(columnIndex, x);
}
public void updateFloat(final String columnLabel, final float x) throws SQLException {
cachedRowSet.updateFloat(columnLabel, x);
}
public void updateInt(final int columnIndex, final int x) throws SQLException {
cachedRowSet.updateInt(columnIndex, x);
}
public void updateInt(final String columnLabel, final int x) throws SQLException {
cachedRowSet.updateInt(columnLabel, x);
}
public void updateLong(final int columnIndex, final long x) throws SQLException {
cachedRowSet.updateLong(columnIndex, x);
}
public void updateLong(final String columnLabel, final long x) throws SQLException {
cachedRowSet.updateLong(columnLabel, x);
}
public void updateNCharacterStream(final int columnIndex, final Reader x, final long length) throws SQLException {
cachedRowSet.updateNCharacterStream(columnIndex, x, length);
}
public void updateNCharacterStream(final int columnIndex, final Reader x) throws SQLException {
cachedRowSet.updateNCharacterStream(columnIndex, x);
}
public void updateNCharacterStream(final String columnLabel, final Reader reader, final long length) throws SQLException {
cachedRowSet.updateNCharacterStream(columnLabel, reader, length);
}
public void updateNCharacterStream(final String columnLabel, final Reader reader) throws SQLException {
cachedRowSet.updateNCharacterStream(columnLabel, reader);
}
public void updateNClob(final int columnIndex, final NClob nClob) throws SQLException {
cachedRowSet.updateNClob(columnIndex, nClob);
}
public void updateNClob(final int columnIndex, final Reader reader, final long length) throws SQLException {
cachedRowSet.updateNClob(columnIndex, reader, length);
}
public void updateNClob(final int columnIndex, final Reader reader) throws SQLException {
cachedRowSet.updateNClob(columnIndex, reader);
}
public void updateNClob(final String columnLabel, final NClob nClob) throws SQLException {
cachedRowSet.updateNClob(columnLabel, nClob);
}
public void updateNClob(final String columnLabel, final Reader reader, final long length) throws SQLException {
cachedRowSet.updateNClob(columnLabel, reader, length);
}
public void updateNClob(final String columnLabel, final Reader reader) throws SQLException {
cachedRowSet.updateNClob(columnLabel, reader);
}
public void updateNString(final int columnIndex, final String nString) throws SQLException {
cachedRowSet.updateNString(columnIndex, nString);
}
public void updateNString(final String columnLabel, final String nString) throws SQLException {
cachedRowSet.updateNString(columnLabel, nString);
}
public void updateNull(final int columnIndex) throws SQLException {
cachedRowSet.updateNull(columnIndex);
}
public void updateNull(final String columnLabel) throws SQLException {
cachedRowSet.updateNull(columnLabel);
}
public void updateObject(final int columnIndex, final Object x, final int scaleOrLength) throws SQLException {
cachedRowSet.updateObject(columnIndex, x, scaleOrLength);
}
public void updateObject(final int columnIndex, final Object x) throws SQLException {
cachedRowSet.updateObject(columnIndex, x);
}
public void updateObject(final String columnLabel, final Object x, final int scaleOrLength) throws SQLException {
cachedRowSet.updateObject(columnLabel, x, scaleOrLength);
}
public void updateObject(final String columnLabel, final Object x) throws SQLException {
cachedRowSet.updateObject(columnLabel, x);
}
public void updateRef(final int columnIndex, final Ref x) throws SQLException {
cachedRowSet.updateRef(columnIndex, x);
}
public void updateRef(final String columnLabel, final Ref x) throws SQLException {
cachedRowSet.updateRef(columnLabel, x);
}
public void updateRow() throws SQLException {
cachedRowSet.updateRow();
}
public void updateRowId(final int columnIndex, final RowId x) throws SQLException {
cachedRowSet.updateRowId(columnIndex, x);
}
public void updateRowId(final String columnLabel, final RowId x) throws SQLException {
cachedRowSet.updateRowId(columnLabel, x);
}
public void updateShort(final int columnIndex, final short x) throws SQLException {
cachedRowSet.updateShort(columnIndex, x);
}
public void updateShort(final String columnLabel, final short x) throws SQLException {
cachedRowSet.updateShort(columnLabel, x);
}
public void updateSQLXML(final int columnIndex, final SQLXML xmlObject) throws SQLException {
cachedRowSet.updateSQLXML(columnIndex, xmlObject);
}
public void updateSQLXML(final String columnLabel, final SQLXML xmlObject) throws SQLException {
cachedRowSet.updateSQLXML(columnLabel, xmlObject);
}
public void updateString(final int columnIndex, final String x) throws SQLException {
cachedRowSet.updateString(columnIndex, x);
}
public void updateString(final String columnLabel, final String x) throws SQLException {
cachedRowSet.updateString(columnLabel, x);
}
public void updateTime(final int columnIndex, final Time x) throws SQLException {
cachedRowSet.updateTime(columnIndex, x);
}
public void updateTime(final String columnLabel, final Time x) throws SQLException {
cachedRowSet.updateTime(columnLabel, x);
}
public void updateTimestamp(final int columnIndex, final Timestamp x) throws SQLException {
cachedRowSet.updateTimestamp(columnIndex, x);
}
public void updateTimestamp(final String columnLabel, final Timestamp x) throws SQLException {
cachedRowSet.updateTimestamp(columnLabel, x);
}
public boolean wasNull() throws SQLException {
return cachedRowSet.wasNull();
}
}
|
package com.example.bmicalculator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
//Deklarasi variabel penampung
EditText edtWeight, edtHeight;
TextView ttvResultNumber, ttvResultSentence;
private static final String STATE_RESULT = "state_result";
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(STATE_RESULT, ttvResultNumber.getText().toString());
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Sambungkan widget dari XML ke JAVA
//ttv untuk JAV
edtWeight = findViewById(R.id.etWeight);
edtHeight = findViewById(R.id.etHeight);
ttvResultNumber = findViewById(R.id.tvResultNumber);
ttvResultSentence = findViewById(R.id.tvResultSentence);
if (savedInstanceState != null) {
String result = savedInstanceState.getString(STATE_RESULT);
ttvResultNumber.setText(result);
}
}
public void calculateBMI(View view) {
//Dapatkan input user di etHeight
String sHeight = edtHeight.getText().toString();
//Menghandel error jika belom di isi sama sekali
if (sHeight.length()==0){
sHeight = "0";
}
String sWeight = edtWeight.getText().toString();
if (sWeight.length()==0){
sWeight = "0";
}
//Konersi inputan user dari string menjadi double
double dHeight = (Double.parseDouble(sHeight))/100; //m
double dWeight = Double.parseDouble(sWeight); // Kg
double dBMI = dWeight /(dHeight*dHeight); //Kg/m2 ideal 18.5-25
//Membulatkan nilai yg berkoma dengan 2 angka di belakang koma
// misal angka 23,769234
dBMI = dBMI*100; //2376,9234
dBMI = Math.round(dBMI); //2376
dBMI = dBMI/100; //23,76
//Munculin Di result
ttvResultNumber.setText(""+dBMI);
if (dBMI>= 18.5 && dBMI <=25 ){
ttvResultSentence.setText("BMI anda ideal");
}
else if(dBMI > 25 ){
ttvResultSentence.setText("BMI lebih dari ideal");
}
else {
ttvResultSentence.setText("BMI Kurang dari ideal");
}
Toast.makeText(this, "" + dBMI,
Toast.LENGTH_SHORT).show();
}
}
|
/*
* 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 loc.error;
/**
*
* @author hi
*/
public class ProductError {
private String productID, name, image;
private String price;
private String quantity;
private String description;
private String createDate;
private String expireDate;
public ProductError() {
}
public ProductError(String productID, String name, String image, String price, String quantity, String description, String createDate, String expireDate) {
this.productID = productID;
this.name = name;
this.image = image;
this.price = price;
this.quantity = quantity;
this.description = description;
this.createDate = createDate;
this.expireDate = expireDate;
}
public String getProductID() {
return productID;
}
public void setProductID(String productID) {
this.productID = productID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getCreateDate() {
return createDate;
}
public void setCreateDate(String createDate) {
this.createDate = createDate;
}
public String getExpireDate() {
return expireDate;
}
public void setExpireDate(String expireDate) {
this.expireDate = expireDate;
}
}
|
package com.bluemingo.bluemingo.domain;
public class AdvDetailVO {
/**
* Advertise(광고) Data
*/
private Integer adv_key;
private String adv_title;
private String adv_message;
private String adv_ticker;
private Long adv_time; //광고(거래) 시작일
private String adv_image;
/**
* Trade(거래) 관련 Data
* 시작일/마감일, 현재수량/목표수량, 광고상태
*/
private Integer trade_key;
private Integer trade_status; //광고(거래) 상태값, 숫자 값에 따라 문자 형태로 변경 시켜줘야함
private Integer trade_rescount; //현재수량
/**
* Product(묶음) Data
*/
private Integer product_key;
private String product_id;
private Integer product_direct_price;
private Integer product_sale_price;
private Integer product_naver_price;
private Integer product_max_count; //최대 목표 수량
private Integer product_max_extra; //실제 목표 수량
private Integer product_min; //최대 구매 가능 수량(세트)
private Long product_period; //공동구매 예약 마감일(광고(거래) 마감일)
private Integer deliver_company;
private Integer deliver_price;
/**
* ref_list (product-item) 묶음-제품 리스트
*/
private String item_id; //제품구별값
private Integer option_value; //제품 구매가능 수량
/**
* Item(제품) Data
*/
private Integer item_key; //제품구별값
private String item_category_top;
private String item_category_mid;
private String item_category_bot;
private String item_name;
private Integer item_direct_price;
private Integer item_sale_price;
private Integer item_naver_price;
private String item_inform;
private String item_detail_inform;
private String item_image;
private String item_detail_image;
/**
* ref_list (item-option) 제품-옵션 리스트
*/
/**
* Company(회사) Data
*/
private Integer company_key;
private String company_name; //상호
private String company_president; //대표자
private String company_address; //주소
private String company_phone; //사업장 번호
private String company_prephone; //대표자 번호
private String company_serial; //사업자 번호
private String company_homepage;
private String company_detail; //사업체 간단 설명
private Integer company_type; //type값에 따라 문자 형태로 변경 시켜 주어야 한다.
}
|
package com.flutterwave.raveandroid.rave_presentation.card;
import com.flutterwave.raveandroid.rave_java_commons.Meta;
import com.flutterwave.raveandroid.rave_java_commons.Payload;
import com.flutterwave.raveandroid.rave_java_commons.SubAccount;
import com.flutterwave.raveandroid.rave_presentation.DaggerTestRaveComponent;
import com.flutterwave.raveandroid.rave_presentation.TestNetworkModule;
import com.flutterwave.raveandroid.rave_presentation.TestRaveComponent;
import com.flutterwave.raveandroid.rave_presentation.TestUtilsModule;
import com.flutterwave.raveandroid.rave_presentation.data.AddressDetails;
import com.flutterwave.raveandroid.rave_presentation.data.validators.TransactionStatusChecker;
import com.flutterwave.raveandroid.rave_remote.Callbacks;
import com.flutterwave.raveandroid.rave_remote.FeeCheckRequestBody;
import com.flutterwave.raveandroid.rave_remote.RemoteRepository;
import com.flutterwave.raveandroid.rave_remote.ResultCallback;
import com.flutterwave.raveandroid.rave_remote.requests.ChargeRequestBody;
import com.flutterwave.raveandroid.rave_remote.requests.RequeryRequestBody;
import com.flutterwave.raveandroid.rave_remote.requests.ValidateChargeBody;
import com.flutterwave.raveandroid.rave_remote.responses.ChargeResponse;
import com.flutterwave.raveandroid.rave_remote.responses.FeeCheckResponse;
import com.flutterwave.raveandroid.rave_remote.responses.RequeryResponse;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.inject.Inject;
import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.ACCESS_OTP;
import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.AVS_VBVSECURECODE;
import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.GTB_OTP;
import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.NOAUTH_INTERNATIONAL;
import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.PIN;
import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.VBV;
import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.enterOTP;
import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.noResponse;
import static com.flutterwave.raveandroid.rave_java_commons.RaveConstants.unknownAuthmsg;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
public class CardPaymentHandlerTest {
@Mock
CardContract.CardInteractor interactor;
@Inject
RemoteRepository networkRequest;
@Inject
TransactionStatusChecker transactionStatusChecker;
@Mock
RequeryRequestBody requeryRequestBody;
private CardPaymentHandler paymentHandler;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
paymentHandler = new CardPaymentHandler(interactor);
TestRaveComponent component = DaggerTestRaveComponent.builder()
.testNetworkModule(new TestNetworkModule())
.testUtilsModule(new TestUtilsModule())
.build();
component.inject(this);
component.inject(paymentHandler);
}
@Test
public void fetchFee_onError_showFetchFeeFailedCalled() {
paymentHandler.fetchFee(generatePayload());
ArgumentCaptor<ResultCallback> captor = ArgumentCaptor.forClass(ResultCallback.class);
verify(networkRequest).getFee(any(FeeCheckRequestBody.class), captor.capture());
captor.getAllValues().get(0).onError(generateRandomString());
verify(interactor).onFetchFeeError(anyString());
}
@Test
public void fetchFee_onSuccess_displayFeeCalled() {
paymentHandler.fetchFee(generatePayload());
ArgumentCaptor<ResultCallback> captor = ArgumentCaptor.forClass(ResultCallback.class);
verify(networkRequest).getFee(any(FeeCheckRequestBody.class), captor.capture());
captor.getAllValues().get(0).onSuccess(generateFeeCheckResponse());
verify(interactor).onTransactionFeeFetched(anyString(), any(Payload.class), anyString());
}
@Test
public void chargeCard_onSuccessWithPIN_onPinAuthModelSuggestedCalled() {
//arrange
ChargeResponse chargeResponse = generateValidChargeResponseWithAuth(PIN);
Payload payload = generatePayload();
//act
paymentHandler.chargeCard(payload, generateRandomString());
verify(interactor).showProgressIndicator(true);
ArgumentCaptor<ResultCallback> captor = ArgumentCaptor.forClass(ResultCallback.class);
verify(networkRequest).charge(any(ChargeRequestBody.class), captor.capture());
captor.getAllValues().get(0).onSuccess(chargeResponse);
//assert
verify(interactor).showProgressIndicator(false);
verify(interactor).collectCardPin(payload);
}
@Test
public void chargeCard_onSuccessWithAVS_VBVSECURECODE_onAVS_VBVSECURECODEModelSuggestedCalled() {
//arrange
ChargeResponse chargeResponse = generateValidChargeResponseWithAuth(AVS_VBVSECURECODE);
Payload payload = generatePayload();
//act
paymentHandler.chargeCard(payload, generateRandomString());
verify(interactor).showProgressIndicator(true);
ArgumentCaptor<ResultCallback> captor = ArgumentCaptor.forClass(ResultCallback.class);
verify(networkRequest).charge(any(ChargeRequestBody.class), captor.capture());
captor.getAllValues().get(0).onSuccess(chargeResponse);
//assert
verify(interactor).showProgressIndicator(false);
verify(interactor).collectCardAddressDetails(eq(payload), anyString());
}
@Test
public void chargeCard_onSuccess_onNOAUTH_INTERNATIONALSuggested_onNoAuthInternationalSuggestedCalled() {
//arrange
ChargeResponse chargeResponse = generateValidChargeResponseWithAuth(NOAUTH_INTERNATIONAL);
Payload payload = generatePayload();
paymentHandler.chargeCard(payload, generateRandomString());
verify(interactor).showProgressIndicator(true);
ArgumentCaptor<ResultCallback> captor = ArgumentCaptor.forClass(ResultCallback.class);
verify(networkRequest).charge(any(ChargeRequestBody.class), captor.capture());
captor.getAllValues().get(0).onSuccess(chargeResponse);
verify(interactor).showProgressIndicator(false);
verify(interactor).collectCardAddressDetails(payload, NOAUTH_INTERNATIONAL);
}
@Test
public void chargeCard_onSuccess_unknownSuggestedAuth_onPaymentErrorCalled() {
//arrange
ChargeResponse chargeResponse = generateValidChargeResponseWithAuth(generateRandomString());
Payload payload = generatePayload();
//act
paymentHandler.chargeCard(payload, generateRandomString());
verify(interactor).showProgressIndicator(true);
ArgumentCaptor<ResultCallback> captor = ArgumentCaptor.forClass(ResultCallback.class);
verify(networkRequest).charge(any(ChargeRequestBody.class), captor.capture());
captor.getAllValues().get(0).onSuccess(chargeResponse);
//assert
verify(interactor).showProgressIndicator(false);
verify(interactor).onPaymentError(unknownAuthmsg);
}
@Test
public void chargeCard_onSuccess_nullSuggestedAuth_VBVAuthModelUsed_onVBVAuthModelUsedCalledWithCorrectParams() {
//arrange
ChargeResponse chargeResponse = generateValidChargeResponseWithAuth(null);
chargeResponse.getData().setAuthModelUsed(VBV);
String authUrlCrude = chargeResponse.getData().getAuthurl();
String flwRef = chargeResponse.getData().getFlwRef();
//act
paymentHandler.chargeCard(generatePayload(), generateRandomString());
verify(interactor).showProgressIndicator(true);
ArgumentCaptor<ResultCallback> captor = ArgumentCaptor.forClass(ResultCallback.class);
verify(networkRequest).charge(any(ChargeRequestBody.class), captor.capture());
captor.getAllValues().get(0).onSuccess(chargeResponse);
//assert
verify(interactor).showProgressIndicator(false);
verify(interactor).showWebPage(authUrlCrude, flwRef);
}
@Test
public void chargeCard_onSuccess_nullSuggestedAuth_authModelUsed_enterOTP_showOTPLayoutCalledWithCorrectParams() {
//arrange
ChargeResponse chargeResponse = generateValidChargeResponseWithAuth(null);
Payload payload = generatePayload();
chargeResponse.getData().setAuthModelUsed(ACCESS_OTP);
chargeResponse.getData().setSuggested_auth(null);
chargeResponse.getData().setChargeResponseMessage(null);
String flwRef = chargeResponse.getData().getFlwRef();
//act
paymentHandler.chargeCard(payload, generateRandomString());
verify(interactor).showProgressIndicator(true);
ArgumentCaptor<ResultCallback> captor = ArgumentCaptor.forClass(ResultCallback.class);
verify(networkRequest).charge(any(ChargeRequestBody.class), captor.capture());
captor.getAllValues().get(0).onSuccess(chargeResponse);
//assert
verify(interactor).showProgressIndicator(false);
verify(interactor).collectOtp(flwRef, enterOTP);
}
@Test
public void chargeCard_onSuccess_nullSuggestedAuth_authModelUsedAccess_showOTPLayoutCalledWithCorrectParams() {
//arrange
ChargeResponse chargeResponse = generateValidChargeResponseWithAuth(null);
Payload payload = generatePayload();
chargeResponse.getData().setAuthModelUsed(ACCESS_OTP);
String flwRef = chargeResponse.getData().getFlwRef();
chargeResponse.getData().setChargeResponseMessage(generateRandomString());
String chargeResponseMessage = chargeResponse.getData().getChargeResponseMessage();
//act
paymentHandler.chargeCard(payload, generateRandomString());
verify(interactor).showProgressIndicator(true);
ArgumentCaptor<ResultCallback> captor = ArgumentCaptor.forClass(ResultCallback.class);
verify(networkRequest).charge(any(ChargeRequestBody.class), captor.capture());
captor.getAllValues().get(0).onSuccess(chargeResponse);
//assert
verify(interactor).showProgressIndicator(false);
verify(interactor).collectOtp(flwRef, chargeResponseMessage);
}
@Test
public void chargeCard_onSuccess_nullSuggestedAuth_authModelUsedGtb_showOTPLayoutCalledWithCorrectParams() {
//arrange
ChargeResponse chargeResponse = generateValidChargeResponseWithAuth(null);
Payload payload = generatePayload();
chargeResponse.getData().setAuthModelUsed(GTB_OTP);
String flwRef = chargeResponse.getData().getFlwRef();
chargeResponse.getData().setChargeResponseMessage(generateRandomString());
String chargeResponseMessage = chargeResponse.getData().getChargeResponseMessage();
//act
paymentHandler.chargeCard(payload, generateRandomString());
verify(interactor).showProgressIndicator(true);
ArgumentCaptor<ResultCallback> captor = ArgumentCaptor.forClass(ResultCallback.class);
verify(networkRequest).charge(any(ChargeRequestBody.class), captor.capture());
captor.getAllValues().get(0).onSuccess(chargeResponse);
//assert
verify(interactor).showProgressIndicator(false);
verify(interactor).collectOtp(flwRef, chargeResponseMessage);
}
@Test
public void chargeCard_onSuccess_nullData_onPaymentErrorCalledWithCorrectParams() {
//arrange
ChargeResponse chargeResponse = generateValidChargeResponseWithAuth(null);
Payload payload = generatePayload();
chargeResponse.setData(null);
//act
paymentHandler.chargeCard(payload, generateRandomString());
verify(interactor).showProgressIndicator(true);
ArgumentCaptor<ResultCallback> captor = ArgumentCaptor.forClass(ResultCallback.class);
verify(networkRequest).charge(any(ChargeRequestBody.class), captor.capture());
captor.getAllValues().get(0).onSuccess(chargeResponse);
//assert
verify(interactor).showProgressIndicator(false);
verify(interactor).onPaymentError(noResponse);
}
@Test
public void chargeCard_onSuccess_nullSuggestedAuth_authModelUsed_otp_showOTPLayoutCalledWithCorrectParams() {
//arrange
ChargeResponse chargeResponse = generateValidChargeResponseWithAuth(null);
Payload payload = generatePayload();
chargeResponse.getData().setAuthModelUsed("otp");
String flwRef = chargeResponse.getData().getFlwRef();
chargeResponse.getData().setChargeResponseMessage(generateRandomString());
String chargeResponseMessage = chargeResponse.getData().getChargeResponseMessage();
//act
paymentHandler.chargeCard(payload, generateRandomString());
verify(interactor).showProgressIndicator(true);
ArgumentCaptor<ResultCallback> captor = ArgumentCaptor.forClass(ResultCallback.class);
verify(networkRequest).charge(any(ChargeRequestBody.class), captor.capture());
captor.getAllValues().get(0).onSuccess(chargeResponse);
//assert
verify(interactor).showProgressIndicator(false);
verify(interactor).collectOtp(flwRef, chargeResponseMessage);
}
@Test
public void chargeCard_onSuccess_nullSuggestedAuth_authModelUsedGTB_chargeResponseMessageNotNull_showOTPLayoutCalledWithCorrectParams() {
//arrange
ChargeResponse chargeResponse = generateValidChargeResponseWithAuth(null);
Payload payload = generatePayload();
chargeResponse.getData().setAuthModelUsed(GTB_OTP);
String flwRef = chargeResponse.getData().getFlwRef();
//act
paymentHandler.chargeCard(payload, generateRandomString());
verify(interactor).showProgressIndicator(true);
ArgumentCaptor<ResultCallback> captor = ArgumentCaptor.forClass(ResultCallback.class);
verify(networkRequest).charge(any(ChargeRequestBody.class), captor.capture());
captor.getAllValues().get(0).onSuccess(chargeResponse);
//assert
verify(interactor).showProgressIndicator(false);
verify(interactor).collectOtp(flwRef, enterOTP);
}
@Test
public void chargeCard_onError_onPaymentErrorCalled() {
paymentHandler.chargeCard(generatePayload(), generateRandomString());
ArgumentCaptor<ResultCallback> captor = ArgumentCaptor.forClass(ResultCallback.class);
verify(networkRequest).charge(any(ChargeRequestBody.class), captor.capture());
captor.getAllValues().get(0).onError(generateRandomString());
verify(interactor).onPaymentError(anyString());
}
@Test
public void validateCardCharge_onSuccess_isNotSuccess_onPaymentErrorCalled() {
ChargeResponse chargeResponse = generateValidChargeResponse();
chargeResponse.setStatus(generateRandomString());
String flwref = generateRandomString();
String otp = generateRandomString();
String pbfkey = generateRandomString();
String message = chargeResponse.getMessage();
String responseAsJson = generateRandomString();
paymentHandler.validateCardCharge(flwref, pbfkey, otp);
ArgumentCaptor<ResultCallback> captor = ArgumentCaptor.forClass(ResultCallback.class);
verify(networkRequest).validateCardCharge(any(ValidateChargeBody.class), captor.capture());
captor.getAllValues().get(0).onSuccess(chargeResponse);
verify(interactor).onPaymentError(message);
}
@Test
public void validateCardCharge_onError_isNotSuccess_onPaymentErrorCalled() {
ChargeResponse chargeResponse = generateValidChargeResponse();
chargeResponse.setStatus(generateRandomString());
String flwref = generateRandomString();
String otp = generateRandomString();
String pbfkey = generateRandomString();
String message = chargeResponse.getMessage();
String responseAsJson = generateRandomString();
paymentHandler.validateCardCharge(flwref, pbfkey, otp);
ArgumentCaptor<ResultCallback> captor = ArgumentCaptor.forClass(ResultCallback.class);
verify(networkRequest).validateCardCharge(any(ValidateChargeBody.class), captor.capture());
captor.getAllValues().get(0).onError(message);
verify(interactor).onPaymentError(message);
}
@Test
public void verifyRequeryResponse_wasTxSuccessful_onPaymentSuccessfulCalled() {
RequeryResponse requeryResponse = generateRequerySuccessful();
String responseAsJsonString = generateRandomString();
String flwRef = generateRandomString();
when(transactionStatusChecker.getTransactionStatus(any(String.class)))
.thenReturn(true);
paymentHandler.verifyRequeryResponse(requeryResponse, responseAsJsonString, flwRef);
verify(interactor).onPaymentSuccessful(requeryResponse.getStatus(), flwRef, responseAsJsonString);
}
@Test
public void verifyRequeryResponse_notWasTxSuccessful_onPaymentFailedCalled() {
RequeryResponse requeryResponse = generateRequerySuccessful();
String responseAsJsonString = generateRandomString();
String flwRef = generateRandomString();
when(transactionStatusChecker.getTransactionStatus(any(String.class)))
.thenReturn(false);
paymentHandler.verifyRequeryResponse(requeryResponse, responseAsJsonString, flwRef);
verify(interactor).onPaymentFailed(requeryResponse.getStatus(), responseAsJsonString);
}
@Test
public void chargeCardWithSuggestedAuthModel_onError_onPaymentErrorCalled() {
String message = generateRandomString();
paymentHandler.chargeCardWithPinAuthModel(generatePayload(), generateRandomString(), generateRandomString());
ArgumentCaptor<ResultCallback> captor = ArgumentCaptor.forClass(ResultCallback.class);
verify(networkRequest).charge(any(ChargeRequestBody.class), captor.capture());
captor.getAllValues().get(0).onError(message);
verify(interactor).onPaymentError(message);
}
@Test
public void chargeCardWithSuggestedAuthModel_onSuccessWithPIN_showOTPLayoutCalled() {
paymentHandler.chargeCardWithPinAuthModel(generatePayload(), generateRandomString(), generateRandomString());
ArgumentCaptor<ResultCallback> captor = ArgumentCaptor.forClass(ResultCallback.class);
verify(networkRequest).charge(any(ChargeRequestBody.class), captor.capture());
captor.getAllValues().get(0).onSuccess(generateValidChargeResponseWithAuthModelUsed(PIN));
verify(interactor).collectOtp(anyString(), anyString());
}
@Test
public void chargeCardWithSuggestedAuthModel_onSuccessWithAVS_VBVSECURECODE_onAVSVBVSecureCodeModelUsedCalled() {
paymentHandler.chargeCardWithPinAuthModel(generatePayload(), generateRandomString(), generateRandomString());
ArgumentCaptor<ResultCallback> captor = ArgumentCaptor.forClass(ResultCallback.class);
verify(networkRequest).charge(any(ChargeRequestBody.class), captor.capture());
captor.getAllValues().get(0).onSuccess(generateValidChargeResponseWithAuthModelUsed(AVS_VBVSECURECODE));
verify(interactor).showWebPage(anyString(), anyString());
}
@Test
public void chargeCardWithSuggestedAuthModel_onSuccess_unknownResCodemsgReturned_onPaymentErrorCalled() {
paymentHandler.chargeCardWithPinAuthModel(generatePayload(), generateRandomString(), generateRandomString());
ArgumentCaptor<ResultCallback> captor = ArgumentCaptor.forClass(ResultCallback.class);
verify(networkRequest).charge(any(ChargeRequestBody.class), captor.capture());
captor.getAllValues().get(0).onSuccess(generateRandomChargeResponse());
verify(interactor).onPaymentError(anyString());
}
@Test
public void chargeCardWithSuggestedAuthModel_onSuccess_unknownAuthmsgReturned_onPaymentErrorCalled() {
paymentHandler.chargeCardWithPinAuthModel(generatePayload(), generateRandomString(), generateRandomString());
ArgumentCaptor<ResultCallback> captor = ArgumentCaptor.forClass(ResultCallback.class);
verify(networkRequest).charge(any(ChargeRequestBody.class), captor.capture());
captor.getAllValues().get(0).onSuccess(generateValidChargeResponseWithAuth("unknown Auth"));
verify(interactor).onPaymentError(unknownAuthmsg);
}
@Test
public void chargeCardWithSuggestedAuthModel_onSuccess_invalidChargeCodeReturned_onPaymentErrorCalled() {
paymentHandler.chargeCardWithPinAuthModel(generatePayload(), generateRandomString(), generateRandomString());
ArgumentCaptor<ResultCallback> captor = ArgumentCaptor.forClass(ResultCallback.class);
verify(networkRequest).charge(any(ChargeRequestBody.class), captor.capture());
captor.getAllValues().get(0).onSuccess(generateNullChargeResponse());
verify(interactor).onPaymentError(anyString());
}
@Test
public void requeryTx_onError_onPaymentFailedCalledWithCorrectParams() {
//arrange
String message = generateRandomString();
String responseAsString = generateRandomString();
//act
paymentHandler.requeryTx(generateRandomString(), generateRandomString());
verify(interactor).showProgressIndicator(true);
ArgumentCaptor<Callbacks.OnRequeryRequestComplete> captor = ArgumentCaptor.forClass(Callbacks.OnRequeryRequestComplete.class);
verify(networkRequest).requeryTx(any(RequeryRequestBody.class), captor.capture());
captor.getAllValues().get(0).onError(message, responseAsString);
//assert
verify(interactor).onPaymentFailed(message, responseAsString);
}
private FeeCheckResponse generateFeeCheckResponse() {
FeeCheckResponse feeCheckResponse = new FeeCheckResponse();
FeeCheckResponse.Data feeCheckResponseData = new FeeCheckResponse.Data();
feeCheckResponseData.setCharge_amount(generateRandomString());
feeCheckResponse.setData(feeCheckResponseData);
feeCheckResponse.getData().setFee(generateRandomString());
return feeCheckResponse;
}
private ChargeResponse generateRandomChargeResponse() {
ChargeResponse chargeResponse = new ChargeResponse();
ChargeResponse.Data chargeResponseData = new ChargeResponse.Data();
chargeResponseData.setChargeResponseCode(generateRandomString());
chargeResponse.setData(chargeResponseData);
return chargeResponse;
}
private ChargeResponse generateNullChargeResponse() {
ChargeResponse chargeResponse = new ChargeResponse();
chargeResponse.setData(null);
return chargeResponse;
}
private ChargeResponse generateValidChargeResponse() {
ChargeResponse chargeResponse = generateRandomChargeResponse();
chargeResponse.getData().setChargeResponseCode("00");
return chargeResponse;
}
private RequeryResponse generateRequerySuccessful() {
return new RequeryResponse();
}
private ChargeResponse generateValidChargeResponseWithAuth(String auth) {
ChargeResponse chargeResponse = generateRandomChargeResponse();
chargeResponse.getData().setAuthModelUsed(auth);
chargeResponse.getData().setSuggested_auth(auth);
chargeResponse.getData().setAuthurl(generateRandomString());
chargeResponse.getData().setFlwRef(generateRandomString());
chargeResponse.getData().setChargeResponseCode("02");
return chargeResponse;
}
private ChargeResponse generateValidChargeResponseWithAuthModelUsed(String auth) {
ChargeResponse chargeResponse = generateRandomChargeResponse();
chargeResponse.getData().setAuthModelUsed(auth);
chargeResponse.getData().setAuthurl(generateRandomString());
chargeResponse.getData().setFlwRef(generateRandomString());
chargeResponse.getData().setChargeResponseCode("02");
return chargeResponse;
}
private Payload generatePayload() {
List<Meta> metas = new ArrayList<>();
List<SubAccount> subAccounts = new ArrayList<>();
return new Payload(generateRandomString(), metas, subAccounts, generateRandomString(), generateRandomString(), generateRandomString(), generateRandomString(), generateRandomString(), generateRandomString(), generateRandomString(), generateRandomString(), generateRandomString(), generateRandomString(), generateRandomString());
}
private String generateRandomString() {
return UUID.randomUUID().toString();
}
private AddressDetails generateRandomAddressDetails() {
return new AddressDetails(
"",
"",
"",
"",
""
);
}
} |
package com.guille.cpm.igu;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
public class CustomComboBoxModel<E extends Comparable<E>> extends DefaultComboBoxModel<E> {
/**
*
*/
private static final long serialVersionUID = 1L;
public void sortFrom(int index) {
if(index < 0)
throw new NullPointerException(index + "<" + 0);
else if(index > this.getSize())
throw new IndexOutOfBoundsException(index + ">" + this.getSize());
List<E> aux = new ArrayList<>();
List<E> notSort = new ArrayList<>();
for(int i = 0; i < index; i++) {
notSort.add(this.getElementAt(i));
}
for(int i = index; i < this.getSize(); i++) {
aux.add(this.getElementAt(i));
}
this.removeAllElements();
Collections.sort(aux);
for(E element : notSort) {
this.addElement(element);
}
for(E element : aux) {
this.addElement(element);
}
}
}
|
package com.sinata.rwxchina.component_home.entity;
/**
* @author HRR
* @datetime 2017/11/27
* @describe 首页精品特卖实体类
* @modifyRecord
*/
public class BoutiqueEntity {
/**
* goods_id : 1
* shopid : 2
* boutique_tilte : 精品特卖1
* default_image : /Uploads/_old/advs/33e15f207e19a04ae7f92aabd51267ef.png
*/
private String goods_id;
private String shopid;
private String boutique_tilte;
private String default_image;
public String getGoods_id() {
return goods_id;
}
public void setGoods_id(String goods_id) {
this.goods_id = goods_id;
}
public String getShopid() {
return shopid;
}
public void setShopid(String shopid) {
this.shopid = shopid;
}
public String getBoutique_tilte() {
return boutique_tilte;
}
public void setBoutique_tilte(String boutique_tilte) {
this.boutique_tilte = boutique_tilte;
}
public String getDefault_image() {
return default_image;
}
public void setDefault_image(String default_image) {
this.default_image = default_image;
}
@Override
public String toString() {
return "BoutiqueEntity{" +
"goods_id='" + goods_id + '\'' +
", shopid='" + shopid + '\'' +
", boutique_tilte='" + boutique_tilte + '\'' +
", default_image='" + default_image + '\'' +
'}';
}
}
|
package de.adesso.gitstalker.core.requests;
import de.adesso.gitstalker.core.config.Config;
import de.adesso.gitstalker.core.enums.RequestStatus;
import de.adesso.gitstalker.core.exceptions.InvalidGithubAPITokenException;
import de.adesso.gitstalker.core.exceptions.InvalidRequestContentException;
import de.adesso.gitstalker.core.objects.Query;
import de.adesso.gitstalker.core.objects.Response;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;
import de.adesso.gitstalker.core.resources.createdReposByMembers.ResponseCreatedReposByMembers;
import de.adesso.gitstalker.core.resources.externalRepo_Resources.ResponseExternalRepository;
import de.adesso.gitstalker.core.resources.memberID_Resources.ResponseMemberID;
import de.adesso.gitstalker.core.resources.memberPR_Resources.ResponseMemberPR;
import de.adesso.gitstalker.core.resources.member_Resources.ResponseMember;
import de.adesso.gitstalker.core.resources.organisation_Resources.ResponseOrganization;
import de.adesso.gitstalker.core.resources.organization_validation.ResponseOrganizationValidation;
import de.adesso.gitstalker.core.resources.repository_Resources.ResponseRepository;
import de.adesso.gitstalker.core.resources.team_Resources.ResponseTeam;
public abstract class Request {
/**
* Starting of the request to the GraphQL GitHub API. Setting up the fundamental structure of the request and processing the request.
*
* @param requestQuery Query containing the content for the request.
* @return Requested query is returned with the new status and response/error.
*/
public Query crawlData(Query requestQuery) {
requestQuery.setQueryStatus(RequestStatus.STARTED);
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Bearer " + Config.API_TOKEN);
HttpEntity entity = new HttpEntity(requestQuery, headers);
RestTemplate restTemplate = new RestTemplate();
try {
processRequest(requestQuery, restTemplate, entity);
} catch (HttpClientErrorException e) {
requestQuery.setQueryStatus(RequestStatus.ERROR_RECEIVED);
if (e.getMessage().equals("401 Unauthorized")) {
requestQuery.setQueryError(new InvalidGithubAPITokenException("Invalid Github API Token! Maybe token wasn't added?", e));
}
} catch (NullPointerException e) {
requestQuery.setQueryStatus(RequestStatus.ERROR_RECEIVED);
if (e.getMessage().equals("Invalid request content: Returned response null!")) {
requestQuery.setQueryError(new InvalidRequestContentException("The content of the request is invalid! The returned data is null."));
}
} catch (Exception e) {
requestQuery.setQueryStatus(RequestStatus.ERROR_RECEIVED);
requestQuery.setQueryError(e);
}
return requestQuery;
}
/**
* Processing the request according to the request type. Differentiation needed because of the various response classes.
* Can throw an NullpointerException or HttpClientErrorException
*
* @param requestQuery Query used for the request
* @param restTemplate RestTemplate created for the request
* @param entity Configuration for the request
*/
private void processRequest(Query requestQuery, RestTemplate restTemplate, HttpEntity entity) throws Exception {
switch (requestQuery.getQueryRequestType()) {
case ORGANIZATION_VALIDATION:
processOrganizationValidationRequest(requestQuery, restTemplate, entity);
break;
case ORGANIZATION_DETAIL:
processOrganizationRequest(requestQuery, restTemplate, entity);
break;
case MEMBER_ID:
processMemberIDRequest(requestQuery, restTemplate, entity);
break;
case MEMBER_PR:
processMemberPRRequest(requestQuery, restTemplate, entity);
break;
case MEMBER:
processMemberRequest(requestQuery, restTemplate, entity);
break;
case REPOSITORY:
processRespositoriesDetail(requestQuery, restTemplate, entity);
break;
case TEAM:
processOrganizationTeams(requestQuery, restTemplate, entity);
break;
case EXTERNAL_REPO:
processExternalRepos(requestQuery, restTemplate, entity);
break;
case CREATED_REPOS_BY_MEMBERS:
processCreatedReposByMembers(requestQuery, restTemplate, entity);
break;
}
requestQuery.setQueryStatus(RequestStatus.VALID_ANSWER_RECEIVED);
}
/**
* Processing of the request for validating an organization's name.
* @param requestQuery
* @param restTemplate
* @param entity
*/
private void processOrganizationValidationRequest(Query requestQuery, RestTemplate restTemplate, HttpEntity entity) {
ResponseOrganizationValidation response = restTemplate.postForObject(Config.API_URL, entity, ResponseOrganizationValidation.class);
if (response.getData() != null) {
requestQuery.setQueryResponse(response);
} else throw new NullPointerException("Invalid request content: Returned response null!");
}
/**
* Processing of the request for the external repos with contribution by the members. Usage of the Response class for the external repos.
* Throws NullPointerException if response data is null because of bad request.
*
* @param requestQuery Query used for the request
* @param restTemplate RestTemplate created for the request
* @param entity Configuration for the request
*/
private void processCreatedReposByMembers(Query requestQuery, RestTemplate restTemplate, HttpEntity entity) {
ResponseCreatedReposByMembers response = restTemplate.postForObject(Config.API_URL, entity, ResponseCreatedReposByMembers.class);
if (response.getData() != null) {
requestQuery.setQueryResponse(response);
} else throw new NullPointerException("Invalid request content: Returned response null!");
}
/**
* Processing of the request for the external repos with contribution by the members. Usage of the Response class for the external repos.
* Throws NullPointerException if response data is null because of bad request.
*
* @param requestQuery Query used for the request
* @param restTemplate RestTemplate created for the request
* @param entity Configuration for the request
*/
private void processExternalRepos(Query requestQuery, RestTemplate restTemplate, HttpEntity entity) {
ResponseExternalRepository response = restTemplate.postForObject(Config.API_URL, entity, ResponseExternalRepository.class);
if (response.getData() != null) {
requestQuery.setQueryResponse(response);
} else throw new NullPointerException("Invalid request content: Returned response null!");
}
/**
* Processing of the request for the teams detail of the organization. Usage of the Response class for the teams.
* Throws NullPointerException if response data is null because of bad request.
*
* @param requestQuery Query used for the request
* @param restTemplate RestTemplate created for the request
* @param entity Configuration for the request
*/
private void processOrganizationTeams(Query requestQuery, RestTemplate restTemplate, HttpEntity entity) {
ResponseTeam response = restTemplate.postForObject(Config.API_URL, entity, ResponseTeam.class);
if (response.getData() != null) {
requestQuery.setQueryResponse(response);
} else throw new NullPointerException("Invalid request content: Returned response null!");
}
/**
* Processing of the request for the de.adesso.gitstalker.core.repositories detail of the organization. Usage of the Response class for the de.adesso.gitstalker.core.repositories.
* Throws NullPointerException if response data is null because of bad request.
*
* @param requestQuery Query used for the request
* @param restTemplate RestTemplate created for the request
* @param entity Configuration for the request
*/
private void processRespositoriesDetail(Query requestQuery, RestTemplate restTemplate, HttpEntity entity) {
ResponseRepository response = restTemplate.postForObject(Config.API_URL, entity, ResponseRepository.class);
if (response.getData() != null) {
requestQuery.setQueryResponse(response);
} else throw new NullPointerException("Invalid request content: Returned response null!");
}
/**
* Processing of the request for the organization detail. Usage of the Response class for the organization.
* Throws NullPointerException if response data is null because of bad request.
*
* @param requestQuery Query used for the request
* @param restTemplate RestTemplate created for the request
* @param entity Configuration for the request
*/
private void processOrganizationRequest(Query requestQuery, RestTemplate restTemplate, HttpEntity entity) throws Exception {
ResponseOrganization response = restTemplate.postForObject(Config.API_URL, entity, ResponseOrganization.class);
if (response.getData() != null) {
requestQuery.setQueryResponse(response);
} else throw new NullPointerException("Invalid request content: Returned response null!");
}
/**
* Processing of the request for the memberID. Usage of the Response class for the memberID.
* Throws NullPointerException if response data is null because of bad request.
*
* @param requestQuery Query used for the request
* @param restTemplate RestTemplate created for the request
* @param entity Configuration for the request
*/
private void processMemberIDRequest(Query requestQuery, RestTemplate restTemplate, HttpEntity entity) {
ResponseMemberID response = restTemplate.postForObject(Config.API_URL, entity, ResponseMemberID.class);
if (response.getData() != null) {
requestQuery.setQueryResponse(response);
} else throw new NullPointerException("Invalid request content: Returned response null!");
}
/**
* Processing of the request for the memberPRRepos. Usage of the Response class for the MemberPR.
* Throws NullPointerException if response data is null because of bad request.
*
* @param requestQuery Query used for the request
* @param restTemplate RestTemplate created for the request
* @param entity Configuration for the request
*/
private void processMemberPRRequest(Query requestQuery, RestTemplate restTemplate, HttpEntity entity) {
ResponseMemberPR response = restTemplate.postForObject(Config.API_URL, entity, ResponseMemberPR.class);
if (response.getData() != null) {
requestQuery.setQueryResponse(response);
} else throw new NullPointerException("Invalid request content: Returned response null!");
}
/**
* Processing of the request for the memberPRRepos. Usage of the Response class for the MemberPR.
* Throws NullPointerException if response data is null because of bad request.
*
* @param requestQuery Query used for the request
* @param restTemplate RestTemplate created for the request
* @param entity Configuration for the request
*/
private void processMemberRequest(Query requestQuery, RestTemplate restTemplate, HttpEntity entity) {
ResponseMember response = restTemplate.postForObject(Config.API_URL, entity, ResponseMember.class);
if (response.getData() != null) {
requestQuery.setQueryResponse(response);
} else throw new NullPointerException("Invalid request content: Returned response null!");
}
}
|
package com.espendwise.tools.gencode.hbmxml;
import org.hibernate.cfg.reveng.JDBCToHibernateTypeHelper;
public class DbBaseType2SqlType {
public DbBaseType2SqlType() {
}
public static SqlType convert(DbBaseTypeSettings dbTypeSwttings, String pDbBaseType) {
Integer jdbcType = dbTypeSwttings != null && dbTypeSwttings.getSpqcificDbBaseSqlTypes().containsKey(pDbBaseType)
? dbTypeSwttings.getSpqcificDbBaseSqlTypes().get(pDbBaseType)
: Integer.valueOf(JDBCToHibernateTypeHelper.getJDBCType(pDbBaseType));
return new SqlType(
jdbcType,
dbTypeSwttings != null ? dbTypeSwttings.getDefinitionSqlTyoes().get(jdbcType) : null,
JDBCToHibernateTypeHelper.getJDBCTypeName(jdbcType)
);
}
public static class SqlType {
private int sqlTypeCode;
private String definitonType;
private String jdbcType;
public SqlType(int sqlTypeCode, String definitonType, String jdbcType) {
this.sqlTypeCode = sqlTypeCode;
this.jdbcType = jdbcType;
this.definitonType = definitonType;
}
public int getSqlTypeCode() {
return sqlTypeCode;
}
public void setSqlTypeCode(int sqlTypeCode) {
this.sqlTypeCode = sqlTypeCode;
}
public String getDefinitonType() {
return definitonType;
}
public void setDefinitonType(String definitonType) {
this.definitonType = definitonType;
}
public String getJdbcType() {
return jdbcType;
}
public void setJdbcType(String jdbcType) {
this.jdbcType = jdbcType;
}
}
}
|
package onlinerealestateproject.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class ActionSevlet
*/
@WebServlet("/ActionSevlet")
public class ActionServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ActionServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* forward a request to other jsp
* @param target
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
protected void forward(String target, HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher dispatcher = request.getRequestDispatcher(target);
dispatcher.forward(request, response);
}
}
|
package com.bierocratie.model;
import com.bierocratie.model.security.Account;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
/**
* Created with IntelliJ IDEA.
* User: pir
* Date: 09/04/14
* Time: 22:33
* To change this template use File | Settings | File Templates.
*/
@Entity
@Table(name = "customer")
public class Customer extends Account implements Serializable {
/**
*
*/
private static final long serialVersionUID = -3271735073765712214L;
@Id
@GeneratedValue
private Long id;
@NotNull
private String name;
private String address;
private String telephone;
private boolean receiveDelivery;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ManyToMany
private Set<Order> orders = new HashSet<>();
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public Set<Order> getOrders() {
return orders;
}
public void setOrders(Set<Order> orders) {
this.orders = orders;
}
public Boolean getReceiveDelivery() {
return receiveDelivery;
}
public void setReceiveDelivery(Boolean receiveDelivery) {
this.receiveDelivery = receiveDelivery;
}
@Override
public String toString() {
return name;
}
}
|
/*
* Copyright 2008 Kjetil Valstadsve
*
* 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 vanadis.integrationtests;
import vanadis.osgi.Context;
import vanadis.osgi.Filter;
import vanadis.osgi.OSGiUtils;
import vanadis.osgi.Reference;
import java.util.concurrent.Callable;
class ReferenceLookup<T> implements Callable<Reference<T>> {
private final Context context;
private final Class<T> serviceInterface;
private final Filter filter;
private final boolean forNull;
private final boolean expectNonNull;
ReferenceLookup(Context context, Class<T> serviceInterface, Filter filter, boolean forNull) {
this.context = context;
this.serviceInterface = serviceInterface;
this.filter = filter;
this.forNull = forNull;
this.expectNonNull = !forNull;
}
@Override
public Reference<T> call() {
printWait();
Reference<T> reference = null;
try {
reference = context.getReference(serviceInterface, filter);
} catch (IllegalStateException e) {
if (OSGiUtils.bundleNoLongerValid(e) && forNull) {
printOK();
return reference;
} else {
throw e;
}
}
boolean nullRef = reference == null;
if ((nullRef && forNull) || !nullRef && expectNonNull) {
printOK();
}
return reference;
}
private static void printWait() {
System.out.print(".");
}
private static void printOK() {
System.out.println(" ok!");
}
}
|
package edu.infnet.bean;
public class Administrador extends Usuario{
private Integer id;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
//colocar o metodo salvar.
public void salvar(){
endereco = "minha casa";
}
//<h:inputText value="#{admin.endereco}">
//<h:commandButton actionListener="#{admin.salvar}"
}
|
import textio.TextIO;
/*
This program will perform 10000 experiments per possible dice total. It will record
the average number of goals it took to achieve that total.
*/
public class RollTheDice3 {
final static int EXPERIMENTS = 10000;
/*
The main method will loop all possible totals for a pair of dice. It will then
call the rollExperiment function which will return the average number of rolls.
It will then print this out in a table.
*/
public static void main (String [] args) {
int i;
double averageNumber;
double [] averageTable;
averageTable = new double [13];
System.out.println ("This program will create a table and display the average number of rolls per possible dice total for 10000 experiments.");
System.out.println ();
System.out.println ("Total On Dice Average Number of Rolls");
System.out.println ("------------- -----------------------");
for (i = 2; i < 13; i ++) {
averageNumber = rollExperiment (i);
averageTable [i] = averageNumber;
System.out.println (" " + i + " " + averageTable [i]);
}
}
/*
This method will experiment each possible total 10000 times. It will call the computeRoll
function. It will also record the average number of rolls per possible total and return that
to the main method.
*/
private static double rollExperiment (int currentPossibleTotal) {
int i;
int currentAttempts;
int totalAttempts;
double currentAverage;
totalAttempts = 0;
for (i = 1; i < EXPERIMENTS; i ++) {
currentAttempts = computeRoll (currentPossibleTotal);
totalAttempts += currentAttempts;
}
currentAverage = (double) totalAttempts / EXPERIMENTS;
return currentAverage;
}
/*
This method will roll two dice continuously until the goal established in the
main method is hit.
*/
private static int computeRoll (int goal) {
int dice1;
int dice2;
int total;
int attempts;
attempts = 0;
do {
dice1 = (int)(Math.random () * 6) + 1;
dice2 = (int)(Math.random () * 6) + 1;
total = dice1 + dice2;
attempts ++;
} while (total != goal);
return attempts;
}
} |
/**
* Lightweight implementation of the client side
* <a href="http://pypi.python.org/pypi/Pyro4/">Pyro</a> protocol.
*
* {@link net.razorvine.pyro.Config} contains the (very few) static config items.
* {@link net.razorvine.pyro.NameServerProxy} is a wrapper proxy to make it easier to talk to Pyro's name server.
* {@link net.razorvine.pyro.PyroProxy} is the proxy class that is used to connect to remote Pyro objects and invoke methods on them.
* {@link net.razorvine.pyro.PyroURI} is the URI class that is used to point at a specific object at a certain location.
*
* This package makes heavy use of the {@link net.razorvine.pickle} package to be able to
* serialize and de-serialize object graphs, which is used in the Pyro communication protocol.
* Note that Pyrolite only supports Pyro4.
*
* @author Irmen de Jong (irmen@razorvine.net)
* @version 4.12
* @see net.razorvine.pickle
*/
package net.razorvine.pyro;
|
package com.dao;
import java.util.List;
import com.entity.Skill;
public interface SkillDao {
public void addSkill(Skill skill);
public void updateSkill(Skill skill);
public void deleteSkill(int id);
public Skill getSkillById(int id);
public List<Skill> getAllSkillsByUserId(int id);
public void deleteAllSkillById(int id);
public int getIdSkillByUserId(int id);
}
|
package com.yrz.mybitesplus;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.baomidou.mybatisplus.MybatisConfiguration;
import com.baomidou.mybatisplus.entity.GlobalConfiguration;
import com.baomidou.mybatisplus.mapper.LogicSqlInjector;
import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.plugins.PerformanceInterceptor;
import com.baomidou.mybatisplus.spring.MybatisSqlSessionFactoryBean;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
/**
* @Author yrz
*/
@Configuration
@MapperScan({"com.yrz.mapper*"})
public class MybatisPlusConfig {
/**
* mybatis-plus分页插件<br>
* 文档:http://mp.baomidou.com<br>
*/
@Bean
public PaginationInterceptor paginationInterceptor() {
PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
//paginationInterceptor.setLocalPage(true);// 开启 PageHelper 的支持
return paginationInterceptor;
}
}
|
import java.util.Scanner;
public class SalesCommissionCalculator {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
float itemValue;
float totalSalesPerWeek = 0.0F;
do {
System.out.println("Enter item value or enter 0 to calculate your earnings");
itemValue = input.nextFloat();
totalSalesPerWeek += itemValue;
}
while (itemValue != 0);
System.out.println("Your earnings for this week = " + (totalSalesPerWeek * 0.09 + 200) + " $");
}
}
|
/*
* 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 ventanas;
import com.google.i18n.phonenumbers.NumberParseException;
import com.google.i18n.phonenumbers.PhoneNumberUtil;
import com.google.i18n.phonenumbers.PhoneNumberUtil.PhoneNumberFormat;
import com.google.i18n.phonenumbers.Phonenumber.PhoneNumber;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
/**
*
* @author meder
*/
public class ModificacionVerClientes extends javax.swing.JFrame {
/**
* Creates new form AgregarReservas
*/
Connection conexion;
private String nombreUsuario,administrador;
private boolean modificadoFlag;
public ModificacionVerClientes() {
initComponents();
this.setLocationRelativeTo(null);
try {
conexion = Conexion.obtener();
} catch (SQLException ex) {
Logger.getLogger(ModificacionVerClientes.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(ModificacionVerClientes.class.getName()).log(Level.SEVERE, null, ex);
}
agregarDatosATabla();
codClienteText.setText(Contar());
modificadoFlag = false;
}
@Override
public Image getIconImage() {
Image retValue = Toolkit.getDefaultToolkit().getImage(ClassLoader.getSystemResource("Imagenes/gr.png"));
return retValue;
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabelTitulo = new javax.swing.JLabel();
jButtonCerrar = new javax.swing.JButton();
jButtonMinimizar = new javax.swing.JButton();
jScrollPane1 = new javax.swing.JScrollPane();
jTable1 = new javax.swing.JTable();
jLabelBarra = new javax.swing.JLabel();
jLabelMpa = new javax.swing.JLabel();
jLabelNombre = new javax.swing.JLabel();
jLabelApellido = new javax.swing.JLabel();
jLabelDNI = new javax.swing.JLabel();
apellidoText = new javax.swing.JTextField();
resetButton = new javax.swing.JButton();
jLabelCodCliente = new javax.swing.JLabel();
nombreText = new javax.swing.JTextField();
dniText = new javax.swing.JTextField();
codClienteText = new javax.swing.JTextField();
jButtonBuscar = new javax.swing.JButton();
jButtonModificar = new javax.swing.JButton();
jButtonAtras = new javax.swing.JButton();
jLabelTelefono = new javax.swing.JLabel();
jButtonEliminar = new javax.swing.JButton();
jButtonAgregar = new javax.swing.JButton();
telefonoText = new javax.swing.JTextField();
jLabelBarraVertical = new javax.swing.JLabel();
jLabelfondo = new javax.swing.JLabel();
jLabelAdmin = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setIconImage(getIconImage());
setUndecorated(true);
getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());
jLabelTitulo.setFont(new java.awt.Font("Cambria", 3, 36)); // NOI18N
jLabelTitulo.setForeground(new java.awt.Color(255, 255, 255));
jLabelTitulo.setText("Gestion De Reservas");
getContentPane().add(jLabelTitulo, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 0, 380, 40));
jButtonCerrar.setBackground(new java.awt.Color(204, 204, 204));
jButtonCerrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/cerrar.png"))); // NOI18N
jButtonCerrar.setBorder(null);
jButtonCerrar.setBorderPainted(false);
jButtonCerrar.setContentAreaFilled(false);
jButtonCerrar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonCerrarActionPerformed(evt);
}
});
getContentPane().add(jButtonCerrar, new org.netbeans.lib.awtextra.AbsoluteConstraints(880, 0, 40, 40));
jButtonMinimizar.setBackground(new java.awt.Color(204, 204, 204));
jButtonMinimizar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/minimizar.png"))); // NOI18N
jButtonMinimizar.setBorder(null);
jButtonMinimizar.setBorderPainted(false);
jButtonMinimizar.setContentAreaFilled(false);
jButtonMinimizar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonMinimizarActionPerformed(evt);
}
});
getContentPane().add(jButtonMinimizar, new org.netbeans.lib.awtextra.AbsoluteConstraints(840, 0, 40, 40));
jTable1.addMouseListener(new java.awt.event.MouseAdapter() {
public void mouseClicked(java.awt.event.MouseEvent evt) {
jTable1MouseClicked(evt);
}
});
jScrollPane1.setViewportView(jTable1);
getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 70, 590, 390));
jLabelBarra.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/barra.jpg"))); // NOI18N
getContentPane().add(jLabelBarra, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 920, 40));
jLabelMpa.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/mpa.png"))); // NOI18N
getContentPane().add(jLabelMpa, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 60, -1, 410));
jLabelNombre.setBackground(new java.awt.Color(255, 255, 255));
jLabelNombre.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N
jLabelNombre.setForeground(new java.awt.Color(255, 255, 255));
jLabelNombre.setText("Nombre:");
getContentPane().add(jLabelNombre, new org.netbeans.lib.awtextra.AbsoluteConstraints(660, 120, -1, -1));
jLabelApellido.setBackground(new java.awt.Color(255, 255, 255));
jLabelApellido.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N
jLabelApellido.setForeground(new java.awt.Color(255, 255, 255));
jLabelApellido.setText("Apellido:");
getContentPane().add(jLabelApellido, new org.netbeans.lib.awtextra.AbsoluteConstraints(660, 160, -1, -1));
jLabelDNI.setBackground(new java.awt.Color(255, 255, 255));
jLabelDNI.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N
jLabelDNI.setForeground(new java.awt.Color(255, 255, 255));
jLabelDNI.setText("DNI:");
getContentPane().add(jLabelDNI, new org.netbeans.lib.awtextra.AbsoluteConstraints(660, 200, -1, -1));
apellidoText.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyReleased(java.awt.event.KeyEvent evt) {
apellidoTextKeyReleased(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
apellidoTextKeyTyped(evt);
}
});
getContentPane().add(apellidoText, new org.netbeans.lib.awtextra.AbsoluteConstraints(780, 160, 110, -1));
resetButton.setText("RESET");
resetButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
resetButtonActionPerformed(evt);
}
});
getContentPane().add(resetButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(810, 420, -1, -1));
jLabelCodCliente.setBackground(new java.awt.Color(255, 255, 255));
jLabelCodCliente.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N
jLabelCodCliente.setForeground(new java.awt.Color(255, 255, 255));
jLabelCodCliente.setText("Cod Cliente:");
getContentPane().add(jLabelCodCliente, new org.netbeans.lib.awtextra.AbsoluteConstraints(660, 80, -1, -1));
nombreText.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
nombreTextActionPerformed(evt);
}
});
nombreText.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
nombreTextKeyPressed(evt);
}
public void keyReleased(java.awt.event.KeyEvent evt) {
nombreTextKeyReleased(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
nombreTextKeyTyped(evt);
}
});
getContentPane().add(nombreText, new org.netbeans.lib.awtextra.AbsoluteConstraints(780, 120, 110, -1));
dniText.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
dniTextActionPerformed(evt);
}
});
dniText.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
dniTextKeyTyped(evt);
}
});
getContentPane().add(dniText, new org.netbeans.lib.awtextra.AbsoluteConstraints(780, 200, 110, -1));
codClienteText.setEditable(false);
codClienteText.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
codClienteTextKeyTyped(evt);
}
});
getContentPane().add(codClienteText, new org.netbeans.lib.awtextra.AbsoluteConstraints(780, 80, 110, -1));
jButtonBuscar.setText("Buscar por DNI");
jButtonBuscar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonBuscarActionPerformed(evt);
}
});
getContentPane().add(jButtonBuscar, new org.netbeans.lib.awtextra.AbsoluteConstraints(700, 230, 160, -1));
jButtonModificar.setText("Modificar");
jButtonModificar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonModificarActionPerformed(evt);
}
});
getContentPane().add(jButtonModificar, new org.netbeans.lib.awtextra.AbsoluteConstraints(700, 330, 160, -1));
jButtonAtras.setText("Atras");
jButtonAtras.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonAtrasActionPerformed(evt);
}
});
getContentPane().add(jButtonAtras, new org.netbeans.lib.awtextra.AbsoluteConstraints(670, 420, 70, -1));
jLabelTelefono.setBackground(new java.awt.Color(255, 255, 255));
jLabelTelefono.setFont(new java.awt.Font("Calibri", 0, 18)); // NOI18N
jLabelTelefono.setForeground(new java.awt.Color(255, 255, 255));
jLabelTelefono.setText("Telefono:");
getContentPane().add(jLabelTelefono, new org.netbeans.lib.awtextra.AbsoluteConstraints(660, 260, -1, -1));
jButtonEliminar.setText("Eliminar");
jButtonEliminar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonEliminarActionPerformed(evt);
}
});
getContentPane().add(jButtonEliminar, new org.netbeans.lib.awtextra.AbsoluteConstraints(700, 360, 160, -1));
jButtonAgregar.setText("Agregar");
jButtonAgregar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButtonAgregarActionPerformed(evt);
}
});
getContentPane().add(jButtonAgregar, new org.netbeans.lib.awtextra.AbsoluteConstraints(700, 300, 160, -1));
telefonoText.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
telefonoTextActionPerformed(evt);
}
});
telefonoText.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyTyped(java.awt.event.KeyEvent evt) {
telefonoTextKeyTyped(evt);
}
});
getContentPane().add(telefonoText, new org.netbeans.lib.awtextra.AbsoluteConstraints(780, 260, 110, -1));
jLabelBarraVertical.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/barra.jpg"))); // NOI18N
getContentPane().add(jLabelBarraVertical, new org.netbeans.lib.awtextra.AbsoluteConstraints(650, 60, 250, 410));
jLabelfondo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imagenes/dark-red-background.jpg"))); // NOI18N
jLabelfondo.setText("jLabel1");
jLabelfondo.setVerticalAlignment(javax.swing.SwingConstants.BOTTOM);
jLabelfondo.setDebugGraphicsOptions(javax.swing.DebugGraphics.BUFFERED_OPTION);
getContentPane().add(jLabelfondo, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 40, 920, 450));
jLabelAdmin.setText("jLabel1");
getContentPane().add(jLabelAdmin, new org.netbeans.lib.awtextra.AbsoluteConstraints(670, 110, -1, -1));
pack();
}// </editor-fold>//GEN-END:initComponents
public void setNombreUsuario(String nombreUsuario) {
this.nombreUsuario = nombreUsuario;
jLabelAdmin.setText(nombreUsuario);
}
private void jButtonCerrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCerrarActionPerformed
this.setVisible(false);
}//GEN-LAST:event_jButtonCerrarActionPerformed
private void jButtonMinimizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonMinimizarActionPerformed
this.setExtendedState(ICONIFIED);
}//GEN-LAST:event_jButtonMinimizarActionPerformed
private void nombreTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_nombreTextActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_nombreTextActionPerformed
private void dniTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dniTextActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_dniTextActionPerformed
private void jButtonAtrasActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAtrasActionPerformed
AccesoDeAdmin ventana = new AccesoDeAdmin();
ventana.setNombreUsuario(nombreUsuario);
ventana.setVisible(true);
ventana.setAdministrador(administrador);
this.setVisible(false);
}//GEN-LAST:event_jButtonAtrasActionPerformed
private void telefonoTextActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_telefonoTextActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_telefonoTextActionPerformed
private void jButtonModificarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonModificarActionPerformed
// TODO add your handling code here:
if(nombreText.getText().equals("")){
JOptionPane.showMessageDialog(rootPane, "Nombre está vacio");
}
if(apellidoText.getText().equals("")){
JOptionPane.showMessageDialog(rootPane, "Apellido está vacio");
}
if(dniText.getText().equals("")){
JOptionPane.showMessageDialog(rootPane, "DNI está vacio");
}
if(telefonoText.getText().equals("")){
JOptionPane.showMessageDialog(rootPane, "Telefono está vacio");
}
Modificar();
agregarDatosATabla();
}//GEN-LAST:event_jButtonModificarActionPerformed
private void jButtonBuscarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBuscarActionPerformed
// TODO add your handling code here:
Buscar();
}//GEN-LAST:event_jButtonBuscarActionPerformed
private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTable1MouseClicked
// TODO add your handling code here:
if (evt.getClickCount() == 2 && !evt.isConsumed()) {
evt.consume();
codClienteText.setText(jTable1.getValueAt(jTable1.getSelectedRow(), 0).toString());
nombreText.setText(jTable1.getValueAt(jTable1.getSelectedRow(), 1).toString());
apellidoText.setText(jTable1.getValueAt(jTable1.getSelectedRow(), 2).toString());
dniText.setText(jTable1.getValueAt(jTable1.getSelectedRow(), 3).toString());
telefonoText.setText(jTable1.getValueAt(jTable1.getSelectedRow(), 4).toString());
modificadoFlag = false;
}
}//GEN-LAST:event_jTable1MouseClicked
private void jButtonAgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAgregarActionPerformed
// TODO add your handling code here:
if(nombreText.getText().equals("")){
JOptionPane.showMessageDialog(rootPane, "Nombre está vacio");
}
if(apellidoText.getText().equals("")){
JOptionPane.showMessageDialog(rootPane, "Apellido está vacio");
}
if(dniText.getText().equals("")){
JOptionPane.showMessageDialog(rootPane, "DNI está vacio");
}
if(telefonoText.getText().equals("")){
JOptionPane.showMessageDialog(rootPane, "Telefono está vacio");
}
agregarCliente();
agregarDatosATabla();
}//GEN-LAST:event_jButtonAgregarActionPerformed
private void nombreTextKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_nombreTextKeyTyped
// TODO add your handling code here:
char c = evt.getKeyChar();
comprobarLetra(c, evt);
}//GEN-LAST:event_nombreTextKeyTyped
private void nombreTextKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_nombreTextKeyPressed
// TODO add your handling code here:
}//GEN-LAST:event_nombreTextKeyPressed
private void apellidoTextKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_apellidoTextKeyTyped
// TODO add your handling code here:
char c = evt.getKeyChar();
comprobarLetra(c, evt);
}//GEN-LAST:event_apellidoTextKeyTyped
private void dniTextKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_dniTextKeyTyped
// TODO add your handling code here:
char c = evt.getKeyChar();
comprobarNumero(c, evt);
if(dniText.getText().length() == 9){
evt.consume();
}
}//GEN-LAST:event_dniTextKeyTyped
private void telefonoTextKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_telefonoTextKeyTyped
// TODO add your handling code here:
char c = evt.getKeyChar();
if(telefonoText.getText().length() > 10){
evt.consume();
}else{
comprobarNumero(c, evt);}
}//GEN-LAST:event_telefonoTextKeyTyped
private void codClienteTextKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_codClienteTextKeyTyped
// TODO add your handling code here:
char c = evt.getKeyChar();
comprobarNumero(c, evt);
}//GEN-LAST:event_codClienteTextKeyTyped
private void resetButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_resetButtonActionPerformed
// TODO add your handling code here:
resetAll();
}//GEN-LAST:event_resetButtonActionPerformed
private void nombreTextKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_nombreTextKeyReleased
// TODO add your handling code here:
}//GEN-LAST:event_nombreTextKeyReleased
private void apellidoTextKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_apellidoTextKeyReleased
// TODO add your handling code here:
}//GEN-LAST:event_apellidoTextKeyReleased
private void jButtonEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonEliminarActionPerformed
// TODO add your handling code here:
if(Integer.parseInt(codClienteText.getText()) == Integer.parseInt(Contar())){
JOptionPane.showMessageDialog(rootPane, "Seleccione un cliente");
}else{
Eliminar();
resetAll();
agregarDatosATabla();
}
}//GEN-LAST:event_jButtonEliminarActionPerformed
public void setAdministrador(String administrador) {
this.administrador = administrador;
if(Integer.parseInt(administrador) == 0){
jButtonAgregar.setEnabled(false);
jButtonEliminar.setEnabled(false);
jButtonModificar.setEnabled(false);
}
}
private void fieldToUppercase(){
if(nombreText.getText() == ""){
JOptionPane.showMessageDialog(rootPane, "El nombre está vacio");
}
if(apellidoText.getText() == ""){
JOptionPane.showMessageDialog(rootPane, "El apellido está vacio");
}
String nombre = nombreText.getText();
nombreText.setText(nombre.substring(0,1).toUpperCase()+nombre.substring(1).toLowerCase());
String apellido = apellidoText.getText();
apellidoText.setText(apellido.substring(0,1).toUpperCase()+apellido.substring(1).toLowerCase());
}
private void agregarCliente() {
try {
fieldToUppercase();
PreparedStatement consulta;
consulta = conexion.prepareStatement("INSERT INTO clientes(cod_cliente,nombre,apellido,dni,telefono) VALUES(?,?,?, ?, ?)");
consulta.setInt(1, Integer.parseInt(codClienteText.getText()));
consulta.setString(2,nombreText.getText());
consulta.setString(3,apellidoText.getText());
//Comprueba si el DNI existe en la tabla
try {
String sql = "select * from clientes where dni = ?";
PreparedStatement consultasql;
consultasql = conexion.prepareStatement(sql);
consultasql.setInt(1, Integer.parseInt(dniText.getText()));
ResultSet rs = consultasql.executeQuery();
if (rs.first()) {
JOptionPane.showMessageDialog(rootPane, "ERROR, El DNI ya existe");
} else {
comprobarSiEsUnNumero(dniText.getText(), consulta,4, "DNI");
}
consultasql.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
consulta.setString(5,comprobarTelefono(telefonoText.getText()));
consulta.executeUpdate();
JOptionPane.showMessageDialog(rootPane, "Cliente agregado correctamente");
resetAll();
} catch (SQLException ex) {
System.out.println(ex.getMessage());
JOptionPane.showMessageDialog(rootPane, "Error al agregar cliente");
}
}
private void Eliminar() {
int dialogResult = JOptionPane.showConfirmDialog(this, "¿Desea Eliminar el cliente?", "Atencion!", JOptionPane.YES_NO_OPTION);
if (dialogResult == JOptionPane.YES_OPTION) {
// Saving code here
try {
String sql = "UPDATE clientes SET oculto = 1 WHERE cod_cliente = ?";
PreparedStatement consulta;
consulta = conexion.prepareStatement(sql);
consulta.setInt(1, Integer.parseInt(codClienteText.getText()));
consulta.executeUpdate();
consulta.close();
JOptionPane.showMessageDialog(rootPane, "Se ha eliminado correctamente");
}
catch(NumberFormatException ex){
JOptionPane.showMessageDialog(rootPane, "Seleccione un cliente");
}
catch (Exception ex) {
Logger.getLogger(ModificacionBajarReservas.class.getName()).log(Level.SEVERE, null, ex);
JOptionPane.showMessageDialog(rootPane, "Codigo de cliente incorrecto");
}
}
}
private void resetAll() {
codClienteText.setText("");
nombreText.setText("");
apellidoText.setText("");
dniText.setText("");
telefonoText.setText("");
codClienteText.setText(Contar());
modificadoFlag = false;
}
private void Buscar() {
try {
String sql = "select * from clientes where dni = ? and oculto = 0";
PreparedStatement consulta;
consulta = conexion.prepareStatement(sql);
consulta.setInt(1, Integer.parseInt(dniText.getText()));
ResultSet rs = consulta.executeQuery();
if (rs.first()) {
nombreText.setText(rs.getString("nombre"));
apellidoText.setText(rs.getString("apellido"));
codClienteText.setText(rs.getString("cod_cliente"));
telefonoText.setText(rs.getString("telefono"));
} else {
nombreText.setText("");
apellidoText.setText("");
dniText.setText("");
telefonoText.setText("");
codClienteText.setText("");
JOptionPane.showMessageDialog(rootPane, "Error en el DNI");
}
consulta.close();
} catch (Exception ex) {
JOptionPane.showMessageDialog(rootPane, "El DNI no existe");
System.out.println(ex.getMessage());
}
}
private void Modificar() {
if(Integer.parseInt(codClienteText.getText()) < Integer.parseInt(Contar())){
try {
fieldToUppercase();
String sql = "UPDATE clientes SET nombre = ?, apellido = ?, dni = ?, telefono = ? WHERE cod_cliente = ?";
PreparedStatement consulta;
consulta = conexion.prepareStatement(sql);
comprobarSiNoHayNumero(nombreText.getText(), consulta, 1, "NOMBRE");
comprobarSiNoHayNumero(apellidoText.getText(), consulta, 2, "APELLIDO");
try {
String sql2 = "select * from clientes where dni = ? and cod_cliente <> ?";
PreparedStatement consultasql;
consultasql = conexion.prepareStatement(sql2);
consultasql.setInt(1, Integer.parseInt(dniText.getText()));
consultasql.setInt(2,Integer.parseInt(codClienteText.getText()));
ResultSet rs = consultasql.executeQuery();
if (rs.first()) {
JOptionPane.showMessageDialog(rootPane, "EL DNI YA EXISTE");
} else {
comprobarSiEsUnNumero(dniText.getText(), consulta, 3, "DNI");
}
consultasql.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
consulta.setString(4,comprobarTelefono(telefonoText.getText()));
consulta.setInt(5, Integer.parseInt(codClienteText.getText()));
consulta.executeUpdate();
if(modificadoFlag){
JOptionPane.showMessageDialog(rootPane, "Modificado Correctamente");
resetAll();
}else{
JOptionPane.showMessageDialog(rootPane, "No se han detectado modificaciones");
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(rootPane, "Error al modificar");
Logger.getLogger(ModificacionBajarReservas.class.getName()).log(Level.SEVERE, null, ex);
}
}else{
JOptionPane.showMessageDialog(rootPane, "Error al modificar, el codigo aún no existe");
}
}
private String Contar() {
try {
ResultSet rp1 = null;
int rowCount = 0;
Statement stat = conexion.createStatement();
rp1 = stat.executeQuery("SELECT MAX(cod_cliente) FROM clientes");
if (rp1.next()) {
rowCount = rp1.getInt(1);
}
return String.valueOf(rowCount + 1);
} catch (Exception ex) {
setTitle(ex.toString());
JOptionPane.showMessageDialog(rootPane, "Error al contar el numero de reserva");
return "ERROR";
}
}
private void crearModelo() {
dfm = new javax.swing.table.DefaultTableModel(
new Object[][]{},
new String[]{
"Cod Cliente", "Nombre", "Apellido", "DNI", "Telefono"
}
) {
Class[] types = new Class[]{
java.lang.Integer.class, java.lang.Integer.class, java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.Integer.class
};
boolean[] canEdit = new boolean[]{
false, false, false, false, false
};
public Class getColumnClass(int columnIndex) {
return types[columnIndex];
}
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit[columnIndex];
}
};
jTable1.setModel(dfm);
}
private void comprobarSiNoHayNumero(String text, PreparedStatement consulta, int i, String campo) throws SQLException {
try {
if(text.length()<3){
JOptionPane.showMessageDialog(rootPane, "Hay menos de 3 caracteres en " + campo);
}
int num;
num = Integer.parseInt(text);
System.out.println("es numero");
JOptionPane.showMessageDialog(rootPane, "Se encontró numeros en " + campo);
} catch (Exception e) {
if(text.length() > 2){
consulta.setString(i, text);}
}
}
private void comprobarSiEsUnNumero(String text, PreparedStatement consulta, int i, String campo) throws SQLException {
try {
int num;
if (text.length() >= 8) {
num = Integer.parseInt(text);
consulta.setString(i, text);
} else {
JOptionPane.showMessageDialog(rootPane, "Tiene que ingresar 8 digitos en " + campo);
}
} catch (Exception e) {
System.out.println("no es numero");
JOptionPane.showMessageDialog(rootPane, "Se encontró letras en " + campo);
}
}
private void comprobarLetra(char c, KeyEvent evt) {
if (!Character.isLetter(c) && !Character.isSpaceChar(c) && evt.getKeyChar() != KeyEvent.VK_BACK_SPACE && evt.getKeyChar() != KeyEvent.VK_DELETE) {
getToolkit().beep();
System.out.println(evt.getKeyChar());
System.out.println(evt.getKeyLocation());
System.out.println(evt.getExtendedKeyCode());
evt.consume();
JOptionPane.showMessageDialog(rootPane, "Ingrese Solo Letras");
}
modificadoFlag = true;
}
private void comprobarNumero(char c, KeyEvent evt) {
if (!Character.isDigit(c) && evt.getKeyChar() != KeyEvent.VK_BACK_SPACE && evt.getKeyChar() != KeyEvent.VK_DELETE) {
getToolkit().beep();
System.out.println(evt.getKeyChar());
System.out.println(evt.getKeyLocation());
System.out.println(evt.getExtendedKeyCode());
evt.consume();
JOptionPane.showMessageDialog(rootPane, "Ingrese Solo Numeros");
}
modificadoFlag = true;
}
private void agregarDatosATabla() {
crearModelo();
try {
String sql = "select * from clientes where oculto = 0";
PreparedStatement consulta;
consulta = conexion.prepareStatement(sql);
ResultSet rs = consulta.executeQuery();
while (rs.next()) {
dfm.addRow(new Object[]{rs.getInt("cod_cliente"), rs.getString("nombre"), rs.getString("apellido"),
rs.getString("dni"), rs.getString("telefono")});
}
consulta.close();
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
private String comprobarTelefono(String number) {
if(number.length() > 8 && number.contains("-") || number.length() > 7 && !number.contains("-")){
try {
if(number.substring(0,2).equals("15")){
number = "11"+number.substring(2);
}
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
PhoneNumber numbers = phoneUtil.parse(number, "AR");
return phoneUtil.format(numbers, PhoneNumberFormat.NATIONAL);
} catch (NumberParseException e) {
System.err.println("NumberParseException was thrown: " + e.toString());
}
}else{
JOptionPane.showMessageDialog(rootPane, "Error en cantidad de numeros en Telefono");
}
return null;
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(ModificacionVerClientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ModificacionVerClientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ModificacionVerClientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ModificacionVerClientes.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
//</editor-fold>
//</editor-fold>
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ModificacionVerClientes().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JTextField apellidoText;
private javax.swing.JTextField codClienteText;
private javax.swing.JTextField dniText;
private javax.swing.JButton jButtonAgregar;
private javax.swing.JButton jButtonAtras;
private javax.swing.JButton jButtonBuscar;
private javax.swing.JButton jButtonCerrar;
private javax.swing.JButton jButtonEliminar;
private javax.swing.JButton jButtonMinimizar;
private javax.swing.JButton jButtonModificar;
private javax.swing.JLabel jLabelAdmin;
private javax.swing.JLabel jLabelApellido;
private javax.swing.JLabel jLabelBarra;
private javax.swing.JLabel jLabelBarraVertical;
private javax.swing.JLabel jLabelCodCliente;
private javax.swing.JLabel jLabelDNI;
private javax.swing.JLabel jLabelMpa;
private javax.swing.JLabel jLabelNombre;
private javax.swing.JLabel jLabelTelefono;
private javax.swing.JLabel jLabelTitulo;
private javax.swing.JLabel jLabelfondo;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTable jTable1;
private DefaultTableModel dfm;
private javax.swing.JTextField nombreText;
private javax.swing.JButton resetButton;
private javax.swing.JTextField telefonoText;
// End of variables declaration//GEN-END:variables
}
|
package com.kgitbank.spring.domain.account.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.kgitbank.spring.domain.account.dto.Sessionkey;
import com.kgitbank.spring.domain.account.mapper.LoginMapper;
import com.kgitbank.spring.domain.model.LoginVO;
import com.kgitbank.spring.domain.model.MemberVO;
@Service
public class LoginServiceImpl implements LoginService {
@Autowired
private LoginMapper mapper;
@Override
public MemberVO getLogin(MemberVO member) {
return mapper.getLogin(member);
}
@Override
public void keepLogin(Sessionkey key) {
mapper.keepLogin(key);
}
@Override
public MemberVO checkUserWithSessionkey(String sessionId) {
return mapper.checkUserWithSessionkey(sessionId);
}
@Override
public void loginHistory(LoginVO history) {
mapper.loginHistory(history);
}
}
|
package com.sdk4.boot.common;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.domain.Page;
import java.util.List;
/**
* 分页数据返回
*
* @author sh
*/
@Data
@NoArgsConstructor
public class PageResponse<T> extends BaseResponse<List<T>> {
private Integer total;
private Integer pageIndex;
private Integer pageSize;
private Integer pageCount;
public PageResponse(int pageIndex, int pageSize, int total, List<T> data) {
this.pageIndex = pageIndex;
this.pageSize = pageSize;
this.total = total;
this.pageCount = (total / pageSize) + (total % pageSize == 0 ? 0 : 1);
this.data = data;
}
public PageResponse(Page<T> page) {
this.total = (int) page.getTotalElements();
this.pageIndex = page.getNumber() + 1;
this.pageSize = page.getSize();
this.pageCount = page.getTotalPages();
this.data = page.getContent();
}
public PageResponse(Page page, List<T> data) {
this.total = (int) page.getTotalElements();
this.pageIndex = page.getNumber() + 1;
this.pageSize = page.getSize();
this.pageCount = page.getTotalPages();
this.data = data;
}
public PageResponse(PageResponse page, List<T> data) {
this.code = page.getCode();
this.message = page.getMessage();
this.total = page.getTotal();
this.pageIndex = page.getPageIndex();
this.pageSize = page.getPageSize();
this.pageCount = page.getPageCount();
this.data = data;
}
}
|
/*
* 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 evolutionaryagent.evolution.agent.teseo.statement;
import evolutionaryagent.evolution.agent.teseo.AgentSquareData;
import evolutionaryagent.evolution.agent.teseo.TeseoMemory;
import evolutionaryagent.evolution.agent.teseo.interpreter.TeseoInterpreter;
import evolutionaryagent.types.statement.Statement;
import unalcol.agents.Percept;
/**
*
* @author Camilo Alaguna
*/
public class Conditional implements Statement {
protected TeseoMemory memory;
protected TeseoInterpreter interpreter;
protected int start, end;
public Conditional(TeseoMemory memory, TeseoInterpreter interpreter, int start) {
this.memory = memory;
this.interpreter = interpreter;
this.start = this.end = start;
}
public boolean isAccommplished(Percept prcpt) {
ConditionResult result = evaluate(prcpt);
this.end = result.end;
return result.result;
}
public int getEnd() {
return this.end;
}
@Override
public Class<Conditional> getType() {
return Conditional.class;
}
public ConditionResult evaluate(Percept prcpt) {
return evaluateCondition(prcpt, this.start);
}
public ConditionResult evaluateCondition(Percept prcpt, int head) {
if(areEnoughBits(head, 2)) {
if(interpreter.getInstructions().get(head))
if(interpreter.getInstructions().get(head + 1))
return isPossibleRath(prcpt, head + 2);
else
return areEquals(prcpt, head + 2);
else
if(interpreter.getInstructions().get(head + 1))
return orOperator(prcpt, head + 2);
else
return andOperator(prcpt, head + 2);
}
return new ConditionResult(false, head + 2);
}
public boolean areEnoughBits(int head, int size) {
return head + size < interpreter.getInstructions().size();
}
public ConditionResult isPossibleRath(Percept prcpt, int head) {
if(areEnoughBits(head, 4)) {
int numberOfDirections = interpreter.readNumber(head, 4);
if(areEnoughBits(head + 4, numberOfDirections << 1)) {
int end = head + 4 + (numberOfDirections << 1);
return new ConditionResult(arePossibleMovements(head + 4, end), end);
}
}
return new ConditionResult(false, interpreter.getInstructions().size());
}
public boolean arePossibleMovements(int head, int end) {
AgentSquareData position = memory.getActualAgentSquareData();
for(; head < end; head += 2) {
position = position.neighbours[getDirection(head)];
if(position == null)
return false;
}
return true;
}
public int getDirection(int head) {
return (interpreter.getInstructions().get(head)? 2:0)
+ (interpreter.getInstructions().get(head + 1)? 1:0);
}
public ConditionResult areEquals(Percept prcpt, int head) {
if(areEnoughBits(head, 4)) {
for(int i = 0; i < 4; ++i)
if(interpreter.getPerception(prcpt, i) != interpreter.getInstructions().get(head + i))
return new ConditionResult(false, head + 4);
return new ConditionResult(true, head + 4);
}
return new ConditionResult(false, head + 4);
}
public ConditionResult andOperator(Percept prcpt, int head) {
ConditionResult left = evaluateCondition(prcpt, head);
ConditionResult right = evaluateCondition(prcpt, left.end);
return new ConditionResult(left.result && right.result, right.end);
}
public ConditionResult orOperator(Percept prcpt, int head) {
ConditionResult left = evaluateCondition(prcpt, head);
ConditionResult right = evaluateCondition(prcpt, left.end);
return new ConditionResult(left.result || right.result, right.end);
}
}
|
package org.inftel.socialwind.shared.services;
import com.google.web.bindery.requestfactory.shared.Request;
import com.google.web.bindery.requestfactory.shared.RequestContext;
import com.google.web.bindery.requestfactory.shared.ServiceName;
import org.inftel.socialwind.shared.domain.DeviceInfoProxy;
@ServiceName("org.inftel.socialwind.server.services.DeviceService")
public interface DeviceRequest extends RequestContext {
/**
* Registra un dispositivo para el servicio de mensajes. El dispositivo se registra asociado a
* la cuenta del surfero que esta atuenticado.
*/
Request<Void> register(DeviceInfoProxy device);
/**
* Elimina un dispositivo del servicio de mensajes. El dispositivo se elimina de la lista de
* dispositivos de la cuenta del surfero que esta atuenticado.
*/
Request<Void> unregister(DeviceInfoProxy device);
} |
/**
* Solutii Ecommerce, Automatizare, Validare si Analiza | Seava.ro
* Copyright: 2013 Nan21 Electronics SRL. All rights reserved.
* Use is subject to license terms.
*/
package seava.ad.business.impl.security;
import java.util.List;
import javax.persistence.EntityManager;
import seava.ad.business.api.security.IMenuItemService;
import seava.ad.domain.impl.security.Menu;
import seava.ad.domain.impl.security.MenuItem;
import seava.ad.domain.impl.security.Role;
import seava.j4e.api.session.Session;
import seava.j4e.business.service.entity.AbstractEntityService;
/**
* Repository functionality for {@link MenuItem} domain entity. It contains
* finder methods based on unique keys as well as reference fields.
*
*/
public class MenuItem_Service extends AbstractEntityService<MenuItem>
implements
IMenuItemService {
public MenuItem_Service() {
super();
}
public MenuItem_Service(EntityManager em) {
super();
this.setEntityManager(em);
}
@Override
public Class<MenuItem> getEntityClass() {
return MenuItem.class;
}
/**
* Find by unique key
*/
public MenuItem findByName(String name) {
return (MenuItem) this
.getEntityManager()
.createNamedQuery(MenuItem.NQ_FIND_BY_NAME)
.setParameter("clientId",
Session.user.get().getClient().getId())
.setParameter("name", name).getSingleResult();
}
/**
* Find by reference: menuItem
*/
public List<MenuItem> findByMenuItem(MenuItem menuItem) {
return this.findByMenuItemId(menuItem.getId());
}
/**
* Find by ID of reference: menuItem.id
*/
public List<MenuItem> findByMenuItemId(String menuItemId) {
return (List<MenuItem>) this
.getEntityManager()
.createQuery(
"select e from MenuItem e where e.clientId = :clientId and e.menuItem.id = :menuItemId",
MenuItem.class)
.setParameter("clientId",
Session.user.get().getClient().getId())
.setParameter("menuItemId", menuItemId).getResultList();
}
/**
* Find by reference: menu
*/
public List<MenuItem> findByMenu(Menu menu) {
return this.findByMenuId(menu.getId());
}
/**
* Find by ID of reference: menu.id
*/
public List<MenuItem> findByMenuId(String menuId) {
return (List<MenuItem>) this
.getEntityManager()
.createQuery(
"select e from MenuItem e where e.clientId = :clientId and e.menu.id = :menuId",
MenuItem.class)
.setParameter("clientId",
Session.user.get().getClient().getId())
.setParameter("menuId", menuId).getResultList();
}
/**
* Find by reference: roles
*/
public List<MenuItem> findByRoles(Role roles) {
return this.findByRolesId(roles.getId());
}
/**
* Find by ID of reference: roles.id
*/
public List<MenuItem> findByRolesId(String rolesId) {
return (List<MenuItem>) this
.getEntityManager()
.createQuery(
"select distinct e from MenuItem e, IN (e.roles) c where e.clientId = :clientId and c.id = :rolesId",
MenuItem.class)
.setParameter("clientId",
Session.user.get().getClient().getId())
.setParameter("rolesId", rolesId).getResultList();
}
}
|
package com.dahua.design.creation.factory.abstractfactory.express;
public class SFExpress extends AbstractExpress{
public SFExpress() {
this.address = "深圳";
}
@Override
public void express() {
System.out.println(address + " 顺丰快递更快更强");
}
}
|
package com.tencent.mm.plugin.webview.fts.ui;
import android.view.View;
import com.tencent.mm.sdk.platformtools.bd;
class b$1 extends bd<Boolean> {
final /* synthetic */ int Xt;
final /* synthetic */ int fKG;
final /* synthetic */ int goT = 0;
final /* synthetic */ float[] goU;
final /* synthetic */ b pQL;
final /* synthetic */ View val$view;
public b$1(b bVar, Boolean bool, View view, int i, float[] fArr, int i2) {
this.pQL = bVar;
this.val$view = view;
this.fKG = i;
this.goU = fArr;
this.Xt = i2;
super(1000, bool, (byte) 0);
}
protected final /* synthetic */ Object run() {
return Boolean.valueOf(this.pQL.a(this.val$view, this.fKG, this.goT, this.goU, this.Xt));
}
}
|
package org.lvzr.fast.java.patten.struct.facade;
/**9、外观/门面模式(Facade) 整合模式
* 外观模式是为了解决类与类之家的依赖关系的,像spring一样,可以将类和类之间的关系配置到配置文件中,
* 而外观模式就是将他们的关系放在一个Facade类中,降低了类类之间的耦合度,该模式中没有涉及到接口,
* 看下类图:(我们以一个计算机的启动过程为例)
* 如果我们没有Computer类,那么,CPU、Memory、Disk他们之间将会相互持有实例,
* 产生关系,这样会造成严重的依赖,修改一个类,可能会带来其他类的修改,这不是我们想要看到的,
* 有了Computer类,他们之间的关系被放在了Computer类里,这样就起到了解耦的作用,这,就是外观模式!
*/
public class User {
public static void main(String[] args) {
Computer computer = new Computer();
computer.startup();
computer.shutdown();
}
}
|
package br.usp.memoriavirtual.servlet;
import java.io.IOException;
import javax.ejb.EJB;
import javax.el.ELResolver;
import javax.faces.context.FacesContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import br.usp.memoriavirtual.controle.EditarCadastroUsuarioMB;
import br.usp.memoriavirtual.modelo.entidades.Aprovacao;
import br.usp.memoriavirtual.modelo.fachadas.ModeloException;
import br.usp.memoriavirtual.modelo.fachadas.remoto.EditarCadastroUsuarioRemote;
import br.usp.memoriavirtual.modelo.fachadas.remoto.MemoriaVirtualRemote;
import br.usp.memoriavirtual.utils.FacesUtil;
public class EditarCadastroUsuario extends HttpServlet {
@EJB
private MemoriaVirtualRemote memoriaVirtualEJB;
@EJB
private EditarCadastroUsuarioRemote editarCadastroUsuarioEJB;
/**
* Serial Version UID
*/
private static final long serialVersionUID = 2734229838622329992L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
String aprovacaoString = request.getParameter("Id");
aprovacaoString = this.memoriaVirtualEJB.embaralhar(aprovacaoString);
Aprovacao aprovacao = new Aprovacao();
try {
aprovacao = this.editarCadastroUsuarioEJB
.getAprovacao(aprovacaoString);
} catch (ModeloException m) {
m.printStackTrace();
}
try {
if (editarCadastroUsuarioEJB.isAprovacaoExpirada(aprovacaoString)) {
editarCadastroUsuarioEJB.removerAprovacao(aprovacaoString);
response.sendRedirect("restrito/dataexpirada.jsf");
} else {
// Inicializando Managed Bean
FacesContext facesContext = FacesUtil.getFacesContext(request,
response);
ELResolver resolver = facesContext.getApplication()
.getELResolver();
EditarCadastroUsuarioMB managedBean = (EditarCadastroUsuarioMB) resolver
.getValue(facesContext.getELContext(), null,
"editarCadastroUsuarioMB");
managedBean.setAcesso(aprovacaoString);
managedBean.setAprovacao(aprovacao);
response.sendRedirect("restrito/validaredicao.jsf");
}
} catch (ModeloException e) {
e.printStackTrace();
}
}
}
|
package com.empresa.controller;
import java.util.List;
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.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.empresa.entity.Medicamento;
import com.empresa.service.MedicamentoService;
@RestController
@RequestMapping("/rest/medicamento")
public class MedicamentoController {
@Autowired
private MedicamentoService service;
@GetMapping
@ResponseBody
public ResponseEntity<List<Medicamento>> listaMedicamento(){
List<Medicamento> lista = service.listaMedicamento();
return ResponseEntity.ok(lista);
}
@PostMapping
@ResponseBody
public ResponseEntity<Medicamento> insertaMedicamento(@RequestBody Medicamento obj){
if (obj == null) {
return ResponseEntity.noContent().build();
}else {
obj.setIdMedicamento(0);
Medicamento objSalida = service.insertaMedicamento(obj);
return ResponseEntity.ok(objSalida);
}
}
}
|
package com.ttan.binarySearchTree;
import java.util.ArrayList;
import java.util.Stack;
/**
* @Description:
* @author ttan
* @time 2020年1月10日 上午10:03:01
*/
public class Convert {
public TreeNode Convert(TreeNode pRootOfTree) {
TreeNode result = null;
TreeNode cur = null;
Stack<TreeNode> stack = new Stack<TreeNode>();
while (pRootOfTree != null || !stack.isEmpty()) {
if (pRootOfTree != null) {
stack.push(pRootOfTree);
pRootOfTree = pRootOfTree.left;
} else {
TreeNode node = stack.pop();
if (result == null) {
result = node;
result.left = null;
cur = result;
} else {
cur.right = node;
node.left = cur;
cur = cur.right;
}
node = node.right;
}
}
cur.right = null;
return result;
}
boolean isSymmetrical(TreeNode pRoot) {
ArrayList<TreeNode> preList = new ArrayList<TreeNode>();
// 中序遍历
preOrder(pRoot, preList);
// 获取根节点索引
int mid = preList.size() / 2;
for (int leftIndex = 0, rightIndex = mid + 1; leftIndex < mid
&& rightIndex < preList.size(); leftIndex++, rightIndex++) {
if (preList.get(leftIndex).data != preList.get(rightIndex).data) {
return false;
}
}
return true;
}
// 中序遍历
public void preOrder(TreeNode pRoot, ArrayList<TreeNode> preList) {
if (pRoot == null) {
return;
}
preOrder(pRoot.left, preList);
preList.add(pRoot);
preOrder(pRoot.right, preList);
}
public static void main(String[] args) {
TreeNode pRoot = new TreeNode(1);
TreeNode pRoot2 = new TreeNode(2);
TreeNode pRoot3 = new TreeNode(3);
TreeNode pRoot4 = new TreeNode(4);
TreeNode pRoot5 = new TreeNode(2);
TreeNode pRoot6 = new TreeNode(3);
TreeNode pRoot7 = new TreeNode(4);
pRoot.left = pRoot2;
pRoot2.left = pRoot3;
pRoot2.right = pRoot4;
pRoot.right = pRoot5;
pRoot5.left = pRoot6;
pRoot5.right = pRoot7;
System.out.println(new Convert().isSymmetrical(pRoot));
}
}
class TreeNode {
// 节点类
int data; // 数据域
TreeNode right; // 右子树
TreeNode left; // 左子树
public TreeNode(int data) {
super();
this.data = data;
}
@Override
public String toString() {
return "TreeNode [data=" + data + "]";
}
}
|
package com.connectis.programator.demo.dom.minecraft4;
public class PickAxe extends Tool {
public PickAxe(Material material) {
super(material);
}
}
|
package com.tencent.mm.ui.bizchat;
import android.content.Intent;
import com.tencent.mm.ac.a.h;
import com.tencent.mm.ac.a.j;
import com.tencent.mm.ac.z;
import com.tencent.mm.bg.d;
import com.tencent.mm.pluginsdk.ui.applet.ContactListExpandPreference.a;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.x;
class BizChatroomInfoUI$7 implements a {
final /* synthetic */ BizChatroomInfoUI tFD;
BizChatroomInfoUI$7(BizChatroomInfoUI bizChatroomInfoUI) {
this.tFD = bizChatroomInfoUI;
}
public final void of(int i) {
BizChatroomInfoUI.a(this.tFD, i);
}
public final void og(int i) {
boolean z = true;
j EE = this.tFD.EE(i);
if (EE == null || bi.oW(EE.field_profileUrl)) {
String str = "MicroMsg.BizChatroomInfoUI";
String str2 = "onItemNormalClick userInfo == null:%s";
Object[] objArr = new Object[1];
if (EE != null) {
z = false;
}
objArr[0] = Boolean.valueOf(z);
x.w(str, str2, objArr);
return;
}
x.i("MicroMsg.BizChatroomInfoUI", "onItemNormalClick Url:%s", new Object[]{EE.field_profileUrl});
z.Ng();
h.a(EE.field_userId, EE.field_brandUserName, this.tFD);
Intent intent = new Intent();
intent.putExtra("rawUrl", EE.field_profileUrl);
intent.putExtra("useJs", true);
d.b(this.tFD.mController.tml, "webview", ".ui.tools.WebViewUI", intent);
}
public final void aAK() {
if (BizChatroomInfoUI.b(this.tFD) != null) {
BizChatroomInfoUI.b(this.tFD).cdV();
}
}
public final void oh(int i) {
BizChatroomInfoUI.c(this.tFD);
}
}
|
import java.io.*;
import java.util.Scanner;
public class Sqr_cube{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
int num=sc.nextInt();
int dig=0,sqr=0,cube=0;
while(num!=0) {
dig=num%10;
num=num/10;
sqr=dig*dig;
cube=sqr*dig;
System.out.println("square = "+sqr+" cube = "+cube);
}
}
}
|
package org.simpleflatmapper.converter.test;
import org.junit.Test;
import org.simpleflatmapper.converter.ComposedConverter;
import org.simpleflatmapper.converter.Converter;
import org.simpleflatmapper.converter.ToStringConverter;
import org.simpleflatmapper.converter.impl.CharSequenceIntegerConverter;
import static org.junit.Assert.*;
public class ComposedConverterTest {
@Test
public void testComposedConverter() throws Exception {
Converter<Object, String> converterToString = ToStringConverter.INSTANCE;
Converter<CharSequence, Integer> converterToInteger = new CharSequenceIntegerConverter();
ComposedConverter<Object, String, Integer> composedConverter =
new ComposedConverter<Object, String, Integer>(converterToString, converterToInteger);
assertEquals(1234, composedConverter.convert(new Object() {
public String toString() {
return "1234";
}
}).intValue());
}
} |
package com.tencent.mm.plugin.voip.model;
import com.tencent.mm.R;
class o$14 implements Runnable {
final /* synthetic */ o oMC;
o$14(o oVar) {
this.oMC = oVar;
}
public final void run() {
i.bJI().stopRing();
if (o.e(this.oMC)) {
i.bJI().dO(R.k.playend, 0);
} else {
i.bJI().dO(R.k.playend, 1);
}
}
}
|
package com.example.euapp16.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
public class RegisterActivity extends AppCompatActivity {
RequestQueue registerqueue;
Button buttonRegister, buttonBack;
EditText editTextNick, editTextEmail, editTextCountry, editTextPassword, editTextPasswordCheck;
String passwd, passwdCheck, email, nick, country;
JSONObject registerRequest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
registerqueue = Volley.newRequestQueue(this);
buttonRegister = findViewById(R.id.buttonRegister);
buttonBack = findViewById(R.id.register_buttonBack);
editTextNick = findViewById(R.id.editTextnickname_register);
editTextEmail = findViewById(R.id.editTextEmail_register);
editTextPassword = findViewById(R.id.editTextPassword_register);
editTextPasswordCheck = findViewById(R.id.editTextCheckPassword_register);
editTextCountry = findViewById(R.id.editTextCountry_register);
buttonBack.setOnClickListener(view -> finish());
buttonRegister.setOnClickListener((View view) -> {
passwd = editTextPassword.getText().toString();
passwdCheck = editTextPasswordCheck.getText().toString();
email = editTextEmail.getText().toString();
nick = editTextNick.getText().toString();
country = editTextCountry.getText().toString();
if (!passwd.equals(passwdCheck) || passwd.length()<8)
{Toast.makeText(RegisterActivity.this, "Passwords not matching or too simple. Try more than 8 characters.", Toast.LENGTH_SHORT).show();}
else if (email.isEmpty()) {Toast.makeText(RegisterActivity.this, "Email not entered.", Toast.LENGTH_SHORT).show();}
else if (country.isEmpty()) {Toast.makeText(RegisterActivity.this, "Country not entered", Toast.LENGTH_SHORT).show();}
else if (nick.isEmpty()) {Toast.makeText(RegisterActivity.this, "Nickname not entered", Toast.LENGTH_SHORT).show();}
else {
registerRequest = new JSONObject();
try {
registerRequest.put("username", nick);
registerRequest.put("password",passwd);
registerRequest.put("country",country);
registerRequest.put("email",email);
} catch (JSONException e) {
e.printStackTrace();
}
String url = "http://147.229.242.53/eu/YellowTeam/API/register.php";
JsonObjectRequest stringRequest = new JsonObjectRequest(Request.Method.POST, url, registerRequest,
response -> {
try {
if (response.getBoolean("done")){
finish();
}
else{
Toast.makeText(RegisterActivity.this, "DB error. Try again later.", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
},
error -> Log.d("verbose",error.getMessage()));
registerqueue.add(stringRequest);
}
});
}
} |
package cn.uway.task.job;
import java.util.Date;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.slf4j.Logger;
import cn.uway.cache.RecordMemoryCache;
import cn.uway.config.LogMgr;
import cn.uway.task.FtpInfo;
import cn.uway.task.Task;
import cn.uway.util.DownStructer;
import cn.uway.util.FTPPathUtil;
import cn.uway.util.FTPTool;
import cn.uway.util.StringUtil;
import cn.uway.util.TimeUtil;
public class AsynScanAndDownJob extends AbstractJob{
private static final Logger LOGGER = LogMgr.getInstance().getSystemLogger();
private final BlockingQueue<Property> filePathQueue;
private final RecordMemoryCache memoryCache;
private DownLoadWorker worker;
private FtpInfo ftpInfo;
private FTPTool ftpTool;
private int sucCount;
private int scanCount;
private int failCount;
private int repeatCount;
private String ftpCharSet;
public AsynScanAndDownJob(Task task, List<String> filePathList, Date dataTime){
this(task, filePathList, dataTime, null);
}
public AsynScanAndDownJob(Task task, List<String> filePathList, Date dataTime, RecordMemoryCache memoryCache){
super(task, filePathList, dataTime);
this.memoryCache = memoryCache;
filePathQueue = new LinkedBlockingQueue<Property>(filePathList.size() * 10);
ftpInfo = task.getFtpInfo();
ftpTool = new FTPTool(ftpInfo);
ftpCharSet = ftpInfo.getCharset();
}
/*
* (non-Javadoc)
*
* @see java.util.concurrent.Callable#call()
*/
@Override
public JobFuture call() throws Exception{
//重命名线程
renameThread();
//开始计时
Long beginTime = System.currentTimeMillis();
// login
boolean bOK = ftpTool.login(ftpPool);
ftpTool.setFtpPool(ftpPool);
if(!bOK){
LOGGER.error("FTP多次尝试登陆失败,任务退出.");
return new JobFuture(-1, sucCount, "ftp登录失败");
}
LOGGER.debug("FTP登陆成功,开始扫描文件");
//创建启动下载线程
FTPClient ftpClient = ftpTool.getFtpClient();
worker = new DownLoadWorker(task, ftpClient);
worker.start();
String gatherPath = FTPPathUtil.getReplacedPath(task.getGatherPath(), task.getTimeZoneDate());
String fileName = FilenameUtils.getName(gatherPath);
LOGGER.debug("分配到扫描路径数:" + filePathList.size() + ",扫描文件名为:" + fileName);
for(String path : filePathList){
String encodeDir = StringUtil.encodeFTPPath(path + "/" + fileName, ftpCharSet);
List<FTPFile> listFiles = ftpTool.listFTPFiles(encodeDir);
if(listFiles==null||listFiles.isEmpty()){
LOGGER.debug("没有扫描到文件或扫描时出错:" + path);
continue;
}
for(FTPFile file : listFiles){
String fileFullPath = StringUtil.decodeFTPPath(file.getName(), ftpCharSet);
LOGGER.debug("扫描到文件:" + fileFullPath);
scanCount++;
if(memoryCache.contains(fileFullPath)){
LOGGER.debug("记录中已存在下载记录:" + fileFullPath);
repeatCount++;
continue;
}
filePathQueue.put(new Property(fileFullPath, file));
}
}
ftpTool.disconn();
worker.close();
//通知下载线程文件已经扫描完毕
//等待下载线程下载完队列中的文件
worker.join();
Long endTime = System.currentTimeMillis();
LOGGER.info("扫描路径个数:" + filePathList.size() + ",扫描到文件数:" + scanCount + ",过滤文件数:" + repeatCount + ",下载成功数:"
+ sucCount + ",下载失败数:" + failCount + ",总共耗时:" + (endTime - beginTime) / 1000.0 + "秒");
return new JobFuture(0, sucCount, "JOB执行成功");
}
/**
* 线程重命名<br>
* 主要是为了打印日志上显示线程方法
*/
protected void renameThread(){
String dataTimeStr = TimeUtil.getDateString_yyyyMMddHHmm(task.getTimeZoneDate());
Thread.currentThread().setName("[" + task.getTaskName() + "(" + dataTimeStr + ")][AsynScanAndDownJob:" + id + "]");
}
/**
* 临时存放ftp文件
*
* @ClassName: Property
* @author Niow
* @date: 2014-6-26
*/
private class Property{
public String fileFullPath;
public FTPFile ftpFile;
public Property(String fileFullPath, FTPFile ftpFile){
this.fileFullPath = fileFullPath;
this.ftpFile = ftpFile;
}
}
/**
* job的下载线程
*
* @ClassName: DownLoadWorker
* @author Niow
* @date: 2014-6-27
*/
private class DownLoadWorker extends Thread{
private boolean keepRunning = true;
private String downLoadPath;
private FTPTool ftpTools;
public DownLoadWorker(Task task, FTPClient ftpClient){
super(task.getTaskName() + "[ScanAndDownJob][id:" + id + "][DownLoadWorker]");
this.downLoadPath = task.getDownLoadPath() + "/" + TimeUtil.getDateStringyyyyMMddHHmm(task.getTimeZoneDate());
ftpTools = new FTPTool(ftpInfo);
}
/*
* (non-Javadoc)
*
* @see java.lang.Thread#run()
*/
@Override
public void run(){
LOGGER.debug("下载线程启动,准备开始下载.");
boolean bOK = ftpTools.login(ftpPool);
if(!bOK){
LOGGER.error("FTP多次尝试登陆失败,任务退出.");
keepRunning = false;
}
while(keepRunning || !filePathQueue.isEmpty()){
try{
Property peropery = filePathQueue.take();
String filePath = peropery.fileFullPath;
FTPFile file = peropery.ftpFile;
boolean downResult = downLoad(filePath, file);
if(downResult){
sucCount++;
memoryCache.addRecord(filePath);
}else{
LOGGER.debug("文件下载失败:" + filePath);
failCount++;
}
}catch(InterruptedException e){
LOGGER.debug("ScanAndDownJob文件路径队列获取唤醒");
}
}
ftpTools.disconn();
}
/**
* 下载文件
*
* @param filePath
* @param file
* @return
*/
private boolean downLoad(String filePath, FTPFile file){
boolean result = false;
LOGGER.debug("文件下载:" + filePath);
if(filePath.endsWith(".gz") && task.isNeedDecompress()){
result = ftpTools.downSingleFileForGz(filePath, downLoadPath, new DownStructer(), file.getSize());
}else{
result = ftpTools.downSingleFile(filePath, downLoadPath, new DownStructer(), file.getSize());
}
return result;
}
public void close(){
keepRunning = false;
this.interrupt();
}
}
}
|
package com.example.crypsis.customkeyboard.retrofit;
import java.util.List;
import retrofit2.http.GET;
import retrofit2.http.Path;
import rx.Observable;
public interface SearchApi {
/**
* See https://developer.github.com/v3/repos/#list-contributors
*/
@GET("/{searchText}")
Observable<List<SearchModel>> search(@Path("searchText") String searchText);
}
|
package jp.personal.server.web.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import jp.personal.server.annotation.NotLoginRequired;
import jp.personal.server.domain.entity.SesAdmin;
import jp.personal.server.enums.AdminRole;
import jp.personal.server.exception.AccessPermissonException;
import jp.personal.server.exception.AuthException;
import jp.personal.server.manager.VisitorManager;
import jp.personal.server.service.AdminUserService;
import jp.personal.server.utils.Cookies;
import jp.personal.server.utils.Msg;
import jp.personal.server.web.form.admin.AdminRegisterForm;
import jp.personal.server.web.form.admin.LoginForm;
/**
* 管理関係
*
* @author noguchi_kohei
*/
//TODO ハンドリングは後で、認証系インターセプターは後で作る
@Controller
@RequestMapping("/admin")
public class AdminController {
@Autowired
private AdminUserService adminUserService;
@Autowired
private VisitorManager visitorManager;
@Value("${root.register.flag}")
private boolean rootRegisterFlag;
@NotLoginRequired
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String view(Model model) {
model.addAttribute("loginForm", new LoginForm());
return "/admin/login";
}
@NotLoginRequired
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String login(Model model, @Validated LoginForm loginForm, BindingResult result, HttpServletRequest req,
HttpServletResponse res) {
if (result.hasErrors()) {
return "/admin/login";
}
try {
adminUserService.login(Cookies.getKey(req), loginForm.getAdminId(), loginForm.getPassword());
} catch (IllegalArgumentException | AuthException e) {
model.addAttribute("error", "ログインに失敗しました。");
return "/admin/login";
}
return "redirect:/admin/mypage";
}
@RequestMapping(value = "/logout", method = RequestMethod.GET)
public String logout(Model model, HttpServletRequest request, HttpServletResponse response) {
Cookies.terminate(request, response);
model.addAttribute("loginForm", new LoginForm());
return "redirect:/admin/login";
}
@NotLoginRequired
@RequestMapping(value = "/register", method = RequestMethod.GET)
public String viewRegister(Model model) {
model.addAttribute("adminRegisterForm", new AdminRegisterForm());
return "/admin/register";
}
@RequestMapping(value = "/mypage", method = RequestMethod.GET)
public String viewMypage(Model model) {
return "/admin/mypage";
}
@NotLoginRequired
@RequestMapping(value = "/register", method = RequestMethod.POST)
public String register(Model model, @Valid AdminRegisterForm adminRegisterForm, BindingResult result,
HttpServletRequest req, HttpServletResponse res) {
if (result.hasErrors()) {
return "/admin/register";
}
AdminRole adminRole = AdminRole.get(adminRegisterForm.getRoleType());
if (adminRole == AdminRole.SYSTEM_ROOT_ADMIN) {
if (!rootRegisterFlag) {
model.addAttribute("error", "登録権限がありません。こちらの登録はルート責任者のみ行えます。");
return "/admin/register";
}
} else {
String sid = Cookies.getKey(req);
SesAdmin sesAdmin = visitorManager.getSesAdminOpt(sid)
.orElseThrow(() -> new AuthException(Msg.NOT_FOUND_USER, true));
if (sesAdmin.getAdminRole() != AdminRole.SYSTEM_ROOT_ADMIN) {
model.addAttribute("error", "登録権限がありません。こちらの登録はルート責任者のみ行えます。");
return "/admin/register";
}
}
if (!adminRegisterForm.getPassword().equals(adminRegisterForm.getConfirmPassword())) {
model.addAttribute("error", "パスワードが一致しません。");
return "/admin/register";
}
try {
adminUserService.register(adminRegisterForm.getAdminId(), adminRegisterForm.getPassword(),
adminRegisterForm.getName(), AdminRole.get(adminRegisterForm.getRoleType()),
adminRegisterForm.getEMail(), adminRegisterForm.getNote());
} catch (AccessPermissonException e) {
model.addAttribute("error", "既に使用されているアカウント名です。");
return "/admin/register";
}
return "/admin/mypage";
}
}
|
package com.nisarg.flash;
import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ToggleButton;
public class MainActivity extends Activity {
Camera cam;
Parameters camParams;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
try{
cam=Camera.open();
camParams = cam.getParameters();
camParams.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(camParams);
cam.startPreview();
}catch (Exception e) {
e.printStackTrace();
cam.stopPreview();
}
ToggleButton tbTorch=(ToggleButton)findViewById(R.id.tbTorch);
tbTorch.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (((ToggleButton) v).isChecked()){
try{
camParams = cam.getParameters();
if(camParams.getFlashMode()!=Parameters.FLASH_MODE_TORCH){
camParams.setFlashMode(Parameters.FLASH_MODE_TORCH);
cam.setParameters(camParams);
cam.startPreview();
}
}catch (Exception e) {
e.printStackTrace();
cam.stopPreview();
}
}
else{
if (camParams.getFlashMode()!=Parameters.FLASH_MODE_OFF){
camParams.setFlashMode(Parameters.FLASH_MODE_OFF);
cam.setParameters(camParams);
}
}
}
});
}
@Override
public void onDestroy(){
super.onDestroy();
if (camParams.getFlashMode()!=Parameters.FLASH_MODE_OFF){
camParams.setFlashMode(Parameters.FLASH_MODE_OFF);
cam.setParameters(camParams);
}
cam.stopPreview();
cam.release();
}
}
|
package com.mwj.bean;
public class Departments {
private Integer departmentId;
private String departmentName;
private String locationName;
public Integer getDepartmentId() {
return departmentId;
}
public void setDepartmentId(Integer departmentId) {
this.departmentId = departmentId;
}
public String getDepartmentName() {
return departmentName;
}
public void setDepartmentName(String departmentName) {
this.departmentName = departmentName == null ? null : departmentName.trim();
}
public String getLocationName() {
return locationName;
}
public void setLocationName(String locationName) {
this.locationName = locationName == null ? null : locationName.trim();
}
@Override
public String toString() {
return "Departments{" +
"departmentId=" + departmentId +
", departmentName='" + departmentName + '\'' +
", locationName='" + locationName + '\'' +
'}';
}
} |
/*
* Copyright (c) 2008-2011 by Christian Lorenz, Bjoern Kolbeck,
* Jan Stender, Zuse Institute Berlin
*
* Licensed under the BSD License, see LICENSE file for details.
*
*/
package org.xtreemfs.utils;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.xtreemfs.common.config.Config;
import org.xtreemfs.foundation.SSLOptions;
public class DefaultDirConfig extends Config {
public static final String DEFAULT_DIR_CONFIG = "/etc/xos/xtreemfs/default_dir";
private static final int MAX_NUM_DIRS = 5;
private boolean sslEnabled;
protected String[] directoryServices;
private String serviceCredsFile;
private String serviceCredsPassphrase;
private String serviceCredsContainer;
private String trustedCertsFile;
private String trustedCertsPassphrase;
private String trustedCertsContainer;
public DefaultDirConfig() throws IOException {
super(DEFAULT_DIR_CONFIG);
// TODO(lukas) this will throw NullPointerExcpetions
directoryServices = null;
read();
}
public String[] getDirectoryServices() {
return directoryServices;
}
/**
* Returns SSL Options or null if SSL is not enabled
*
* @throws IOException
* @throws FileNotFoundException
*/
public SSLOptions getSSLOptions() throws FileNotFoundException, IOException {
if (sslEnabled) {
return new SSLOptions(new FileInputStream(serviceCredsFile), serviceCredsPassphrase,
serviceCredsContainer, new FileInputStream(trustedCertsFile), trustedCertsPassphrase,
trustedCertsContainer, false, false, null);
} else {
return null;
}
}
private void read() throws IOException {
List<String> dirServices = new ArrayList<String>();
// read required DIR service
dirServices.add(this.readRequiredString("dir_service.host") + ":"
+ this.readRequiredString("dir_service.port"));
// read optional DIR services
for (int i = 1; i < MAX_NUM_DIRS; i++) {
String dirHost = this.readOptionalString("dir_service" + (i + 1) + ".host", null);
String dirPort = this.readOptionalString("dir_service" + (i + 1) + ".port", null);
if (dirHost == null | dirPort == null) {
break;
}
dirServices.add(dirHost + ":" + dirPort);
}
directoryServices = dirServices.toArray(new String[dirServices.size()]);
this.sslEnabled = readOptionalBoolean("ssl.enabled", false);
// read SSL settings if SSL is enabled
if (sslEnabled) {
this.serviceCredsFile = this.readRequiredString("ssl.service_creds");
this.serviceCredsPassphrase = this.readRequiredString("ssl.service_creds.pw");
this.serviceCredsContainer = this.readRequiredString("ssl.service_creds.container");
this.trustedCertsFile = this.readRequiredString("ssl.trusted_certs");
this.trustedCertsPassphrase = this.readRequiredString("ssl.trusted_certs.pw");
this.trustedCertsContainer = this.readRequiredString("ssl.trusted_certs.container");
}
}
}
|
package com.hjtech.base.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
/*
* 项目名: EasyPark
* 包名 com.hjtech.easypark.common.utils
* 文件名: TimeUtils
* 创建者: ZJB
* 创建时间: 2017/6/20 on 15:12
* 描述: TODO
*/
public class TimeUtils {
/**
* 将时间戳转换为时间
*
* @param time
* @return
*/
public static String yyyyMMdd(long time) {
if (time == 0) {
return "";
}
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date(time);
return format.format(date);
}
/***
* 时间戳转换为时间
*
* @param time
* @return
*/
public static String HHmmss(long time) {
if (time == 0) {
return "";
}
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
Date date = new Date(time);
return format.format(date);
}
/***
* 时间戳转换为时间
*
* @param time
* @return
*/
public static String yyyyMMddHHmm(long time) {
if (time == 0) {
return "";
}
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
Date date = new Date(time);
return format.format(date);
}
/***
* 时间戳转换为时间
*
* @param time
* @return
*/
public static String yyyyMMddHHmmss(long time) {
if (time == 0) {
return "";
}
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date(time);
return format.format(date);
}
/***
* 时间戳转换为时间
*
* @param time
* @return
*/
public static String MMddHHmm(long time) {
if (time == 0) {
return "";
}
SimpleDateFormat format = new SimpleDateFormat("MM-dd HH:mm");
Date date = new Date(time);
return format.format(date);
}
/***
* 时间戳转换为时间
*
* @param time
* @return
*/
public static String MMddHHmmss(long time) {
if (time == 0) {
return "";
}
SimpleDateFormat format = new SimpleDateFormat("MM-dd HH:mm:ss");
Date date = new Date(time);
return format.format(date);
}
/***
* 时间戳转换为时间
*
* @param time
* @return
*/
public static String slashyyyyMMdd(long time) {
if (time == 0) {
return "";
}
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
Date date = new Date(time);
return format.format(date);
}
}
|
package com.example.dou.mysale;
import android.app.Activity;
import android.os.Bundle;
/**
* Created by Dou on 2016/4/27.
*/
public class LoginActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.registerorlogin);
}
}
|
package com.shift.timer.db;
import androidx.room.TypeConverter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
/**
* Created by roy on 6/13/2017.
*/
public class Converters {
@TypeConverter
public static Date fromTimeStampToDate(Long value) {
if (value == null) return null;
return new Date(value);
}
@TypeConverter
public static Long toDateTimestamp(Date value) {
if (value == null) return null;
return value.getTime();
}
} |
package pro.eddiecache.core.control.event;
/**
* @author eddie
* 事件处理器
*/
public interface IElementEventHandler
{
/**
* 对事件进行处理
* 可以通过事件得到对应的eventType与源缓存数据
*
* @param event 事件
*/
<T> void handleElementEvent(IElementEvent<T> event);
}
|
/*
* 文 件 名: ImageShowRestService.java
* 描 述: ImageShowRestService.java
* 时 间: 2013-7-1
*/
package com.babyshow.rest.imageshow;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.babyshow.image.bean.Image;
import com.babyshow.image.service.ImageService;
import com.babyshow.rest.RestService;
import com.babyshow.user.bean.User;
import com.babyshow.user.service.UserService;
/**
* <一句话功能简述>
*
* @author ztc
* @version [BABYSHOW V1R1C1, 2013-7-1]
*/
@Service
public class ImageShowRestService extends RestService
{
@Autowired
private UserService userService;
@Autowired
private ImageService imageService;
/**
*
* 公共照片查看
*
* @param imageShowRequest
* @return
*/
public ImageShowResponse handleImageShow(ImageShowRequest imageShowRequest)
{
ImageShowResponse imageShowResponse = new ImageShowResponse();
String deviceID = imageShowRequest.getDevice_id();
// 校验ID是否存在
boolean userValidate = this.validateUser(deviceID, imageShowResponse);
if(!userValidate)
{
imageShowResponse.setRequest("imageShowRequest");
return imageShowResponse;
}
Integer count = imageShowRequest.getCount();
if(count == null)
{
count = 1;
}
int imageStyle = imageShowRequest.getImage_style();
User user = this.userService.findUserByDeviceID(deviceID);
String userCode = user.getUserCode();
List<ImageShowResponseImage> imageShowResponseImageList = new ArrayList<ImageShowResponseImage>();
List<Image> imageList = this.imageService.findRandomImageList(imageStyle, count);
for(Image image : imageList)
{
ImageShowResponseImage imageShowResponseImage = new ImageShowResponseImage();
imageShowResponseImage.setImage(image);
// 用户和照片的赞关系
boolean likeStatus = this.imageService.isImageLikeExist(userCode, image.getImageCode());
imageShowResponseImage.setLikeStatus(likeStatus);
imageShowResponseImageList.add(imageShowResponseImage);
}
imageShowResponse.setImageShowResponseImageList(imageShowResponseImageList);
return imageShowResponse;
}
}
|
/*
* 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 utn.resumiderobilletes.excepciones;
/**
*
* @author libanez
*/
public class ResumideroValidationException extends Exception {
private static final String ERROR = "Error de Validación: ";
public ResumideroValidationException(String message) {
super(ERROR + message);
}
public ResumideroValidationException(String message, Throwable cause) {
super(ERROR + message, cause);
}
}
|
/** This program will randomly select a number from the 365 days of the year until
* we have found a "birthday" on each of those days.
**/
public class AllBirthdaysMethods {
/** The main method will simply print out what the result of the computeBirthdays
* method returns.
**/
public static void main (String [] args) {
int result;
result = 0;
System.out.print ("We had to check ");
result = computeBirthdays (result);
System.out.println (result + " people in order to find a birthday on each day.");
}
/** Preconditions: None
Postconditions: This method will return the result of how many people it took to cover
* every day of the year.
**/
private static int computeBirthdays (int count) {
boolean [] birthdayArray;
int birthdaysFound;
birthdayArray = new boolean [365];
birthdaysFound = 0;
while (birthdaysFound < 365) {
int birthday;
birthday = (int)(Math.random () * 365);
count ++;
if (birthdayArray [birthday] == false) {
birthdaysFound ++;
}
birthdayArray [birthday] = true;
}
return count;
}
} |
package mobi.wrt.oreader.app.test.feedly;
import mobi.wrt.oreader.app.clients.db.ClientEntity;
import mobi.wrt.oreader.app.clients.feedly.db.Category;
import mobi.wrt.oreader.app.clients.feedly.processor.CategoriesProcessor;
import mobi.wrt.oreader.app.test.common.AbstractTestProcessor;
/**
* Created by Uladzimir_Klyshevich on 4/23/2014.
*/
public class CategoriesProcessorTest extends AbstractTestProcessor {
public void testCategoryFeeds() throws Exception {
clear(Category.class);
clear(ClientEntity.class);
testExecute(CategoriesProcessor.APP_SERVICE_KEY, "feedly/categories.json");
checkCount(Category.class, 5);
checkCount(ClientEntity.class, 5);
checkRequiredFields(Category.class, Category.ID, Category.ID_AS_STRING, Category.LABEL, Category.POSITION);
testExecute(CategoriesProcessor.APP_SERVICE_KEY, "feedly/categories_updated.json");
checkCount(Category.class, 3);
checkCount(ClientEntity.class, 3);
checkRequiredFields(Category.class, Category.ID, Category.ID_AS_STRING, Category.LABEL, Category.POSITION);
}
}
|
package firstPg.services;
import firstPg.model.User;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
public class ReaderReviews extends JFrame {
private User user;
private JTextField bookReview;
private String bookTitle, Title, Review;
private JButton btnAddReview;
static String summery;
public void addBooksInTxtFileReviews(String title, String review) {
Title = ("");
Review = ("");
Title=title;
Review=review;
summery = ( Title + ",") + Review ;
String Data = summery;
try {
BufferedWriter reader1 = new BufferedWriter(new FileWriter(new File("src/main/resources/Reviews"), true));
reader1.write(Data);
reader1.newLine();
reader1.close();
} catch (IOException E) {
System.out.println("Error is " + E);
}
}
public ReaderReviews(String title) {
this.user = user;
this.bookTitle = title;
setLayout(new BorderLayout());
setTitle("Review Page");
setResizable(false);
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setSize(650, 350);
setLocationRelativeTo(null);
setVisible(true);
Container contentPane = this.getContentPane();
contentPane.setLayout(null);
Color c = Color.pink;
contentPane.setBackground(c);
Color cl = Color.lightGray;
JLabel mainTitle = new JLabel("Leave a review");
mainTitle.setBounds(180, 50, 600, 30);
mainTitle.setForeground(Color.BLACK);
mainTitle.setFont(new Font("Lucida Calligraphy", Font.BOLD, 30));
contentPane.add(mainTitle);
JLabel lblTitle = new JLabel("Book title:");
lblTitle.setBackground(Color.BLACK);
lblTitle.setForeground(Color.BLACK);
lblTitle.setFont(new Font("Lucida Calligraphy", Font.ITALIC, 20));
lblTitle.setBounds(50, 120, 200, 30);
lblTitle.setBackground(cl);
contentPane.add(lblTitle);
JLabel lblGivenTitle = new JLabel(bookTitle);
lblGivenTitle.setBackground(Color.BLACK);
lblGivenTitle.setForeground(Color.BLACK);
lblGivenTitle.setFont(new Font("Lucida Calligraphy", Font.ITALIC, 20));
lblGivenTitle.setBounds(200, 120, 600, 30);
lblGivenTitle.setBackground(cl);
contentPane.add(lblGivenTitle);
JLabel lblReview = new JLabel("Review:");
lblReview.setBackground(Color.BLACK);
lblReview.setForeground(Color.BLACK);
lblReview.setFont(new Font("Lucida Calligraphy", Font.PLAIN, 20));
lblReview.setBounds(50, 180, 200, 30);
lblReview.setBackground(cl);
contentPane.add(lblReview);
bookReview = new JTextField();
bookReview.setBounds(200, 180, 400, 25);
contentPane.add(bookReview);
btnAddReview = new JButton("Add Review");
btnAddReview.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if ((bookReview.getText()).equals("")) {
JOptionPane.showMessageDialog(null, "Sorry, your review box is empty!", "Adding review", JOptionPane.INFORMATION_MESSAGE);
} else {
addBooksInTxtFileReviews(bookTitle, bookReview.getText());
JOptionPane.showMessageDialog(null, "Thank you for your review!", "Adding review", JOptionPane.INFORMATION_MESSAGE);
dispose();
}
}
});
btnAddReview.setBounds(200,250, 160, 25);
btnAddReview.setBackground(Color.white);
contentPane.add(btnAddReview);
}
}
|
package at.ebinterface.validation.parser;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import com.helger.xsds.xmldsig.CXMLDSig;
/**
* Custom handler for ebInterface XML instances
*
* @author pl
*/
public class CustomHandler
{
// ebInterface Namespace
private String foundNameSpace;
// Indicates whether the file is signed or not
private boolean containsSignature;
// Namespace Prefix of the Signature element
private String signatureNamespacePrefix;
private void _evalElement (final Element aElem)
{
if ("Invoice".equals (aElem.getLocalName ()))
{
foundNameSpace = aElem.getNamespaceURI ();
}
else
if (CXMLDSig.NAMESPACE_URI.equals (aElem.getNamespaceURI ()) && "Signature".equals (aElem.getLocalName ()))
{
containsSignature = true;
// Get the namespace prefix of the signature element
signatureNamespacePrefix = aElem.getPrefix ();
}
}
private void _parseRecursive (@Nonnull final Node node)
{
if (node.getNodeType () == Node.ELEMENT_NODE)
_evalElement ((Element) node);
final NodeList nodeList = node.getChildNodes ();
for (int i = 0; i < nodeList.getLength (); i++)
{
final Node currentNode = nodeList.item (i);
if (currentNode.getNodeType () == Node.ELEMENT_NODE)
{
// calls this method for all the children which is Element
_parseRecursive (currentNode);
}
}
}
public void parse (@Nullable final Node node)
{
foundNameSpace = "";
containsSignature = false;
signatureNamespacePrefix = "";
if (node != null)
_parseRecursive (node);
}
@Nonnull
public String getFoundNameSpace ()
{
return foundNameSpace;
}
public boolean isContainsSignature ()
{
return containsSignature;
}
@Nonnull
public String getSignatureNamespacePrefix ()
{
return signatureNamespacePrefix;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.