text
stringlengths 10
2.72M
|
|---|
package es.uma.sportjump.sjs.dao.test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.springframework.beans.factory.annotation.Autowired;
import es.uma.sportjump.sjs.dao.test.util.CalendarEventDaoTestUtil;
import es.uma.sportjump.sjs.dao.test.util.CoachDaoTestUtil;
import es.uma.sportjump.sjs.dao.test.util.TeamDaoTestUtil;
import es.uma.sportjump.sjs.dao.test.util.TrainingDaoTestUtil;
import es.uma.sportjump.sjs.model.entities.CalendarEvent;
import es.uma.sportjump.sjs.model.entities.Coach;
import es.uma.sportjump.sjs.model.entities.Team;
import es.uma.sportjump.sjs.model.entities.Training;
public class CalendarEventDaoTest{
@Autowired
private CoachDaoTestUtil coachUtil;
@Autowired
private TeamDaoTestUtil teamUtil;
@Autowired
private TrainingDaoTestUtil trainingUtil;
@Autowired
private CalendarEventDaoTestUtil calendarEventDaoTestUtil;
protected Coach coach;
private Team team1;
private Training training1;
private Training training2;
private Training training3;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
coach = coachUtil.createNewCoach();
Long id1 = trainingUtil.createTraining("name1", "type1", "descripcion1", null, coach);
Long id2 = trainingUtil.createTraining("name2", "type2", "descripcion2", null, coach);
Long id3 = trainingUtil.createTraining("name3", "type3", "descripcion3", null, coach);
training1 = trainingUtil.readTraining(id1);
training2 = trainingUtil.readTraining(id2);
training3 = trainingUtil.readTraining(id3);
Long idTeam = teamUtil.createTeam("team1", coach);
team1 = teamUtil.readTeam(idTeam);
}
@After
public void tearDown() throws Exception {
teamUtil.deleteTeam(team1);
trainingUtil.deleteTraining(training1);
trainingUtil.deleteTraining(training2);
trainingUtil.deleteTraining(training3);
coachUtil.deleteCoach(coach);
}
public void testCalendarEventCRUD() {
// Definition calendarEvent
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(45000000);
Date eventDate = calendar.getTime();
// Create CalendarEvent
Long idEvent = calendarEventDaoTestUtil.createCalendarEvent(eventDate, team1, training1);
// Make assert
assertNotNull(idEvent);
// Read calendarEvent
CalendarEvent calendarEvent = calendarEventDaoTestUtil.readCalendarEvent(idEvent);
// Make assert
calendarEventDaoTestUtil.makeAssertTraining(eventDate, team1, training1, calendarEvent);
// Update training
calendar.setTimeInMillis(8000000);
Date newEventDate = calendar.getTime();
calendarEventDaoTestUtil.updateTraining(idEvent, newEventDate);
// Read calendarEvent
calendarEvent = calendarEventDaoTestUtil.readCalendarEvent(idEvent);
// Make assert
calendarEventDaoTestUtil.makeAssertTraining(newEventDate, team1, training1, calendarEvent);
// Delete calendarEvent
calendarEventDaoTestUtil.deleteCaledarEvent(idEvent);
// Read calendarEvent
calendarEvent = calendarEventDaoTestUtil.readCalendarEvent(idEvent);
// Make assert
assertNull(calendarEvent);
}
public void testGetAllEventByTeam(){
// Definition calendarEvent
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(45000000);
Date eventDate = calendar.getTime();
//Read List of calendarEvents
List<CalendarEvent> calendarEventList = calendarEventDaoTestUtil.getAllTrainingByTeam(team1);
int initSize = calendarEventList.size();
// Create CalendarEvent
Long idEvent1 = calendarEventDaoTestUtil.createCalendarEvent(eventDate, team1, training1);
calendar.setTimeInMillis(55000000);
Long idEvent2 = calendarEventDaoTestUtil.createCalendarEvent(calendar.getTime(), team1, training2);
calendar.setTimeInMillis(65000000);
Long idEvent3 = calendarEventDaoTestUtil.createCalendarEvent(calendar.getTime(), team1, training3);
//Read List of calendarEvents
calendarEventList = calendarEventDaoTestUtil.getAllTrainingByTeam(team1);
//make asserts
assertNotNull(idEvent1);
assertNotNull(idEvent2);
assertNotNull(idEvent3);
//asserts
assertNotNull (calendarEventList);
assertEquals(initSize + 3, calendarEventList.size());
// Delete calendarEvent
calendarEventDaoTestUtil.deleteCaledarEvent(idEvent1);
//Read List exercises
calendarEventList = calendarEventDaoTestUtil.getAllTrainingByTeam(team1);
//asserts
assertNotNull (calendarEventList);
assertEquals(initSize + 2, calendarEventList.size());
//Delete exerciseBlock
calendarEventDaoTestUtil.deleteCaledarEvent(idEvent2);
calendarEventDaoTestUtil.deleteCaledarEvent(idEvent3);
}
}
|
package com.tencent.mm.plugin.aa.ui;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
class PaylistAAUI$1 implements OnMenuItemClickListener {
final /* synthetic */ PaylistAAUI eEl;
PaylistAAUI$1(PaylistAAUI paylistAAUI) {
this.eEl = paylistAAUI;
}
public final boolean onMenuItemClick(MenuItem menuItem) {
this.eEl.finish();
return false;
}
}
|
package ru.nikozavr.auto.fragments;
import android.app.Activity;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import ru.nikozavr.auto.AutoEncyclopedia;
import ru.nikozavr.auto.LoginActivity;
import ru.nikozavr.auto.MainActivity;
import ru.nikozavr.auto.R;
public class ProfileFragment extends Fragment implements View.OnClickListener {
AutoEncyclopedia globe;
TextView txtLogin;
TextView txtEmail;
TextView txtPermission;
Button btnExit;
ListView mDrawerList;
DrawerLayout mDrawerLayout;
private String[] navMenuTitles;
@Override
public void onClick(View v){
globe.logoutUser();
Fragment home = new HomeFragment();
FragmentTransaction tr = getFragmentManager().beginTransaction();
tr.replace(R.id.frame_container, home, "home");
tr.addToBackStack("home");
tr.commit();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = null;
globe = (AutoEncyclopedia)getActivity().getApplicationContext();
if(globe.isLoggedIn()) {
rootView = inflater.inflate(R.layout.fragment_profile, container, false);
ImageView image = (ImageView) rootView.findViewById(R.id.imProfile);
image.setImageResource(R.drawable.ic_action_person);
btnExit = (Button) rootView.findViewById(R.id.btnExit);
btnExit.setOnClickListener(this);
} else {
Logging();
}
return rootView;
}
@Override
public void onResume()
{
super.onResume();
String[] info;
globe = (AutoEncyclopedia) getActivity().getApplicationContext();
info = globe.getUserDetails();
txtLogin = (TextView) getView().findViewById(R.id.lblProfileName);
txtEmail = (TextView) getView().findViewById(R.id.lblProfileEmail);
txtPermission = (TextView) getView().findViewById(R.id.lblProfileStatus);
txtLogin.setText(info[0]);
txtEmail.setText(getString(R.string.email) + " " + info[1]);
txtPermission.setText(getString(R.string.permission) + " " + info[2]);
TextView txtDownloading = (TextView) getView().findViewById(R.id.lblDownloadEdition);
TextView txtNoEdition = (TextView) getView().findViewById(R.id.lblNoEdition);
txtDownloading.setVisibility(View.INVISIBLE);
txtNoEdition.setVisibility(View.VISIBLE);
}
private void Logging(){
Intent intent = new Intent(getActivity(),LoginActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_TASK_ON_HOME);
startActivity(intent);
}
}
|
package com.github.manage.common.util;
import com.github.manage.vo.MenuVo;
import java.util.*;
/**
* @ProjectName: spring-cloud-examples
* @Package: com.github.manage.common.util
* @Description: 构建树
* @Author: Vayne.Luo
* @date 2019/01/18
*/
public class TreeBuilder {
public static List<MenuVo> findRoots(List<MenuVo> allNodes) {
// 根节点
List<MenuVo> root = new ArrayList<>();
allNodes.forEach(node -> {
if (node.getParentId() == 0) {
root.add(node);
}
});
root.forEach(node -> {
findChildren(node, allNodes);
});
return root;
}
/**
* 递归查找子节点
*
* @param treeNodes
* @return
*/
private static MenuVo findChildren(MenuVo rootNode, List<MenuVo> treeNodes) {
for (MenuVo menuVo : treeNodes) {
if (rootNode.getId().equals(menuVo.getParentId())) {
if (rootNode.getChildren() == null) {
rootNode.setChildren(new ArrayList<>());
}
rootNode.getChildren().add(findChildren(menuVo, treeNodes));
}
}
return rootNode;
}
public static void main(String[] args) {
// Set<MenuVo> set = new HashSet<>();
// set.addAll(Arrays.asList(
// new MenuVo(1, 0, "一级", "", ""),
// new MenuVo(2, 0, "一级", "", ""),
// new MenuVo(3, 1, "二级", "", ""),
// new MenuVo(4, 1, "二级", "", ""),
// new MenuVo(4, 2, "二级", "", ""),
// new MenuVo(6, 2, "二级", "", ""),
// new MenuVo(7, 3, "三级", "", ""),
// new MenuVo(8, 4, "三级", "", ""),
// new MenuVo(9, 5, "三级", "", ""),
// new MenuVo(10, 6, "三级", "", ""),
// new MenuVo(11, 6, "三级", "", "")
// ));
//
// for (MenuVo menuVo : findRoots(set)) {
// System.out.println(menuVo);
// }
}
}
|
/**
*
*/
package fi.jjc.graphics.rendering;
import fi.jjc.graphics.matrix.MatrixStack;
import fi.jjc.math.Angle;
import fi.jjc.math.Vector3;
import fi.jjc.util.wrappers.RotationHolder;
/**
* Class that creates and pushes a new rotate matrix to the modelview matrix stack, renders the
* specified inner render call, and then pops the matrix. The rotation is determined by specifying
* an axis and a rotation holder.
*
* @see fi.jjc.graphics.rendering.MVRender
* @see fi.jjc.graphics.matrix.MatrixStack
* @param <R>
* inner render call type.
* @author Jens ┼kerblom
*/
public class MVRotateRender<R extends RenderCall> implements RenderCall, RotationHolder
{
/**
* Rotation axis.
*/
private Vector3 axis;
/**
* Rotation.
*/
private final RotationHolder rh;
/**
* Inner render call.
*/
private final R rc;
/**
* Constructor.
*
* @param rh
* rotation.
* @param axis
* rotation axis.
* @param rc
* inner render call.
* @throws NullPointerException
* if any of the parameters is null.
*/
public MVRotateRender(RotationHolder rh, Vector3 axis, R rc)
{
if (rh == null || axis == null || rc == null)
throw new NullPointerException();
this.rc = rc;
this.rh = rh;
this.axis = axis;
}
/**
* @return inner render call.
*/
public R inner()
{
return this.rc;
}
/**
* Sets the rotation axis.
*
* @param axis
* the new rotation axis.
* @throws NullPointerException
* if parameter is null.
*/
public void setAxis(Vector3 axis)
{
if (axis == null)
throw new NullPointerException();
this.axis = axis;
}
/**
* @return the rotation axis.
*/
public Vector3 getAxis()
{
return this.axis;
}
/**
* Set the rotation.
*
* @param rot
* the new rotation.
*/
@Override
public void setRotation(Angle rot)
{
this.rh.setRotation(rot);
}
/**
* @return the rotation.
*/
@Override
public Angle getRotation()
{
return this.rh.getRotation();
}
/**
* @see fi.jjc.graphics.rendering.RenderCall#render()
*/
@Override
public void render()
{
MatrixStack.MAT_MODELVIEW.push();
{
MatrixStack.MAT_MODELVIEW.rotate(this.rh.getRotation(), this.axis);
this.rc.render();
}
MatrixStack.MAT_MODELVIEW.pop();
}
}
|
package InterfaceDemo;
/**
* "One Interface multiple implementations". Interfaces cannot be used to create
* objects. All methods, variables static, and final (constant) by default. All
* methods in interface usually have empty methods. The subclass should
* implement all methods from the interface, but each subclass can implement
* these methods in a different way. To access the different method
* implementation through interface (Ex: MyInterface obj = new Class()).
* Interfaces can be nested in the class then they can be public\private.
*
* @author Bohdan Skrypnyk
*/
interface CallBack {
void callback(int param);
}
class Client implements CallBack {
@Override
public void callback(int param) {
System.out.println("Method callback(); , called with variable : " + param);
}
//We can declare methods which is not in interface
public void notInterfaceMethod() {
System.out.println("Not interface method");
}
}
class AnotherClient implements CallBack {
@Override
public void callback(int param) {
System.out.println("One more way of method callback();");
System.out.println("param in ^2 = " + (param * param));
}
}
/**
* This class do not use callback method from interface, that why Incomplete
* class is abstract. Any other class which extends Incomplete class, should
* implement callback method from interface or be assigned as abstract.
*/
abstract class Incomplete implements CallBack {
int a, b;
void show() {
System.out.println(a + "" + b);
}
}
public class InterfDemo {
public static void main(String args[]) {
CallBack callback = new AnotherClient();
Client сlient = new Client();
callback.callback(15);
callback = сlient;
callback.callback(20);
}
}
|
package com.aciton;
import com.entity.BooksEntity;
import com.entity.OrdersEntity;
import com.service.BookService;
import org.apache.struts2.ServletActionContext;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Vector;
/**
* Created by 滩涂上的芦苇 on 2016/6/8.
*/
public class updateCart {
public static final long serialVersionUID = 1L;
public static final String RETURN = "return";
public HttpServletRequest request;
private String bookname;
private int quantity;
private BookService bookService;
public BookService getBookService() {
return bookService;
}
public void setBookService(BookService bookService) {
this.bookService = bookService;
}
public String getBookname() {
return bookname;
}
public void setBookname(String bookname) {
this.bookname = bookname;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public String execute() {
request = ServletActionContext.getRequest();
Vector<OrdersEntity> orderlist=new Vector<OrdersEntity>();
Vector<String>namelist=new Vector<String>();
Vector<BigDecimal>pricelist=new Vector<BigDecimal>();
try{
if(request.getSession().getAttribute("cart")!=null)
{
/*if there is a cart*/
orderlist=(Vector<OrdersEntity>)request.getSession().getAttribute("cart");
}
boolean exist=false;
for(int i=0;i<orderlist.size();i++)
{
BooksEntity book=bookService.queryByIsbn(orderlist.get(i).getIsbn());
namelist.add(book.getTitle());
pricelist.add(book.getPrice());
if(orderlist.get(i).getIsbn().equals(bookname))
{
/*the book exist*/
orderlist.get(i).setAmount(orderlist.get(i).getAmount()+quantity);
exist=true;
}
}
if(!exist)
{
OrdersEntity newOrder=new OrdersEntity();
newOrder.setAmount(quantity);
newOrder.setIsbn(bookname);
orderlist.add(newOrder);
BooksEntity book=bookService.queryByIsbn(bookname);
namelist.add(book.getTitle());
pricelist.add(book.getPrice());
}
}catch (Exception e){
e.printStackTrace();
}
request.setAttribute("namelist",namelist);
request.setAttribute("pricelist",pricelist);
request.getSession().setAttribute("cart", orderlist);
ServletActionContext.setRequest(request);
return RETURN;
}
}
|
package com.tencent.mm.plugin.luckymoney.ui;
import android.text.TextUtils;
import com.tencent.mm.modelcdntran.keep_SceneResult;
import com.tencent.mm.plugin.luckymoney.ui.LuckyMoneyNewYearReceiveUI.4;
import com.tencent.mm.plugin.wxpay.a.i;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.base.h;
class LuckyMoneyNewYearReceiveUI$4$1 implements Runnable {
final /* synthetic */ keep_SceneResult dPf;
final /* synthetic */ boolean kWh;
final /* synthetic */ 4 kWi;
LuckyMoneyNewYearReceiveUI$4$1(4 4, boolean z, keep_SceneResult keep_sceneresult) {
this.kWi = 4;
this.kWh = z;
this.dPf = keep_sceneresult;
}
public final void run() {
if (this.kWh) {
x.i("MicroMsg.LuckyMoneyNewYearReceiveUI", "the download image data is success!");
if (!TextUtils.isEmpty(this.dPf.field_fileId) && this.dPf.field_fileId.equals(LuckyMoneyNewYearReceiveUI.e(this.kWi.kWg))) {
LuckyMoneyNewYearReceiveUI.f(this.kWi.kWg);
return;
}
return;
}
x.e("MicroMsg.LuckyMoneyNewYearReceiveUI", "download image fail!");
h.bA(this.kWi.kWg, this.kWi.kWg.getString(i.lucky_money_download_image_fail_tips));
}
}
|
package in.yuchengl.scoutui;
import android.app.Application;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.parse.GetCallback;
import com.parse.Parse;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import com.parse.SaveCallback;
public class Scout extends Application {
private Location mLocation;
public boolean mBroadcasting = false;
private LocationManager mLocationManager;
private LocationListener mLocationListener;
public Location getLocation() {
return mLocation;
}
public void startListening() {
mLocationManager.requestLocationUpdates(mLocationManager.NETWORK_PROVIDER, 400, 1,
mLocationListener);
}
public void stopListening() {
mLocationManager.removeUpdates(mLocationListener);
}
@Override
public void onCreate() {
super.onCreate();
Parse.enableLocalDatastore(this);
Parse.initialize(this, "ZFqxViHGMZC0FRXXu1QlQJF44lewIZ4VBLDAPlZ5",
"3cmt5L56qE1NpMcqzZInRGNhIhNcy1feJb9cKIdx");
mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
mLocationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
mLocation = location;
Log.d("Application", "Lat: " + location.getLatitude() + " Long: " +
location.getLongitude());
if (mBroadcasting) {
ParseUser user = ParseUser.getCurrentUser();
if (user != null) {
user.put("latitude", mLocation.getLatitude());
user.put("longitude", mLocation.getLongitude());
user.saveInBackground(new SaveCallback() {
@Override
public void done(ParseException e) {
if (e == null) {
Log.d("Application", "location updated");
} else {
Log.e("Application", "Failed to update location");
}
}
});
}
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
@Override
public void onProviderEnabled(String provider) {}
@Override
public void onProviderDisabled(String provider) {}
};
}
}
|
class Figure{
protected double area;
protected double circleAround;
Figure(){}
Figure(double area, double circleAround){
this.area=area;
this.circleAround=circleAround;
}
public String toString(){
return String.format("이 도형은 %s이고, 넓이는 %f, 둘레는 %f입니다.",this.getClass().getName(), area, circleAround);
}
}
class Circle extends Figure{
protected double radius;
Circle(){
super(Math.PI,Math.PI*2);
radius=1;
}
Circle(double r){
radius = r;
super(Math.PI*r*r, 2*Math.PI*r);
}
public String toString(){
return super.toString()+"이 원의 반지름은"+radius+"입니다.";
}
}
class EquilateralTriangle extends Figure{
protected double side;
protected double height;
EquilateralTriangle(){
super(Math.sqrt(3)/4,3);
this.side=side;
}
EquilateralTriangle(double s){
super(Math.sqrt(3)/4*s,3*s);
side=s;
}
public String toString(){
return super.toString()+ 이 정삼각형의 한 변의 길이는"+s+"입니다.";
}
}
class Test{
public static void main(String [] args){
Circle c = new Circle(3);
System.out.print(c);
EquilateralTriangle t = new EquilateralTriangle(3);
System.out.print(t);
}
}
|
/*
* [y] hybris Platform
*
* Copyright (c) 2000-2016 SAP SE
* All rights reserved.
*
* This software is the confidential and proprietary information of SAP
* Hybris ("Confidential Information"). You shall not disclose such
* Confidential Information and shall use it only in accordance with the
* terms of the license agreement you entered into with SAP Hybris.
*/
package com.cnk.travelogix.operations.order.converters.populator;
import de.hybris.platform.converters.Populator;
import de.hybris.platform.servicelayer.dto.converter.ConversionException;
import org.springframework.util.Assert;
import com.cnk.travelogix.common.core.cart.data.AirlineIATAData;
import com.cnk.travelogix.common.core.model.AirlineIATAModel;
/**
* This populator is used for populate AirlineIATAModel into AirlineIATAData
*
* @author C5244543 (Shivraj)
*/
public class AirlineIATAPopulator implements Populator<AirlineIATAModel, AirlineIATAData>
{
@Override
public void populate(final AirlineIATAModel source, final AirlineIATAData target) throws ConversionException
{
Assert.notNull(source, "Parameter source cannot be null.");
Assert.notNull(target, "Parameter target cannot be null.");
target.setAccountingCode(source.getAccountingCode());
target.setAirlineName(source.getAirlineName());
target.setAirlinePrefix(source.getAirlinePrefix());
}
}
|
package com.urhive.panicbutton.activities;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.urhive.panicbutton.R;
import com.urhive.panicbutton.adapters.ContactsRecyclerViewAdapter;
import com.urhive.panicbutton.helpers.DBHelper;
import com.urhive.panicbutton.models.IceContact;
import java.util.List;
public class EditContactsActivity extends AppCompatBase {
public static final String EDIT = "EDIT";
private static final String TAG = "EditContactsActivity";
private static final int REQUEST_CODE_PICK_CONTACTS = 11;
private static List<IceContact> contacts;
private RelativeLayout addContactRL;
private RecyclerView recyclerView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_contacts);
setToolbar(getString(R.string.edit_contacts));
addContactRL = (RelativeLayout) findViewById(R.id.addContactRL);
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(EditContactsActivity.this));
contacts = DBHelper.getContactsList(EditContactsActivity.this);
addContactRL.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK, ContactsContract
.CommonDataKinds.Phone.CONTENT_URI);
startActivityForResult(contactPickerIntent, REQUEST_CODE_PICK_CONTACTS);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// check whether the result is ok
if (resultCode == RESULT_OK) {
// Check for the request code, we might be usign multiple startActivityForReslut
switch (requestCode) {
case REQUEST_CODE_PICK_CONTACTS:
Uri uriContact = data.getData();
setContactsInfo(uriContact);
break;
}
} else {
Toast.makeText(this, getString(R.string
.there_is_some_problem_try_again_later_check_for_permissions), Toast
.LENGTH_SHORT).show();
Log.e("MainActivity", "Failed to pick contact");
}
}
/**
* Query the Uri and read contact details. Handle the picked contact data.
*
* @param uri
*/
private void setContactsInfo(Uri uri) {
Cursor cursor;
//Query the content uri
cursor = getContentResolver().query(uri, null, null, null, null);
assert cursor != null;
cursor.moveToFirst();
int phoneIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
int nameIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
int contactIdIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone
.RAW_CONTACT_ID);
int id = cursor.getInt(contactIdIndex);
String photoUri = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds
.Phone.PHOTO_URI));
String phoneNo = cursor.getString(phoneIndex);
String name = cursor.getString(nameIndex);
IceContact contact = new IceContact(id, photoUri, name, phoneNo);
Log.i(TAG, "setContactsInfo: Selected contact is " + contact.toString());
contacts = DBHelper.getContactsList(EditContactsActivity.this);
int flag = 0;
for (IceContact c : contacts) {
if (c.getId() == contact.getId()) {
flag = 1;
}
}
if (flag == 0) {
// i.e. contact is not there in the list
contacts.add(contact);
Log.i(TAG, "setContactsInfo: contact not present already");
DBHelper.updateContactsToPreferences(EditContactsActivity.this, contacts);
recyclerView.setAdapter(new ContactsRecyclerViewAdapter(EditContactsActivity.this,
contacts, EDIT));
} else {
Log.i(TAG, "setContactsInfo: contact was already in the list");
}
}
@Override
protected void onResume() {
super.onResume();
recyclerView.setAdapter(new ContactsRecyclerViewAdapter(EditContactsActivity.this,
contacts, EDIT));
}
}
|
/**
* Copyright 2007 Jens Dietrich 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 nz.org.take.rt;
import java.io.PrintStream;
import java.util.ArrayList;
import java.util.List;
/**
* Data structure to store the reference to elements in the knowledge base.
* Used to record derivation trees, and can be used to cancel the inference process.
* Recorded are string ids of the rules, facts etc, applications can use this strings to
* access artefacts in the knowledge base.
* @author <a href="http://www-ist.massey.ac.nz/JBDietrich/">Jens Dietrich</a>
* @param <T> the type of the iterated elements
*/
public class DefaultDerivationController implements DerivationController {
private List<String> delegate = new ArrayList<String>();
private List<Integer> delegate2 = new ArrayList<Integer>();
private int depth = 0;
private boolean cancelled = false;
private int derivationCount = 0;
private DerivationListener derivationListener = null;
/**
* Log the use of a clause set
* this implementation does not record the parameters
*/
public void log(String ruleRef,int kind,Object... param) {
if (cancelled)
throw new DerivationCancelledException();
// System.out.println("Log@" + depth + " : " + ruleRef);
this.delegate.add(depth,ruleRef);
this.delegate2.add(depth,kind);
this.derivationCount = this.derivationCount+1;
if (derivationListener!=null)
derivationListener.step(ruleRef, depth, derivationCount);
}
/**
* Get a copy of the derivation log.
* @return a list
*/
public List<DerivationLogEntry> getLog() {
List<DerivationLogEntry> list = new ArrayList<DerivationLogEntry>();
for (int i=0;i<=depth;i++) {
String s = this.delegate.get(i);
if (s!=null) {
list.add(new DerivationLogEntry(this.delegate.get(i),this.delegate2.get(i)));
}
}
return list;
}
/**
* Print the log to a print stream.
* @param out a print stream
*/
public void printLog(PrintStream out) {
for (int i=0;i<=depth;i++) {
String s = this.delegate.get(i);
if (s!=null) {
out.print(i+1);
out.print(". ");
out.println(s);
}
}
}
/**
* Print the log to System.out.
*/
public void printLog() {
printLog(System.out);
}
/**
* Get the derivation level.
* @return
*/
public int getDepth() {
return depth;
}
/**
* Increase the derivation level.
* @return this
*/
public DefaultDerivationController increaseDepth() {
this.depth = depth+1;
return this;
}
/**
* Reset the derivation level.
* @param value
* @return this
*/
public DefaultDerivationController reset(int value) {
assert value<=depth;
assert value>=0;
this.depth = value;
return this;
}
/**
* Cancel the derivation.
*/
public void cancel() {
this.cancelled = true;
}
/**
* Whether the derivation has been cancelled.
* @return the cancelled status
*/
public boolean isCancelled() {
return this.cancelled;
}
/**
* Get the number of derivation steps performed so far.
* @return an int
*/
public int getDerivationCount() {
return derivationCount;
}
public DerivationListener getDerivationListener() {
return derivationListener;
}
public void setDerivationListener(DerivationListener derivationListener) {
this.derivationListener = derivationListener;
}
}
|
//
// FingerDot
//
// Created by Eduardo Almeida and Joao Almeida
// LPOO 13/14
//
package pt.up.fe.lpoo.fingerdot.logic.singleplayer;
import java.io.Serializable;
public class LeaderboardEntry implements Serializable {
public String username;
public String timestamp;
public String version;
public int score;
/**
* Initializes an empty leaderboard entry.
*/
public LeaderboardEntry() {
}
/**
* Initializes a leaderboard entry.
*
* @param n The username of the user.
* @param t The timestamp of the entry.
* @param v The version of the application.
* @param s The score.
*/
public LeaderboardEntry(String n, String t, String v, int s) {
username = n;
timestamp = t;
version = v;
score = s;
}
}
|
package service.fourier;
import org.apache.log4j.Logger;
import org.jtransforms.fft.DoubleFFT_1D;
import service.AbstractService;
import service.IService;
import service.exception.WavFileException;
import service.model.WavFile;
import java.io.File;
import java.io.IOException;
/**
* Created by vlad on 20.04.17.
*/
public class FilterService extends AbstractService implements IService {
private final static String ILLEGAL_ARG_EXCEPTION_MESSAGE="End frequency must higher than Start";
private final static Logger logger =Logger.getLogger(FilterService.class);
/*level of filtering
* 1-Lowest
* 10-Highest
* */
private final int ITERATION_COUNT =10;
@Override
public void filterFile(final String FILE_NAME,final String FILTERED_FILE_NAME,Integer beginFrequency,Integer endFrequency) throws IOException, WavFileException {
logger.info("filterFile function start");
if(beginFrequency>endFrequency) {
logger.error(ILLEGAL_ARG_EXCEPTION_MESSAGE);
throw new IllegalArgumentException(ILLEGAL_ARG_EXCEPTION_MESSAGE);
}
WavFile wavFile=WavFile.openWavFile(new File(FILE_NAME));
SAMPLE_RATE=(int) wavFile.getSampleRate();
if(wavFile.getNumFrames()/2>Integer.MAX_VALUE-5) {
logger.error(FILE_SIZE_EXCEPTION);
throw new WavFileException(FILE_SIZE_EXCEPTION);
}
/*read file data*/
int fileFramesCount=(int)wavFile.getNumFrames();
int frames[]=new int[fileFramesCount];
/*read data into frames*/
wavFile.readFrames(frames, fileFramesCount);
/*create appropriate fft helper object */
DoubleFFT_1D fftDo = new DoubleFFT_1D(fileFramesCount);
/*fft data container*/
double [] fft=new double[fileFramesCount*2];
/*write Re[i] to fft data*/
for(int i=0;i<frames.length;i++){
fft[i]=frames[i];
}
/*Frequency normalization coefficient
* Used to find appropriate frequency Real and Imaginary parts
* */
double normCoeff=(double)SAMPLE_RATE/fileFramesCount;
/*find fft data array indexes for desired frequency diapason*/
int beginFreqIndex = (int) (beginFrequency /normCoeff);
int endFreqIndex = (int) (endFrequency /normCoeff);
/*filtered frames*/
int framesFiltered[]=new int[fileFramesCount];
/*FILTERING PROCESS*/
for(int numFiltration = 0; numFiltration< ITERATION_COUNT; numFiltration++) {
fftDo.realForwardFull(fft);
/*update freq range data*/
for (int i = beginFreqIndex; i < endFreqIndex; i++) {
fft[2 * i] = 0.001;
fft[2 * i + 1] = 0.001;
//fft[i]=0;
}
/*get inverse data*/
fftDo.complexInverse(fft, true);
/*prepare data to backward conversion*/
if(numFiltration< ITERATION_COUNT -1)
for(int i=0;i<fft.length/2;i++){
fft[i]=fft[2*i];
fft[2*i+1]=0;
}
}//for ITERATION_COUNT
/*FILTERING PROCESS END*/
/*getting filtered frames*/
for(int i=0;i<fileFramesCount-1;i++){
framesFiltered[i]=(int)fft[2*i];
}
fftDo.realForwardFull(fft);
/*save filtered file*/
WavFile newFile=WavFile.newWavFile(new File(FILTERED_FILE_NAME),wavFile.getNumChannels(),
framesFiltered.length,wavFile.getValidBits(),wavFile.getSampleRate());
newFile.writeFrames(framesFiltered,framesFiltered.length);
//close file streams
newFile.close();
wavFile.close();
logger.info("file was filtered. New file is "+FILTERED_FILE_NAME);
}
}
|
package com.example.c_t_t_s;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import java.util.ArrayList;
public class FeedbackAdapter extends RecyclerView.Adapter<FeedbackAdapter.ViewHolder> {
private Context mContext;
private ArrayList<FeedBackDB> mFeedbackDB;
public FeedbackAdapter(Context c, ArrayList<FeedBackDB> feedbackDB){
mContext = c;
mFeedbackDB = feedbackDB;
}
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(mContext).inflate(R.layout.feedback_item,parent,false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
FeedBackDB feedBackDB= mFeedbackDB.get(position);
holder.em.setText(feedBackDB.getEmail().toString());
holder.fb.setText(feedBackDB.getFeedback().toString());
}
@Override
public int getItemCount() {
return mFeedbackDB.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView em,fb;
public ViewHolder(@NonNull View itemView) {
super(itemView);
em = itemView.findViewById(R.id.feedbackEmail);
fb = itemView.findViewById(R.id.feedbackView);
}
}
}
|
package com.fang.example.lock.client;
import com.fang.example.lock.protocol.LockProtocol;
import com.fang.example.lock.reactor.ReactorExption;
import java.io.IOException;
import java.lang.reflect.Proxy;
import java.net.InetSocketAddress;
import java.util.Enumeration;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Created by andy on 5/15/16.
*/
public class Client {
private static ConcurrentHashMap<InetSocketAddress , Connection> connMap =
new ConcurrentHashMap<InetSocketAddress , Connection>();
private static ExecutorService pool = Executors.newCachedThreadPool();
private static volatile int counter = 0;
public static Connection getConnection(InetSocketAddress address) throws IOException{
return connMap.get(address);
}
public static Object getInstance(Class clazz , InetSocketAddress address,int timeout) throws IOException{
ProtocolHandler handler = new ProtocolHandler();
handler.setAddress(address);
handler.setTimeOut(timeout);
if(!connMap.containsKey(address)){
Connection conn = new Connection(address);
connMap.put(address, conn);
pool.execute(conn);
}
else {
Connection isoldcon=connMap.get(address);
if(isoldcon.running==false)
{
Connection conn = new Connection(address);
connMap.put(address, conn);
pool.execute(conn);
}
}
return Proxy.newProxyInstance(clazz.getClassLoader(),
new Class[]{clazz}, handler);
}
public static synchronized int getCounter(){
if (counter < 1000 * 1000 * 1000) {
return counter ++;
}
else {
counter = 0;
return counter;
}
}
public static ExecutorService getPool() {
return pool;
}
public static void shutdown(){
//pool.shutdown();
//Set set = connMap.entrySet();
Enumeration<Connection> enumeration =connMap.elements();
while(enumeration.hasMoreElements()){
Connection conn = enumeration.nextElement();
conn.running = false;
}
}
public static void main(String[]args) throws IOException {
final int bolckTime = 60 * 60;
ExecutorService executor = Executors.newFixedThreadPool(4);
final InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8889);
LockProtocol lock = null;
try {
lock = (LockProtocol) Client
.getInstance(LockProtocol.class, address,
bolckTime);
} catch (IOException e) {
throw new ReactorExption("error" + e.getMessage(), e);
}
// String locked = lock.lock("key", "clientid1", 40000l);
String unlock = lock.unLock("key", "clientid2");
System.out.println("status-" + unlock);
}
}
|
package be_a_good_visitor;
class CartesianPt extends PointD {
CartesianPt(int x, int y) {
super(x, y);
}
int distanceToO() {
return (int) Math.sqrt(x * x + y * y);
}
}
|
package hl.restauth.auth;
import java.io.IOException;
import java.util.Iterator;
import java.util.Properties;
import java.util.SortedMap;
import java.util.TreeMap;
import org.json.JSONObject;
import hl.common.PropUtil;
public class AuthConfig {
public static String _PROP_FILENAME = "auth.properties";
public final static String _CFG_ROLES_SEPARATOR = ",";
public static String _PROP_KEY_USERBASE = "userbase";
//
public static String _PROP_KEY_FILE = "file";
public static String _PROP_KEY_LDAP = "ldap";
public static String _PROP_KEY_FACE = "face";
public static String _PROP_KEY_JDBC = "jdbc";
public static String _PROP_KEY_AUTH = "auth";
//
public static String _LDAP_HOST = "host";
public static String _LDAP_PORT = "port";
public static String _LDAP_SERVICE_ACCT_DN = "service.acct.dn";
public static String _LDAP_SERVICE_ACCT_PWD = "service.acct.pwd";
public static String _LDAP_SEARCH_SCOPE = "ldap.search.scope";
public static String _LDAP_SEARCH_CRITERIA = "ldap.search.criteria";
public static String _LDAP_USERNAME = "user.name";
public static String _LDAP_USERROLES= "user.roles";
//
public static String _FACEAPI_COMPARE_URL = "compare.url";
public static String _FACEAPI_COMPARE_TARGET = "compare.compare-target";
public static String _FACEAPI_COMPARE_POST_CONTENTTYPE = "compare.post.content-type";
public static String _FACEAPI_COMPARE_POST_TEMPLATE = "compare.post.template";
public static String _FACEAPI_COMPARE_THRESHOLD = "compare.threshold";
public static String _FACEAPI_COMPARE_RETRY_HFLIP = "compare.retry-hflip";
public static String _FACEAPI_COMPARE_RESULT_SCORE = "Score";
public static String _FACEAPI_EXTRACT_URL = "extract.url";
public static String _FACEAPI_EXTRACT_POST_CONTENTTYPE = "extract.post.content-type";
public static String _FACEAPI_EXTRACT_POST_TEMPLATE = "extract.post.template";
public static String _FACEAPI_EXTRACT_POST_RETURN_ATTR = "extract.post.return.attr";
//
public static String _JDBC_CLASSNAME= "classname";
public static String _JDBC_URL = "url";
public static String _JDBC_UID = "uid";
public static String _JDBC_PWD = "pwd";
public static String _JDBC_DB_TABLE = "db.table";
public static String _JDBC_DB_OPT_WHERE_CAUSE = "db.opt.where.causes";
public static String _JDBC_DB_COL_UID = "db.col.uid";
public static String _JDBC_DB_COL_NAME = "db.col.name";
public static String _JDBC_DB_COL_PASS = "db.col.password";
public static String _JDBC_DB_COL_ROLES = "db.col.roles";
public static String _JDBC_DB_COL_AUTH = "db.col.authtype";
//
private Properties propFileInfo = new Properties();
private Properties propLdapInfo = new Properties();
private Properties propFaceAuthInfo = new Properties();
private Properties propJdbcInfo = new Properties();
private Properties propAuthSettingsInfo = new Properties();
private Properties propAll = new Properties();
//
private SortedMap<String, String> mapUserbase = new TreeMap<String, String>();
//
private static AuthConfig instance = null;
//
public static AuthConfig getInstance()
{
if(instance==null)
{
instance = new AuthConfig();
}
return instance;
}
public String[] getUserBases()
{
return (String[]) mapUserbase.values().toArray(new String[]{});
}
public JSONObject getAuthConfig(String aConfigName)
{
JSONObject jsonCfg = new JSONObject();
aConfigName = aConfigName.toLowerCase();
for(Object oKey: propAuthSettingsInfo.keySet())
{
String sKey = oKey.toString().substring(aConfigName.length());
String sVal = propAuthSettingsInfo.getProperty(oKey.toString());
jsonCfg.put(sKey, sVal);
}
return jsonCfg;
}
public JSONObject getLdapConfig(String aConfigName)
{
JSONObject jsonCfg = new JSONObject();
aConfigName = aConfigName.toLowerCase();
jsonCfg.put(_LDAP_HOST, propLdapInfo.getProperty(aConfigName+"."+_LDAP_HOST));
jsonCfg.put(_LDAP_PORT, propLdapInfo.getProperty(aConfigName+"."+_LDAP_PORT));
jsonCfg.put(_LDAP_SERVICE_ACCT_DN, propLdapInfo.getProperty(aConfigName+"."+_LDAP_SERVICE_ACCT_DN));
jsonCfg.put(_LDAP_SERVICE_ACCT_PWD, propLdapInfo.getProperty(aConfigName+"."+_LDAP_SERVICE_ACCT_PWD));
jsonCfg.put(_LDAP_SEARCH_SCOPE, propLdapInfo.getProperty(aConfigName+"."+_LDAP_SEARCH_SCOPE));
jsonCfg.put(_LDAP_SEARCH_CRITERIA, propLdapInfo.getProperty(aConfigName+"."+_LDAP_SEARCH_CRITERIA));
jsonCfg.put(_LDAP_USERNAME, propLdapInfo.getProperty(aConfigName+"."+_LDAP_USERNAME));
jsonCfg.put(_LDAP_USERROLES, propLdapInfo.getProperty(aConfigName+"."+_LDAP_USERROLES));
return jsonCfg;
}
public JSONObject getFaceAuthConfig(String aConfigName)
{
JSONObject jsonCfg = new JSONObject();
aConfigName = aConfigName.toLowerCase();
jsonCfg.put(_FACEAPI_COMPARE_URL, propFaceAuthInfo.getProperty(aConfigName+"."+_FACEAPI_COMPARE_URL));
jsonCfg.put(_FACEAPI_COMPARE_TARGET, propFaceAuthInfo.getProperty(aConfigName+"."+_FACEAPI_COMPARE_TARGET));
jsonCfg.put(_FACEAPI_COMPARE_POST_CONTENTTYPE, propFaceAuthInfo.getProperty(aConfigName+"."+_FACEAPI_COMPARE_POST_CONTENTTYPE));
jsonCfg.put(_FACEAPI_COMPARE_POST_TEMPLATE, propFaceAuthInfo.getProperty(aConfigName+"."+_FACEAPI_COMPARE_POST_TEMPLATE));
jsonCfg.put(_FACEAPI_COMPARE_THRESHOLD, propFaceAuthInfo.getProperty(aConfigName+"."+_FACEAPI_COMPARE_THRESHOLD));
jsonCfg.put(_FACEAPI_COMPARE_RETRY_HFLIP, "true".equalsIgnoreCase(propFaceAuthInfo.getProperty(aConfigName+"."+_FACEAPI_COMPARE_RETRY_HFLIP)));
//
jsonCfg.put(_FACEAPI_EXTRACT_URL, propFaceAuthInfo.getProperty(aConfigName+"."+_FACEAPI_EXTRACT_URL));
jsonCfg.put(_FACEAPI_EXTRACT_POST_CONTENTTYPE, propFaceAuthInfo.getProperty(aConfigName+"."+_FACEAPI_EXTRACT_POST_CONTENTTYPE));
jsonCfg.put(_FACEAPI_EXTRACT_POST_TEMPLATE, propFaceAuthInfo.getProperty(aConfigName+"."+_FACEAPI_EXTRACT_POST_TEMPLATE));
jsonCfg.put(_FACEAPI_EXTRACT_POST_RETURN_ATTR, propFaceAuthInfo.getProperty(aConfigName+"."+_FACEAPI_EXTRACT_POST_RETURN_ATTR));
return jsonCfg;
}
public JSONObject getJdbcConfig(String aConfigName)
{
JSONObject jsonCfg = new JSONObject();
aConfigName = aConfigName.toLowerCase();
jsonCfg.put(_JDBC_CLASSNAME, propJdbcInfo.getProperty(aConfigName+"."+_JDBC_CLASSNAME));
jsonCfg.put(_JDBC_URL, propJdbcInfo.getProperty(aConfigName+"."+_JDBC_URL));
jsonCfg.put(_JDBC_UID, propJdbcInfo.getProperty(aConfigName+"."+_JDBC_UID));
jsonCfg.put(_JDBC_PWD, propJdbcInfo.getProperty(aConfigName+"."+_JDBC_PWD));
jsonCfg.put(_JDBC_DB_TABLE, propJdbcInfo.getProperty(aConfigName+"."+_JDBC_DB_TABLE));
jsonCfg.put(_JDBC_DB_COL_UID, propJdbcInfo.getProperty(aConfigName+"."+_JDBC_DB_COL_UID));
jsonCfg.put(_JDBC_DB_COL_NAME, propJdbcInfo.getProperty(aConfigName+"."+_JDBC_DB_COL_NAME));
jsonCfg.put(_JDBC_DB_COL_AUTH, propJdbcInfo.getProperty(aConfigName+"."+_JDBC_DB_COL_AUTH));
jsonCfg.put(_JDBC_DB_COL_PASS, propJdbcInfo.getProperty(aConfigName+"."+_JDBC_DB_COL_PASS));
jsonCfg.put(_JDBC_DB_COL_ROLES, propJdbcInfo.getProperty(aConfigName+"."+_JDBC_DB_COL_ROLES));
jsonCfg.put(_JDBC_DB_OPT_WHERE_CAUSE, propJdbcInfo.getProperty(aConfigName+"."+_JDBC_DB_OPT_WHERE_CAUSE));
return jsonCfg;
}
public Properties getFileUserProps()
{
return propFileInfo;
}
public String getPropValue(String aPropKey)
{
return propAll.getProperty(aPropKey);
}
public void init()
{
propFileInfo.clear();
propLdapInfo.clear();
propJdbcInfo.clear();
propFaceAuthInfo.clear();
mapUserbase.clear();
propAuthSettingsInfo.clear();
try {
propAll = PropUtil.loadProperties(_PROP_FILENAME);
} catch (IOException e) {
System.err.println(e);
propAll = new Properties();
}
Iterator iter = propAll.keySet().iterator();
while(iter.hasNext())
{
String sOrgkey = (String) iter.next();
if(sOrgkey!=null)
{
String sKey = sOrgkey.toLowerCase();
String sKeyType = sKey;
String sConfigValue = propAll.getProperty(sOrgkey);
Properties prop = null;
int iPos = sKey.indexOf(".");
if(iPos>-1)
{
sKeyType = sKey.substring(0, iPos);
//sKey = sKey.substring(iPos+1);
//
//System.out.println("type:"+sKeyType+" key:"+sKey+" value:"+sConfigValue);
}
//
if(sKeyType.startsWith(_PROP_KEY_USERBASE))
{
// Userbase will be sorted according to precedence
mapUserbase.put(sKey.toLowerCase(), sConfigValue);
}
else
{
if(sKeyType.startsWith(_PROP_KEY_FILE))
{
prop = propFileInfo;
}
//
else if(sKeyType.startsWith(_PROP_KEY_LDAP))
{
prop = propLdapInfo;
}
//
else if(sKeyType.startsWith(_PROP_KEY_JDBC))
{
prop = propJdbcInfo;
}
//
else if(sKeyType.startsWith(_PROP_KEY_FACE))
{
prop = propFaceAuthInfo;
}
//
else if(sKeyType.startsWith(_PROP_KEY_AUTH))
{
prop = propAuthSettingsInfo;
}
if(prop!=null)
{
prop.put(sKey.toLowerCase(), sConfigValue);
}
}
//
}
}
}
}
|
public class ReturnCash2 extends ReturnCash {
Data2 d;
public ReturnCash2(Data data) {
d = (Data2)data;
}
@Override
public void ReturnCash() {
System.out.println("RETURN $"+ (d.getCash() - d.getTotal()) +" of CASH");
}
}
|
package com.tencent.mm.ui.bizchat;
import android.content.Context;
import android.database.Cursor;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.tencent.mm.R;
import com.tencent.mm.ac.a.e;
import com.tencent.mm.ac.z;
import com.tencent.mm.ak.o;
import com.tencent.mm.pluginsdk.ui.d.j;
import com.tencent.mm.sdk.e.m;
import com.tencent.mm.sdk.e.m.b;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.MMActivity;
import com.tencent.mm.ui.base.MMSlideDelView;
import com.tencent.mm.ui.base.MMSlideDelView.d;
import com.tencent.mm.ui.base.MMSlideDelView.f;
import com.tencent.mm.ui.base.MMSlideDelView.g;
import com.tencent.mm.ui.r;
import com.tencent.mm.ui.r.a;
public final class c extends r<com.tencent.mm.ac.a.c> implements b {
private final MMActivity bGc;
private com.tencent.mm.ak.a.a.c hOC = null;
protected g hkN;
protected com.tencent.mm.ui.base.MMSlideDelView.c hkO;
protected f hkP;
protected d hkQ = MMSlideDelView.getItemStatusCallBack();
private final String hpJ;
public final /* synthetic */ Object a(Object obj, Cursor cursor) {
com.tencent.mm.ac.a.c cVar = (com.tencent.mm.ac.a.c) obj;
if (cVar == null) {
cVar = new com.tencent.mm.ac.a.c();
}
cVar.d(cursor);
return cVar;
}
public c(Context context, a aVar, String str) {
super(context, new com.tencent.mm.ac.a.c());
this.tlG = aVar;
this.bGc = (MMActivity) context;
this.hpJ = str;
com.tencent.mm.ak.a.a.c.a aVar2 = new com.tencent.mm.ak.a.a.c.a();
aVar2.dXB = e.cy(this.hpJ);
aVar2.dXy = true;
aVar2.dXV = true;
aVar2.dXN = R.k.default_avatar;
this.hOC = aVar2.Pt();
}
public final void WT() {
aYc();
com.tencent.mm.ac.a.d Na = z.Na();
String str = this.hpJ;
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("select * from BizChatInfo");
stringBuilder.append(" where brandUserName = '").append(str).append("'");
stringBuilder.append(" and (bitFlag & 8) != 0 ");
StringBuilder append = stringBuilder.append(" order by ");
StringBuffer stringBuffer = new StringBuffer();
stringBuffer.append(" case when length(BizChatInfo.chatNamePY) > 0 then upper(BizChatInfo.chatNamePY) ");
stringBuffer.append(" else upper(BizChatInfo.chatName) end asc, ");
stringBuffer.append(" upper(BizChatInfo.chatNamePY) asc, ");
stringBuffer.append(" upper(BizChatInfo.chatName) asc ");
append.append(stringBuffer.toString());
x.d("MicroMsg.BizChatInfoStorage", "getBizChatFavCursor: sql:%s", new Object[]{stringBuilder.toString()});
setCursor(Na.diF.rawQuery(stringBuilder.toString(), null));
if (this.tlG != null) {
this.tlG.Xb();
}
super.notifyDataSetChanged();
}
public final int getViewTypeCount() {
return 1;
}
public final void setPerformItemClickListener(g gVar) {
this.hkN = gVar;
}
public final void a(f fVar) {
this.hkP = fVar;
}
public final void setGetViewPositionCallback(com.tencent.mm.ui.base.MMSlideDelView.c cVar) {
this.hkO = cVar;
}
public final int getItemViewType(int i) {
return 0;
}
public final void onPause() {
if (this.hkQ != null) {
this.hkQ.aYl();
}
}
public final View getView(int i, View view, ViewGroup viewGroup) {
a aVar;
com.tencent.mm.ac.a.c cVar = (com.tencent.mm.ac.a.c) getItem(i);
if (view == null) {
a aVar2 = new a();
view = View.inflate(this.bGc, R.i.enterprise_bizchat_list_item, null);
aVar2.eCl = (ImageView) view.findViewById(R.h.avatar_iv);
aVar2.eTm = (TextView) view.findViewById(R.h.name_tv);
view.setTag(aVar2);
aVar = aVar2;
} else {
aVar = (a) view.getTag();
}
o.Pj().a(cVar.field_headImageUrl, aVar.eCl, this.hOC);
aVar.eTm.setText(j.a(this.bGc, cVar.field_chatName, (int) aVar.eTm.getTextSize()));
return view;
}
protected final void WS() {
WT();
}
public final void a(int i, m mVar, Object obj) {
super.a(i, mVar, obj);
}
}
|
package subjects.sample;
/**
* 买卖股票的最佳时机
* https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock/
*/
public class Q121 {
public static int maxProfit1(int[] prices) {
if (prices.length < 2) {
return 0;
}
int min = prices[0];
int result = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] < min) {
min = prices[i];
} else {
result = Math.max(result, prices[i] - min);
}
}
return result;
}
/**
* 动态规划
*
* @param prices
* @return
*/
public static int maxProfit2(int[] prices) {
int len = prices.length;
if (len < 2) {
return 0;
}
int[][] dp = new int[len][2];
dp[0][0] = 0;
dp[0][1] = -prices[0];
for (int i = 1; i < len; i++) {
// 这里dp[i - 1][1] + prices[i]为什么能保证卖了一次,因为下面一行代码买的时候已经保证了只买一次,所以这里自然就保证了只卖一次,不管是只允许交易一次还是允许交易多次,这行代码都不用变,因为只要保证只买一次(保证了只卖一次)或者买多次(保证了可以卖多次)即可。
dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
// - prices[i]这里可以理解为dp[0][0] - prices[i],这里为什么是dp[0][0] - prices[i],因为只有这样才能保证只买一次,所以需要用一开始初始化的未持股的现金dp[0][0]减去当天的股价
dp[i][1] = Math.max(dp[i - 1][1], dp[0][0] - prices[i]);
// 如果题目允许交易多次,就说明可以从直接从昨天的未持股状态变为今天的持股状态,因为昨天未持股状态可以代表之前买过又卖过后的状态,也就是之前交易过多次后的状态。也就是下面的代码。
// dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i]);
}
return dp[len - 1][0];
}
public static void main(String[] args) {
int[] prices = {7, 1, 5, 3, 6, 4};
System.out.println(maxProfit1(prices));
}
}
|
package com.apprisingsoftware.xmasrogue.world;
import com.apprisingsoftware.util.ArrayUtil;
import com.apprisingsoftware.util.MathUtil;
import com.apprisingsoftware.util.Pair;
import com.apprisingsoftware.util.Perlin2;
import com.apprisingsoftware.xmasrogue.entity.Armors;
import com.apprisingsoftware.xmasrogue.entity.Entities;
import com.apprisingsoftware.xmasrogue.entity.Foods;
import com.apprisingsoftware.xmasrogue.entity.Sleigh;
import com.apprisingsoftware.xmasrogue.entity.Weapons;
import com.apprisingsoftware.xmasrogue.util.Coord;
import com.apprisingsoftware.xmasrogue.util.Dir;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.List;
import java.util.Random;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
public final class DungeonBuilder implements MapBuilder {
protected final int width, height, originalSeed, depth;
private interface Feature {
/*
* # Already-placed walls
* . Interior tile (randomly selected)
* + Proposed door tile (randomly selected)
* X (0, 0) for proposed feature
* ` Space occupied by proposed feature
*
* ###
* #
* #````
* .+X```
* #````
* ###
*
* ````````
* ####````````
* .+X```````
* ####````````
* ````````
*/
List<Pair<Coord, Terrain>> getShiftedFeatureData();
boolean needsBorders(Coord coord);
default boolean canPlace(MapTile[][] map, Predicate<MapTile> freeTiles) {
List<Pair<Coord, Terrain>> shiftedFeatureData = getShiftedFeatureData();
if (shiftedFeatureData == null) return false;
for (Pair<Coord, Terrain> pair : shiftedFeatureData) {
Coord rootLoc = pair.getFirst();
if (needsBorders(rootLoc)) {
for (Coord loc : Dir.getOrthogonalNeighborsWithSelf(pair.getFirst())) { // allow space for neighbors
if (loc.x < 0 || loc.y < 0 || loc.x >= map.length || loc.y >= map[loc.x].length ||
!freeTiles.test(map[loc.x][loc.y])) {
return false;
}
}
}
else {
Coord loc = rootLoc;
if (loc.x < 0 || loc.y < 0 || loc.x >= map.length || loc.y >= map[loc.x].length ||
!freeTiles.test(map[loc.x][loc.y])) {
return false;
}
}
}
return true;
}
default boolean place(MapTile[][] map) {
List<Pair<Coord, Terrain>> shiftedFeatureData = getShiftedFeatureData();
for (Pair<Coord, Terrain> pair : shiftedFeatureData) {
map[pair.getFirst().x][pair.getFirst().y].setTerrain(pair.getSecond());
}
return true;
}
static List<Pair<Coord, Terrain>> shiftFeatureData(List<Pair<Coord, Terrain>> originalFeatureData, int doorX, int doorY, Dir direction) {
int rotationAngle = MathUtil.mod(direction.getAngle() - Dir.RIGHT.getAngle(), 360);
Coord doorLocation = new Coord(doorX, doorY);
Coord featureOrigin = doorLocation.plus(direction);
List<Pair<Coord, Terrain>> shiftedFeatureData = new ArrayList<>(originalFeatureData.size());
for (int i=0; i<originalFeatureData.size(); i++) {
Pair<Coord, Terrain> pair = originalFeatureData.get(i);
shiftedFeatureData.add(new Pair<>(pair.getFirst().rotate(rotationAngle).plus(featureOrigin), pair.getSecond()));
}
return shiftedFeatureData;
}
}
private static final class Room implements Feature {
private final List<Pair<Coord, Terrain>> shiftedFeatureData;
private final Coord doorLoc;
public Room(int width, int height, int doorX, int doorY, Dir direction, int entranceOffset) {
this.doorLoc = new Coord(doorX, doorY);
List<Pair<Coord, Terrain>> featureData = ArrayUtil.cartesianProduct(width, height, (x, y) -> new Pair<>(new Coord(x, y - entranceOffset), Terrain.DUNGEON_FLOOR));
this.shiftedFeatureData = Feature.shiftFeatureData(featureData, doorX, doorY, direction);
}
@Override public List<Pair<Coord, Terrain>> getShiftedFeatureData() {
return shiftedFeatureData;
}
@Override public boolean needsBorders(Coord coord) {
return !coord.equals(doorLoc);
}
}
private static final class Corridor implements Feature {
private final List<Pair<Coord, Terrain>> shiftedFeatureData;
private final Dir lastDir;
private final Coord doorLoc;
public Corridor(int length, double turnChance, int doorX, int doorY, Dir direction, Random random) {
this.doorLoc = new Coord(doorX, doorY);
List<Pair<Coord, Terrain>> featureData = new ArrayList<>();
Coord lastLoc = new Coord(0, 0);
Dir lastDir = Dir.RIGHT;
do {
featureData.add(new Pair<>(lastLoc, Terrain.DUNGEON_FLOOR));
lastLoc = lastLoc.plus(lastDir);
if (random.nextDouble() < turnChance) {
lastDir = lastDir.turn(random.nextBoolean());
}
}
while (featureData.size() < length);
this.shiftedFeatureData = Feature.shiftFeatureData(featureData, doorX, doorY, direction);
this.lastDir = lastDir;
}
public Dir getLastDir() {
return lastDir;
}
@Override public List<Pair<Coord, Terrain>> getShiftedFeatureData() {
return shiftedFeatureData;
}
@Override public boolean needsBorders(Coord coord) {
return !coord.equals(doorLoc);
}
}
private static final class CorridorWithRoom implements Feature {
private final List<Pair<Coord, Terrain>> shiftedFeatureData;
private final Coord doorLoc;
public CorridorWithRoom(int length, double turnChance, int width, int height, int doorX, int doorY, Dir direction, Random random) {
this.doorLoc = new Coord(doorX, doorY);
boolean addDoor1 = random.nextInt(100) < 60 || length >= 5;
boolean addDoor2 = random.nextInt(100) < 60 || length >= 5;
if (addDoor1 && addDoor2 && length < 4) {
if (random.nextBoolean()) addDoor1 = false;
else addDoor2 = false;
}
// Create corridor
Corridor corridor = new Corridor(length, turnChance, doorX, doorY, direction, random);
List<Pair<Coord, Terrain>> corridorFeatureData = corridor.getShiftedFeatureData();
List<Pair<Coord, Terrain>> shiftedFeatureData = new ArrayList<>(corridorFeatureData);
// Insert door
int doorIndex = shiftedFeatureData.size() - 1;
Coord doorLoc = shiftedFeatureData.get(doorIndex).getFirst();
shiftedFeatureData.set(doorIndex, new Pair<>(doorLoc, addDoor2 ? Terrain.WOOD_DOOR : Terrain.DUNGEON_FLOOR));
// Create room
Room room = new Room(width, height, doorLoc.x, doorLoc.y, corridor.getLastDir(), random.nextInt(height-1));
List<Pair<Coord, Terrain>> roomFeatureData = room.getShiftedFeatureData();
{
// If the room overlaps the corridor, then abort.
List<Coord> roomSpaces = roomFeatureData.stream().map(Pair::getFirst).collect(Collectors.toList());
if (shiftedFeatureData.stream().anyMatch(pair -> roomSpaces.contains(pair.getFirst()))) {
this.shiftedFeatureData = null;
return;
}
}
shiftedFeatureData.addAll(roomFeatureData);
shiftedFeatureData.add(new Pair<>(new Coord(doorX, doorY), addDoor1 ? Terrain.WOOD_DOOR : Terrain.DUNGEON_FLOOR));
this.shiftedFeatureData = shiftedFeatureData;
}
@Override public List<Pair<Coord, Terrain>> getShiftedFeatureData() {
return shiftedFeatureData;
}
@Override public boolean needsBorders(Coord coord) {
return !coord.equals(doorLoc);
}
}
private static final class Cavern implements Feature {
private final List<Pair<Coord, Terrain>> shiftedFeatureData;
public Cavern(int frameWidth, int frameHeight, double rockPercentage, int iterations, Random random) {
boolean[][] rock = new boolean[frameWidth][frameHeight];
ArrayUtil.fill(rock, () -> random.nextDouble() < rockPercentage);
for (int I=0; I<iterations; I++) {
boolean[][] copy = ArrayUtil.copy(rock);
IntStream.range(0, frameWidth).forEach(x -> IntStream.range(0, frameHeight).forEach(y -> {
rock[x][y] = IntStream.rangeClosed(x-1, x+1).map(i -> IntStream.rangeClosed(y-1, y+1).map(j -> {
try {
return copy[i][j] ? 1 : 0;
}
catch (IndexOutOfBoundsException e) {
return 1;
}
}).sum()).sum() >= 5;
}));
}
List<List<Coord>> blobs = new ArrayList<>();
boolean[][] visited = new boolean[frameWidth][frameHeight];
for (int X=0; X<frameWidth; X++) {
for (int Y=0; Y<frameHeight; Y++) {
if (!rock[X][Y] && !visited[X][Y]) {
List<Coord> blob = new ArrayList<>();
Deque<Coord> stack = new ArrayDeque<>();
stack.add(new Coord(X, Y));
while (!stack.isEmpty()) {
Coord currentLoc = stack.removeFirst();
int x = currentLoc.x, y = currentLoc.y;
try {
if (visited[x][y]) {
continue;
}
}
catch (ArrayIndexOutOfBoundsException e) {
continue;
}
visited[x][y] = true;
if (rock[x][y]) continue;
blob.add(currentLoc);
for (Dir d : Dir.ORTHOGONAL_COMPASS) {
stack.addLast(currentLoc.plus(d));
}
}
blobs.add(blob);
}
}
}
blobs.sort((l1, l2) -> l1.size() - l2.size());
List<Coord> chosenBlob = blobs.get(blobs.size()-1);
this.shiftedFeatureData = chosenBlob.stream().map(coord -> new Pair<>(coord, Terrain.ROCK_FLOOR)).collect(Collectors.toList());
}
@Override public List<Pair<Coord, Terrain>> getShiftedFeatureData() {
return shiftedFeatureData;
}
@Override public boolean needsBorders(Coord coord) {
return false;
}
}
public DungeonBuilder(int width, int height, int depth, int originalSeed) {
this.width = width;
this.height = height;
this.depth = depth;
this.originalSeed = originalSeed;
}
@Override public MapTile[][] getMap() {
Random random = new Random((originalSeed * (depth + Integer.MAX_VALUE / 2)) ^ depth);
MapTile[][] map = new MapTile[width][height];
// Fill dungeon with solid rock
ArrayUtil.fill(map, () -> new MapTile(Terrain.ROCK_WALL));
// Place first feature
{
Feature firstFeature;
if (depth+1 >= 3 && random.nextInt(100) < 75) {
firstFeature = new Cavern(width, height, 0.5, 5, random);
}
else {
firstFeature = new Room(9, 7, width/2, height/2, Dir.ORTHOGONAL_COMPASS.get(random.nextInt(4)), random.nextInt(7));
}
if (firstFeature.canPlace(map, tile -> true)) {
firstFeature.place(map);
}
else {
throw new AssertionError();
}
}
// Place more features branching off the first
int attemptedRooms = 0;
int successfulRooms = 0;
while (attemptedRooms < 10000 && successfulRooms < 100) {
// Pick two random adjacent cells, and check if they go across the wall of a room.
int startX = random.nextInt(width),
startY = random.nextInt(height);
Dir direction = Dir.ORTHOGONAL_COMPASS.get(random.nextInt(4));
int doorX = startX + direction.getX(),
doorY = startY + direction.getY();
if (doorX < 0 || doorY < 0 || doorX >= width || doorY >= height) continue;
if ((map[startX][startY].getTerrain() == Terrain.ROCK_FLOOR || map[startX][startY].getTerrain() == Terrain.DUNGEON_FLOOR) &&
(map[doorX][doorY].getTerrain() == Terrain.ROCK_WALL || map[doorX][doorY].getTerrain() == Terrain.DUNGEON_WALL)) {
Feature feature;
feature = new CorridorWithRoom(
1 + random.nextInt(7),
random.nextDouble(),
7 + random.nextInt(7),
4 + random.nextInt(4),
doorX,
doorY,
direction,
random);
if (feature.canPlace(map, tile -> tile.getTerrain() == Terrain.ROCK_WALL || tile.getTerrain() == Terrain.DUNGEON_WALL)) {
feature.place(map);
successfulRooms += 1;
}
attemptedRooms += 1;
}
}
// Set material of dungeon walls
for (int x=0; x<width; x++) {
for (int y=0; y<height; y++) {
Coord rootLoc = new Coord(x, y);
if (map[x][y].getTerrain() == Terrain.ROCK_WALL &&
Dir.ALL_COMPASS.stream().map(rootLoc::plus).anyMatch(coord -> {
try {
return map[coord.x][coord.y].getTerrain() == Terrain.DUNGEON_FLOOR;
}
catch (ArrayIndexOutOfBoundsException e) {
return false;
}
})) {
map[x][y].setTerrain(Terrain.DUNGEON_WALL);
}
}
}
// Place foliage
Perlin2 grassNoise = new Perlin2(random.nextInt(), 4, 0.5, 1);
double maxValue = grassNoise.getMaximumValue();
for (int x=0; x<width; x++) {
for (int y=0; y<height; y++) {
double noise = grassNoise.perlinNoise(x / 3.0, y / 3.0);
if (noise >= maxValue * map[x][y].getTerrain().admitsThickGrass(depth)) {
map[x][y].setTerrain(map[x][y].getTerrain().getThickGrass());
}
else if (noise >= maxValue * map[x][y].getTerrain().admitsThinGrass(depth)) {
map[x][y].setTerrain(map[x][y].getTerrain().getThinGrass());
}
else if (noise >= maxValue * map[x][y].getTerrain().admitsFungus(depth)) {
map[x][y].setTerrain(map[x][y].getTerrain().getMushrooms());
}
}
}
// X.
// Remove corners: .X
boolean foundOne;
do {
foundOne = false;
for (int x=0; x<width-1; x++) {
for (int y=0; y<height-1; y++) {
if (map[x][y].getTerrain().canWalkOver() && map[x+1][y+1].getTerrain().canWalkOver() &&
map[x+1][y].getTerrain().blocksMovement() && map[x][y+1].getTerrain().blocksMovement()) {
map[x+1][y].setTerrain(Terrain.RUBBLE);
map[x][y+1].setTerrain(Terrain.RUBBLE);
foundOne = true;
}
else if (map[x+1][y].getTerrain().canWalkOver() && map[x][y+1].getTerrain().canWalkOver() &&
map[x][y].getTerrain().blocksMovement() && map[x+1][y+1].getTerrain().blocksMovement()) {
map[x][y].setTerrain(Terrain.RUBBLE);
map[x+1][y+1].setTerrain(Terrain.RUBBLE);
foundOne = true;
}
}
}
}
while (foundOne);
// ######
// Remove stupid doors: ......
// ..+###
// ..####
// ..####
for (int x=1; x<width-1; x++) {
for (int y=1; y<height-1; y++) {
if (map[x][y].getTerrain() == Terrain.WOOD_DOOR) {
if (!(
map[x-1][y].getTerrain().blocksMovement() && map[x+1][y].getTerrain().blocksMovement() &&
map[x][y-1].getTerrain().canWalkOver() && map[x][y+1].getTerrain().canWalkOver() ||
map[x-1][y].getTerrain().canWalkOver() && map[x+1][y].getTerrain().canWalkOver() &&
map[x][y-1].getTerrain().blocksMovement() && map[x][y+1].getTerrain().blocksMovement()
)) {
map[x][y].setTerrain(Terrain.RUBBLE);
}
}
if (map[x][y].getTerrain().canWalkOver() && map[x+1][y+1].getTerrain().canWalkOver() &&
map[x+1][y].getTerrain().blocksMovement() && map[x][y+1].getTerrain().blocksMovement()) {
map[x+1][y].setTerrain(Terrain.RUBBLE);
map[x][y+1].setTerrain(Terrain.RUBBLE);
foundOne = true;
}
else if (map[x+1][y].getTerrain().canWalkOver() && map[x][y+1].getTerrain().canWalkOver() &&
map[x][y].getTerrain().blocksMovement() && map[x+1][y+1].getTerrain().blocksMovement()) {
map[x][y].setTerrain(Terrain.RUBBLE);
map[x+1][y+1].setTerrain(Terrain.RUBBLE);
foundOne = true;
}
}
}
// Place armor and weapons
int numberOfItems = 1+random.nextInt(3);
for (int i=0; i<numberOfItems; i++) {
Coord itemLoc = MapAnalysis.getRandomTile(map, tile -> tile.getTerrain().canWalkOver() && !tile.getTerrain().isStaircase() && tile.getTerrain() != Terrain.WOOD_DOOR && tile.getItem() == null, random);
map[itemLoc.x][itemLoc.y].setItem(random.nextBoolean() ? Weapons.getAppropriate(depth, random).make() : Armors.getAppropriate(depth, random).make());
}
// Place food
int amtFood = 1 + random.nextInt(2);
for (int i=0; i<amtFood; i++) {
Coord itemLoc = MapAnalysis.getRandomTile(map, tile -> tile.getTerrain().canWalkOver() && !tile.getTerrain().isStaircase() && tile.getTerrain() != Terrain.WOOD_DOOR && tile.getItem() == null, random);
map[itemLoc.x][itemLoc.y].setItem(Foods.getAppropriate(random).make());
}
// Place monsters
int numberOfMonsters = 5+random.nextInt(5);
for (int i=0; i<numberOfMonsters; i++) {
Coord monsterLoc = MapAnalysis.getRandomTile(map, tile -> tile.getTerrain().canWalkOver() && tile.getTerrain() != Terrain.WOOD_DOOR && tile.getEntity() == null, random);
map[monsterLoc.x][monsterLoc.y].setEntity(Entities.getAppropriate(depth, 12 + depth * 2, random).make());
}
// Place staircases
{
Coord upStaircaseLoc = MapAnalysis.getRandomTile(map, tile -> tile.getTerrain().admitsStaircase(), random);
MapTile tile = map[upStaircaseLoc.x][upStaircaseLoc.y];
tile.setTerrain(tile.getTerrain().getStaircase(false));
}
if (depth+1 != 26) {
Coord downStaircaseLoc = MapAnalysis.getRandomTile(map, tile -> tile.getTerrain().admitsStaircase(), random);
MapTile tile = map[downStaircaseLoc.x][downStaircaseLoc.y];
tile.setTerrain(tile.getTerrain().getStaircase(true));
}
else {
// On the last level, plant a sleigh.
Coord sleighLoc = MapAnalysis.getRandomTile(map, tile -> tile.getTerrain().canWalkOver() && !tile.getTerrain().isStaircase() && tile.getTerrain() != Terrain.WOOD_DOOR && tile.getItem() == null, random);
map[sleighLoc.x][sleighLoc.y].setItem(new Sleigh());
}
return map;
}
@SuppressWarnings("unused")
private void fill(MapTile[][] map, int minX, int maxX, int minY, int maxY, Terrain terrain) {
for (int x=minX; x<=maxX; x++) {
for (int y=minY; y<=maxY; y++) {
map[x][y].setTerrain(terrain);
}
}
}
@Override public int getWidth() {
return width;
}
@Override public int getHeight() {
return height;
}
}
|
package monsters;
public abstract class Monster {
private String classe;
private float defesa;
private float ataque;
private int energia;
private String terreno;
public Monster(String classe) {
super();
this.classe = classe;
}
public String getClasse() {
return classe;
}
public float getDefesa() {
return defesa;
}
public float getAtaque() {
return ataque;
}
public int getEnergia() {
return energia;
}
public String getTerreno() {
return terreno;
}
public void setDefesa(float defesa) {
this.defesa = defesa;
}
public void setAtaque(float ataque) {
this.ataque = ataque;
}
public void setEnergia(int energia) throws Exception {
if(energia>0){
this.energia = energia;
}else{
throw new Exception("Energia não pode ser nula");
}
}
public void setTerreno(String terreno) {
this.terreno = terreno;
}
public abstract String exibirInfo();
}
|
package com.hpg.demo.service;
import java.util.List;
import com.hpg.demo.bean.PostImage;
public interface PostImageService {
/**
* 插入一条用户信息
* @param user
*/
public void insertPostImage(PostImage postImage);
public List<String> getUrlByPostId(int postId);
}
|
package duke.command;
import duke.Storage;
import duke.Ui;
import duke.task.Event;
import duke.task.TaskList;
import java.time.LocalDateTime;
/**
* This class represents the Command when the user types "event" validly.
*/
public class EventCommand extends Command {
private String task;
private LocalDateTime time;
/**
* Constructor for EventCommand which takes in the task details and the time of the event.
*
* @param task task details.
* @param time time of the event.
*/
public EventCommand(String task, LocalDateTime time) {
this.task = task;
this.time = time;
}
/**
* Adds an event to the list and saves the task list.
*
* @param tasks task list
* @param storage storage
* @param ui ui
* @return output for this command.
*/
@Override
public String execute(TaskList tasks, Storage storage, Ui ui) {
Event event = new Event(task, time);
String output = tasks.add(event, true);
String saveFileString = tasks.save();
storage.save(saveFileString);
return output;
}
}
|
package br.usp.memoriavirtual.controle;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.el.ELResolver;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
import br.usp.memoriavirtual.modelo.entidades.Autor;
import br.usp.memoriavirtual.modelo.entidades.Autor.Atividade;
import br.usp.memoriavirtual.modelo.fachadas.remoto.CadastrarAutorRemote;
import br.usp.memoriavirtual.utils.MVControleMemoriaVirtual;
import br.usp.memoriavirtual.utils.MensagensDeErro;
@ManagedBean(name = "cadastrarAutorMB")
@SessionScoped
public class CadastrarAutorMB implements Serializable, BeanMemoriaVirtual {
private static final long serialVersionUID = 5784819830194641882L;
@EJB
private CadastrarAutorRemote cadastrarAutorEJB;
protected String nome = "";
protected String sobrenome = "";
protected String codinome = "";
protected Atividade atividade = Autor.Atividade.adaptador;
protected String nascimento = "";
protected String obito = "";
private MensagensMB mensagens;
public CadastrarAutorMB() {
super();
FacesContext facesContext = FacesContext.getCurrentInstance();
ELResolver resolver = facesContext.getApplication().getELResolver();
this.mensagens = (MensagensMB) resolver.getValue(
facesContext.getELContext(), null, "mensagensMB");
}
public String cadastrar() {
if (this.validar()) {
try {
Autor autor = new Autor();
autor.setAtividade(this.atividade);
autor.setCodinome(this.codinome);
autor.setNascimento(this.nascimento);
autor.setNome(this.nome);
autor.setObito(this.obito);
autor.setSobrenome(this.sobrenome);
this.cadastrarAutorEJB.cadastrarAutor(autor);
this.getMensagens().mensagemSucesso(this.traduzir("sucesso"));
this.limpar();
return this.redirecionar("/restrito/index.jsf", true);
} catch (Exception e) {
this.getMensagens().mensagemErro(this.traduzir("erroInterno"));
e.printStackTrace();
return null;
}
}
return null;
}
public String cadastroRapido(){
String resultado = this.cadastrar();
if(resultado != null && resultado.equals(this.redirecionar("/restrito/index.jsf", true))){
MensagensDeErro.getSucessMessage("sucesso", "resultado");
}
return null;
}
public String limpar() {
this.nome = "";
this.sobrenome = "";
this.codinome = "";
this.atividade = Autor.Atividade.adaptador;
this.nascimento = "";
this.obito = "";
return null;
}
public String cancelar() {
this.limpar();
return this.redirecionar("/restrito/index.jsf", true);
}
@Override
public String traduzir(String chave) {
FacesContext context = FacesContext.getCurrentInstance();
ResourceBundle bundle = context.getApplication().getResourceBundle(
context, MVControleMemoriaVirtual.bundleName);
return bundle.getString(chave);
}
@Override
public String redirecionar(String pagina, boolean redirect) {
return redirect ? pagina + "?faces-redirect=true" : pagina;
}
@Override
public boolean validar() {
boolean a = this.validarNome();
boolean b = this.validarSobrenome();
return (a && b);
}
public boolean validarNome() {
if (this.nome == null || this.nome.equals("")) {
String args[] = { this.traduzir("nome") };
MensagensDeErro.getErrorMessage("erroCampoVazio", args,
"validacao-nome");
return false;
}
return true;
}
public boolean validarSobrenome() {
if (this.sobrenome == null || this.sobrenome.equals("")) {
String args[] = { this.traduzir("sobrenome") };
MensagensDeErro.getErrorMessage("erroCampoVazio", args,
"validacao-sobrenome");
return false;
}
return true;
}
public List<SelectItem> getListaAtividade() {
List<SelectItem> opcoes = new ArrayList<SelectItem>();
for (Autor.Atividade t : Autor.Atividade.values()) {
opcoes.add(new SelectItem(t, this.traduzir(t.toString())));
}
return opcoes;
}
// getters e setters
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getSobrenome() {
return sobrenome;
}
public void setSobrenome(String sobrenome) {
this.sobrenome = sobrenome;
}
public String getCodinome() {
return codinome;
}
public void setCodinome(String codinome) {
this.codinome = codinome;
}
public Atividade getAtividade() {
return atividade;
}
public void setAtividade(Atividade atividade) {
this.atividade = atividade;
}
public String getNascimento() {
return nascimento;
}
public void setNascimento(String nascimento) {
this.nascimento = nascimento;
}
public String getObito() {
return obito;
}
public void setObito(String obito) {
this.obito = obito;
}
public MensagensMB getMensagens() {
return mensagens;
}
public void setMensagens(MensagensMB mensagens) {
this.mensagens = mensagens;
}
}
|
package switch2019.project.domain.domainEntities.ledger;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertEquals;
class PeriodicityTest {
/**
* testing if the keywords can be converted into milliseconds to be used later
*/
@Test
void convertKeyWordIntoMillisecondsDaily() {
//Arrange & Act
Periodicity periodicity = new Periodicity("daily");
int expected = 500;
int actual = periodicity.getPeriodicityInMilliseconds();
//Assert
assertEquals(expected, actual);
}
@Test
void convertKeyWordIntoMillisecondsWorkingDays() {
//Arrange & Act
Periodicity periodicity = new Periodicity("working days");
int expected = 1000;
int actual = periodicity.getPeriodicityInMilliseconds();
//Assert
assertEquals(expected, actual);
}
@Test
void convertKeyWordIntoMillisecondsWeekly() {
//Arrange & Act
Periodicity periodicity = new Periodicity("weekly");
int expected = 1500;
int actual = periodicity.getPeriodicityInMilliseconds();
//Assert
assertEquals(expected, actual);
}
@Test
void convertKeyWordIntoMillisecondsMonthly() {
//Arrange & Act
Periodicity periodicity = new Periodicity("monthly");
int expected = 2000;
int actual = periodicity.getPeriodicityInMilliseconds();
//Assert
assertEquals(expected, actual);
}
@Test
void convertKeyWordIntoMillisecondsNoMatch() {
//Arrange & Act
try {
new Periodicity("tomorrow");
}
//Assert
catch (IllegalArgumentException result) {
assertEquals("You have to choose between 'daily', 'working days', 'weekly' or 'monthly'.", result.getMessage());
}
}
}
|
package com.komdosh.yandextestapp.utils;
import com.komdosh.yandextestapp.data.dto.DictionaryDto;
import com.komdosh.yandextestapp.data.dto.TranslateDto;
import com.komdosh.yandextestapp.data.model.entity.CacheRequest;
import com.komdosh.yandextestapp.data.model.entity.CacheRequestDao;
import com.komdosh.yandextestapp.data.model.entity.DaoSession;
import java.util.Date;
import java.util.concurrent.TimeUnit;
/**
* @author komdosh
* created on 26.03.17.
*/
public class CustomCache {
private CacheRequestDao cacheRequestDao;
public CustomCache(DaoSession daoSession) {
cacheRequestDao = daoSession.getCacheRequestDao();
}
public void addOrUpdate(String textToTranslate, String langDir, TranslateDto translateDto,
DictionaryDto dictionaryDto) {
CacheRequest cacheRequest = cacheRequestDao.load(textToTranslate);
if (cacheRequest == null) {
cacheRequest = new CacheRequest(textToTranslate, langDir, translateDto, dictionaryDto, new Date());
} else {
if (translateDto != null) {
cacheRequest.setTranslateDto(translateDto);
}
if (dictionaryDto != null) {
cacheRequest.setDictionaryDto(dictionaryDto);
}
}
cacheRequestDao.insertOrReplace(cacheRequest);
}
public void update(CacheRequest cacheRequest) {
cacheRequest.setDate(new Date());
cacheRequestDao.update(cacheRequest);
}
public CacheRequest getFromCache(String textToTranslate) {
return cacheRequestDao.load(textToTranslate);
}
public void invalidateOld() {
cacheRequestDao.queryBuilder().where(CacheRequestDao.Properties.Date.le(new
Date().getTime() - TimeUnit.HOURS.toMillis(2))).buildDelete()
.executeDeleteWithoutDetachingEntities();
}
}
|
package util;
import java.util.Arrays;
public class IntList {
private int[] ns;
public IntList() {
ns = new int[0]; // ns = null;
}
public IntList(int[] numbers) {
ns = Arrays.copyOf(numbers, numbers.length);
}
public int get() {
return ns[0];
}
public int get(int index) {
return ns[index];
}
}
|
package in.zollet.abhilash.retailstore.UI;
import android.content.Intent;
import android.database.Cursor;
import android.app.LoaderManager;
import android.content.Loader;
import android.net.Uri;
import android.content.CursorLoader;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
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.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import in.zollet.abhilash.retailstore.Adapters.CartAdapter;
import in.zollet.abhilash.retailstore.Common.Utility;
import in.zollet.abhilash.retailstore.R;
import in.zollet.abhilash.retailstore.data.ProductColumns;
import in.zollet.abhilash.retailstore.data.ProductProvider;
public class CartActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<Cursor>{
private static final int CURSOR_LOADER_ID = 1;
RecyclerView recyclerView;
CartAdapter cartAdapter;
Cursor cursor;
CardView totalPriceDetailCard,totalPriceCard;
TextView productTotalPrice,productActualTotalPrice,productTotalDiscount,productPaybaleAmount,emptyText;
ImageView emptyImage;
Button checkOut;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
productTotalPrice = (TextView) findViewById(R.id.productTotalPrice);
productActualTotalPrice = (TextView) findViewById(R.id.productActualTotalPrice);
productTotalDiscount = (TextView) findViewById(R.id.productTotalDiscount);
productPaybaleAmount = (TextView) findViewById(R.id.productPaybaleAmount);
totalPriceDetailCard = (CardView) findViewById(R.id.totalPriceDetailCard);
totalPriceCard = (CardView) findViewById(R.id.totalPriceCard);
emptyText = (TextView) findViewById(R.id.emptyText);
emptyImage = (ImageView) findViewById(R.id.emptyImage);
checkOut = (Button) findViewById(R.id.checkOut);
recyclerView = (RecyclerView) findViewById(R.id.cart_recycler_view);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setLayoutManager(new LinearLayoutManager(this));
getLoaderManager().initLoader(CURSOR_LOADER_ID, null,this);
cartAdapter = new CartAdapter(this, null);
cartAdapter.setOnItemClickListener(new CartAdapter.OnItemClickListener() {
@Override
public void onClickRemove(View itemView, int position) {
cursor.moveToPosition(position);
String id = cursor.getString(cursor.getColumnIndex(ProductColumns._ID));
Uri uri = ProductProvider.Product.ID(id);
Utility.updateCount(getApplicationContext(),uri,0);
resetLoader();
}
@Override
public void onClickCard(View itemView, int position) {
cursor.moveToPosition(position);
String id = cursor.getString(cursor.getColumnIndex(ProductColumns._ID));
Uri uri = ProductProvider.Product.ID(id);
Intent detailIntent = new Intent(getApplicationContext(),ProductDetailActivity.class)
.setData(uri);
startActivity(detailIntent);
}
@Override
public void onClickAdd(View itemView, int position) {
cursor.moveToPosition(position);
String id = cursor.getString(cursor.getColumnIndex(ProductColumns._ID));
int quantity = cursor.getInt(cursor.getColumnIndex(ProductColumns.QUANTITY));
if(quantity>5){
Toast.makeText(CartActivity.this, "Reached maximum count", Toast.LENGTH_SHORT).show();
} else {
Uri uri = ProductProvider.Product.ID(id);
Utility.updateCount(getApplicationContext(), uri, quantity+1);
resetLoader();
}
}
@Override
public void onClickMinus(View itemView, int position) {
cursor.moveToPosition(position);
String id = cursor.getString(cursor.getColumnIndex(ProductColumns._ID));
int quantity = cursor.getInt(cursor.getColumnIndex(ProductColumns.QUANTITY));
Uri uri = ProductProvider.Product.ID(id);
Utility.updateCount(getApplicationContext(), uri, quantity-1);
resetLoader();
}
});
recyclerView.setAdapter(cartAdapter);
}
private void resetLoader() {
getLoaderManager().restartLoader(CURSOR_LOADER_ID, null, this);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
return new CursorLoader(this, ProductProvider.Product.CONTENT_URI, null,
ProductColumns.QUANTITY + " !=? "
, new String[]{"0"}, null);
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
int count = data.getCount();
cursor = data;
getSupportActionBar().setTitle("My Cart(" +count +")");
cartAdapter.swapCursor(data);
if(count != 0) {
Double totalPrice = 0.0;
Double payblePrice = 0.0;
Double totalDiscount = 0.0;
while (data.moveToNext()) {
int quantity = data.getInt(data.getColumnIndex(ProductColumns.QUANTITY));
Float sellingPrice = Float.valueOf(data.getString(data.getColumnIndex(ProductColumns.SELLING_PRICE)));
Float actualPrice = Float.valueOf(data.getString(data.getColumnIndex(ProductColumns.ACTUAL_PRICE)));
totalDiscount = totalDiscount + (actualPrice - sellingPrice) * quantity;
totalPrice = totalPrice + (actualPrice * quantity);
payblePrice = payblePrice + (sellingPrice * quantity);
}
productTotalPrice.setText("₹ " + String.valueOf(payblePrice));
productPaybaleAmount.setText("₹ " + String.valueOf(payblePrice));
productTotalDiscount.setText("\u002D ₹ " + String.valueOf(totalDiscount));
productActualTotalPrice.setText("₹ " + String.valueOf(totalPrice));
} else {
emptyImage.setVisibility(View.VISIBLE);
emptyText.setVisibility(View.VISIBLE);
totalPriceDetailCard.setVisibility(View.GONE);
totalPriceCard.setVisibility(View.GONE);
checkOut.setVisibility(View.GONE);
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
}
|
package org.apache.maven.plugin.deltacoverage.coverage;
import java.util.ArrayList;
import java.util.List;
public class ModuleCoverage extends AggregateCoverage {
private List<String> sources;
private List<PackageCoverage> packages = new ArrayList<PackageCoverage>();
private long timestamp = System.currentTimeMillis();
private String version = "";
public List<String> getSources() {
return sources;
}
public void setSources(List<String> sources) {
this.sources = sources;
}
public List<PackageCoverage> getPackages() {
return packages;
}
public void setPackages(List<PackageCoverage> packages) {
this.packages = packages;
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(long timestamp) {
this.timestamp = timestamp;
}
public String getVersion() {
return version;
}
public void setVersion(String version) {
this.version = version;
}
public void addPackage(PackageCoverage packageCoverage) {
if (packages == null) {
packages = new ArrayList<PackageCoverage>();
}
packages.add(packageCoverage);
}
public PackageCoverage getPackage(String name) {
if (packages != null) {
for (PackageCoverage packageCoverage : packages) {
if (packageCoverage.getName().equals(name)) {
return packageCoverage;
}
}
}
return null;
}
}
|
package com.pineapple.mobilecraft.tumcca.manager;
import android.util.Log;
import com.pineapple.mobilecraft.utils.SyncHttpPost;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by yihao on 15/6/7.
*/
public class LogManager {
/**
*
* @param level "v", "d", "e"
* @param filter 和andrid的log一致
* @param content
* @param remoteFlag 是否需要远程
*/
public static void log(String level, String filter, final String content, boolean remoteFlag){
if(level.equals("v")){
Log.v(filter, content);
}
else if(level.equals("d")){
Log.d(filter, content);
}
else if(level.equals("e")){
Log.e(filter, content);
}
else {
Log.v(filter, content);
}
if(remoteFlag){
//Thread t = new Thread(new Runnable() {
// @Override
// public void run() {
String url = "http://120.26.202.114/api/logs/android";
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("description", content);
} catch (JSONException e) {
e.printStackTrace();
}
SyncHttpPost<String> post = new SyncHttpPost<String>(url, null, jsonObject.toString()) {
@Override
public String postExcute(String result) {
return null;
}
};
post.execute();
// }
// });
// t.start();
}
}
}
|
package com.am.pertaminapps;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.am.pertaminapps.AppController.AppController;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import java.util.HashMap;
import java.util.Map;
public class Login extends AppCompatActivity {
SharedPreferences sharedPreferences;
SharedPreferences.Editor editorPreferences;
private EditText etUsername, etPassword;
private TextView tvNotifikasi;
private Button btnLogin;
private String url;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
sharedPreferences = getSharedPreferences(getResources().getString(R.string.sharedpreferences), 0);
editorPreferences = sharedPreferences.edit();
url = getResources().getString(R.string.api_endpoint).concat(getResources().getString(R.string.api_login));
tvNotifikasi = (TextView)findViewById(R.id.tv_notifikasi);
etUsername = (EditText)findViewById(R.id.et_username);
etPassword = (EditText)findViewById(R.id.et_password);
btnLogin = (Button)findViewById(R.id.btn_login);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
doLogin(etUsername.getText().toString(),etPassword.getText().toString());
}
});
}
private void doLogin(String username,String password) {
String tag_login = "request_login";
final ProgressDialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading . . . ");
pDialog.show();
final Map<String, String> params = new HashMap<String, String>();
params.put("username", username);
params.put("password", password);
JSONObject parameter = new JSONObject(params);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, url, parameter,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
pDialog.dismiss();
checkResponse(response);
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
pDialog.dismiss();
tvNotifikasi.setVisibility(View.VISIBLE);
tvNotifikasi.setText("Error : " + error.getMessage());
tvNotifikasi.setBackgroundColor(getResources().getColor(R.color.backgroundDanger));
}
});
AppController.getInstance().addToRequestQueue(jsonObjectRequest, tag_login);
}
public void checkResponse(JSONObject response){
tvNotifikasi.setVisibility(View.VISIBLE);
try{
tvNotifikasi.setText(response.getString("message"));
if(response.getString("severity").equals("success")){
tvNotifikasi.setBackgroundColor(getResources().getColor(R.color.backgroundSuccess));
Intent intent = null;
JSONArray jsonArray = response.getJSONArray("data");
JSONObject objectUser = jsonArray.getJSONObject(0);
editorPreferences.putString("pref_user_id",objectUser.getString("id"));
editorPreferences.putString("pref_user_username",objectUser.getString("username"));
editorPreferences.putString("pref_user_password",objectUser.getString("password"));
editorPreferences.putString("pref_user_full_name",objectUser.getString("user_full_name"));
editorPreferences.putString("pref_user_dob",objectUser.getString("dob"));
editorPreferences.commit();
if(objectUser.getString("user_type").equals("1")){
intent = new Intent(Login.this,DealerAdmin.class);
}else
if(objectUser.getString("user_type").equals("2")){
intent = new Intent(Login.this,UserCostumer.class);
}
startActivity(intent);
finish();
}else
if(response.getString("severity").equals("warning")){
tvNotifikasi.setBackgroundColor(getResources().getColor(R.color.backgroundWarning));
}else
if(response.getString("severity").equals("danger")){
tvNotifikasi.setBackgroundColor(getResources().getColor(R.color.backgroundDanger));
}
}catch (JSONException e){
tvNotifikasi.setBackgroundColor(getResources().getColor(R.color.backgroundDanger));
tvNotifikasi.setText(e.getMessage().toString());
}
}
@Override
public void onBackPressed(){
super.onBackPressed();
}
@Override
public void onPause() {
super.onPause();
}
@Override
public void onResume() {
super.onResume();
}
}
|
package com.devinchen.library.common.widget;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ListView;
/**
* CommonLibraryDemo
* com.devinchen.library.common.widget
* Created by Devin Chen on 2017/5/16 21:06.
* explain:
*/
public class CustomListView extends ListView {
public CustomListView(Context context) {
super(context);
}
public CustomListView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomListView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
}
|
package cn.uway.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.zip.GZIPInputStream;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.uway.task.FtpInfo;
/**
* FTP工具。
*
* @author ChenSijiang 2012-10-30
*/
public final class FTPUtil{
private static final Logger log = LoggerFactory.getLogger(FTPUtil.class);
private static FTPFileComparator ftpFileComparator = new FTPFileComparator();
public static FTPFileComparator getFTPFileComparator(){
return ftpFileComparator;
}
/**
* 登出并关闭FTP连接。
*
* @param ftp FTP连接。
* @return 未正常登出或关闭。
*/
public static boolean logoutAndCloseFTPClient(FTPClient ftp){
if(ftp == null){
log.warn("传入的FTPClient为null.");
return false;
}
boolean bOk = true;
try{
if(!ftp.logout()){
log.warn("FTP登出返回false,reply={}", ftp.getReplyString());
bOk = false;
}
}catch(IOException exLogout){
bOk = false;
log.warn("FTP登出发生异常。", exLogout);
}finally{
try{
ftp.disconnect();
}catch(IOException exClose){
bOk = false;
log.warn("FTP断开发生异常。", exClose);
}
}
return bOk;
}
/**
* FTP执行LIST命令,递归的获取文件列表。如果失败,将返回<code>null</code>. 注意,之支持一级目录有星号的递归。
*
* @param ftp FTP连接。
* @param path 路径。
* @return 文件列表。
* @throws IOException 操作失败。
*/
public static List<FTPFile> listFilesRecursive(FTPClient ftp, String path) throws IOException{
// 目录无通配符的情况,直接返回。
String parentPath = FilenameUtils.getFullPath(path);
if(!parentPath.contains("*") && !parentPath.contains("?"))
return listFiles(ftp, path);
String [] spPath = path.split("/");
String namePart = FilenameUtils.getName(path);
String wildDir = "";
List<String> parsedDirs = new ArrayList<String>();
String currFullDir = "/";
for(int i = 0; i < spPath.length; i++){
String dir = spPath[i];
if(dir == null || dir.trim().isEmpty() || dir.equals(namePart))
continue;
if(dir.contains("*") || dir.contains("?")){
wildDir = dir;
FTPFile [] dirs = ftp.listDirectories(currFullDir + "/" + wildDir);
for(FTPFile ftpDir : dirs){
if(ftpDir == null || ftpDir.getName() == null)
continue;
if(FilenameUtils.wildcardMatch(ftpDir.getName(), dir))
parsedDirs.add(ftpDir.getName());
}
break;
}else{
currFullDir += (dir + "/");
}
}
List<FTPFile> files = new ArrayList<FTPFile>();
for(int i = 0; i < parsedDirs.size(); i++){
if(parsedDirs.get(i) == null)
continue;
String oneDir = path.replace("/" + wildDir + "/", "/" + parsedDirs.get(i) + "/");
List<FTPFile> tmp = listFilesRecursive(ftp, oneDir);
if(tmp != null)
files.addAll(tmp);
}
Collections.sort(files, getFTPFileComparator());
return files;
}
/**
* FTP执行LIST命令,获取文件列表。如果失败,将返回<code>null</code>.
*
* @param ftp FTP连接。
* @param path 路径。
* @return 文件列表。
*/
public static List<FTPFile> listFiles(FTPClient ftp, String path){
if(ftp == null){
log.warn("ftp为null.");
return null;
}
if(path == null){
log.warn("path为null.");
return null;
}
FTPFile [] ftpFiles = null;
try{
ftpFiles = ftp.listFiles(path);
}catch(IOException e){
// 异常时,返回null,告知调用者listFiles失败,有可能是网络原因,可重试。
log.warn("FTP listFiles时发生异常。", e);
return null;
}
// listFiles返回null或长度为0时,可认为确实无文件,即使重试,也是一样。
// 所以此处正常返回,即返回一个长度为0的List.
if(ftpFiles == null || ftpFiles.length == 0)
return Collections.emptyList();
// 正常化文件列表, 做四个处理:
// 1、为null的FTPFile对象消除;
// 2、文件名为null的FTP对象清除;
// 3、文件名改名绝对路径;
// 4、如果不是文件,跳过。
List<FTPFile> list = new ArrayList<FTPFile>();
for(FTPFile ff : ftpFiles){
if(ff == null || ff.getName() == null || ff.getName().trim().isEmpty() || !ff.isFile())
continue;
String filename = FilenameUtils.getName(ff.getName());
String dir = FilenameUtils.getFullPath(path);
ff.setName(dir + filename);
list.add(ff);
}
Collections.sort(list, getFTPFileComparator());
return list;
}
/**
* FTP执行LIST命令,获取文件列表。如果失败,将返回<code>null</code>.
*
* @param ftp FTP连接。
* @param path 路径。
* @return 文件列表。
*/
public static List<FTPFile> list(FTPClient ftp, String path){
if(ftp == null){
log.warn("ftp为null.");
return null;
}
if(path == null){
log.warn("path为null.");
return null;
}
FTPFile [] ftpFiles = null;
try{
ftpFiles = ftp.listDirectories(path);
}catch(IOException e){
// 异常时,返回null,告知调用者listFiles失败,有可能是网络原因,可重试。
log.warn("FTP listDirectories时发生异常。", e);
return null;
}
// listFiles返回null或长度为0时,可认为确实无文件,即使重试,也是一样。
// 所以此处正常返回,即返回一个长度为0的List.
if(ftpFiles == null || ftpFiles.length == 0)
return Collections.emptyList();
List<FTPFile> list = new ArrayList<FTPFile>();
for(FTPFile ff : ftpFiles){
if(ff == null || ff.getName() == null || ff.getName().trim().isEmpty())
continue;
String filename = FilenameUtils.getName(ff.getName());
String dir = FilenameUtils.getFullPath(path);
ff.setName(dir + filename);
list.add(ff);
}
Collections.sort(list, getFTPFileComparator());
return list;
}
/**
* FTP执行LIST命令,获取文件列表。如果失败,将返回<code>null</code>.
*
* @param ftp FTP连接。
* @param path 路径。
* @return 文件列表。
*/
public static List<FTPFile> listDirectories(FTPClient ftp, String path){
if(ftp == null){
log.warn("ftp为null.");
return null;
}
if(path == null){
log.warn("path为null.");
return null;
}
FTPFile [] ftpFiles = null;
try{
ftpFiles = ftp.listDirectories(path);
}catch(IOException e){
// 异常时,返回null,告知调用者listFiles失败,有可能是网络原因,可重试。
log.warn("FTP listDirectories时发生异常。", e);
return null;
}
// listFiles返回null或长度为0时,可认为确实无文件,即使重试,也是一样。
// 所以此处正常返回,即返回一个长度为0的List.
if(ftpFiles == null || ftpFiles.length == 0)
return Collections.emptyList();
// 正常化文件列表, 做四个处理:
// 1、为null的FTPFile对象消除;
// 2、文件名为null的FTP对象清除;
// 3、文件名改名绝对路径;
// 4、如果不是文件,跳过。
List<FTPFile> list = new ArrayList<FTPFile>();
for(FTPFile ff : ftpFiles){
if(ff == null || ff.getName() == null || ff.getName().trim().isEmpty() || !ff.isDirectory())
continue;
String filename = FilenameUtils.getName(ff.getName());
String dir = FilenameUtils.getFullPath(path);
ff.setName(dir + filename);
list.add(ff);
}
Collections.sort(list, getFTPFileComparator());
return list;
}
/**
* 下载GZ文件
*
* @param filePath
* @param downLoadPath
* @param ftpClient
* @return
* @throws Exception
*/
public static File downLoadGZ(String filePath, String downLoadPath, FTPClient ftpClient) throws Exception{
String fileName = FilenameUtils.getName(filePath);
File file = null;
FileOutputStream fos = null;
GZIPInputStream inputStream = null;
try{
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
file = new File(downLoadPath, fileName);
fos = new FileOutputStream(file);
inputStream = new GZIPInputStream(ftpClient.retrieveFileStream(filePath));
int bytesWritten = 0;
int byteCount = 0;
byte [] bytes = new byte[1024];
while((byteCount = inputStream.read(bytes)) != -1){
fos.write(bytes, bytesWritten, byteCount);
bytesWritten += byteCount;
}
}catch(Exception e){
if(file != null){
file.delete();
}
file = null;
throw e;
}finally{
IoUtil.closeQuietly(fos);
IoUtil.closeQuietly(inputStream);
}
return file;
}
/**
* 下载文件
*
* @param filePath
* @param downLoadPath
* @param ftpClient
* @return
* @throws Exception
*/
public static File downLoad(String filePath, String downLoadPath, FTPClient ftpClient) throws Exception{
String fileName = FilenameUtils.getName(filePath);
File file = null;
FileOutputStream fos = null;
InputStream inputStream = null;
try{
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
file = new File(downLoadPath, fileName);
fos = new FileOutputStream(file);
inputStream = download(filePath, ftpClient);
int bytesWritten = 0;
int byteCount = 0;
byte [] bytes = new byte[1024];
while((byteCount = inputStream.read(bytes)) != -1){
fos.write(bytes, bytesWritten, byteCount);
bytesWritten += byteCount;
}
}catch(Exception e){
if(file != null){
file.delete();
}
file = null;
throw e;
}finally{
IoUtil.closeQuietly(fos);
IoUtil.closeQuietly(inputStream);
}
return file;
}
/**
* FTP 下载过程,包括重试。
*/
public static InputStream download(String ftpPath, FTPClient ftpClient){
InputStream in = retrNoEx(ftpPath, ftpClient);
if(in != null){
return in;
}
log.warn("FTP下载失败,开始重试,文件:{},reply={}", new Object[]{ftpPath,
ftpClient.getReplyString() != null ? ftpClient.getReplyString().trim() : ""});
for(int i = 0; i < 3; i++){
try{
Thread.sleep(3000);
}catch(InterruptedException e){
log.warn("FTP 下载重试过程中线程被中断。", e);
return null;
}
log.debug("第{}次重试下载。", i + 1);
completePendingCommandNoEx(ftpClient);
in = retrNoEx(ftpPath, ftpClient);
if(in != null){
log.debug("第{}次重试下载成功。", i + 1);
break;
}
}
return in;
}
/**
* FTP接收,处理异常。
*
* @param ftpPath
* @param ftpClient
* @return
*/
public static InputStream retrNoEx(String ftpPath, FTPClient ftpClient){
InputStream in = null;
try{
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
in = ftpClient.retrieveFileStream(ftpPath);
}catch(IOException e){
log.error("FTP下载异常:" + ftpPath, e);
}
return in;
}
/**
* 从FTP读取了流之后,需要读取FTP响应消息,否则下次操作时将会失败
*/
public static boolean completePendingCommandNoEx(FTPClient ftpClient){
boolean b = true;
try{
b = ftpClient.completePendingCommand();
if(!b)
log.warn("FTP失败响应:{}", ftpClient.getReplyString());
}catch(Exception e){
log.error("获取FTP响应异常。", e);
return false;
}
return b;
}
private FTPUtil(){
super();
}
private static class FTPFileComparator implements Comparator<FTPFile>{
@Override
public int compare(FTPFile o1, FTPFile o2){
if(o1 == null && o2 == null)
return 0;
if(o1 == null)
return -1;
if(o2 == null)
return 1;
String name1 = (o1.getName() != null ? o1.getName() : "");
String name2 = (o2.getName() != null ? o2.getName() : "");
return name1.compareTo(name2);
}
}
public FTPClient createFTPClient(FtpInfo ftpInfo){
FTPClient ftp = new FTPClient();
ftp.setBufferSize(ftpInfo.getBufferSize());
ftp.setRemoteVerificationEnabled(false);
int timeout = ftpInfo.getDataTimeout();
ftp.setDataTimeout(timeout * 1000);
ftp.setDefaultTimeout(timeout * 1000);
/* ftpConfig.xml中配置了此任务使用PASV模式 */
if("pasv".equals(ftpInfo.getPassiveFlag())){
ftp.enterLocalPassiveMode();
log.debug("进入FTP被动模式。ftp entering passive mode");
}else{
log.debug("进入FTP主动模式。ftp entering local mode");
}
setFTPClientConfig(ftp);
try{
ftp.setFileType(FTPClient.BINARY_FILE_TYPE);
}catch(IOException e){
log.error("设置FileType时异常", e);
}
return ftp;
}
/**
* 自动设置FTP服务器类型
*/
public static FTPClientConfig setFTPClientConfig(FTPClient ftp){
FTPClientConfig cfg = null;
try{
ftp.configure(cfg = new FTPClientConfig(FTPClientConfig.SYST_UNIX));
if(!isFilesNotNull(ftp.listFiles("/*"))){
ftp.configure(cfg = new FTPClientConfig(FTPClientConfig.SYST_NT));
}else{
log.debug("ftp type:UNIX");
return cfg;
}
if(!isFilesNotNull(ftp.listFiles("/*"))){
ftp.configure(cfg = new FTPClientConfig(FTPClientConfig.SYST_AS400));
}else{
log.debug("ftp type:NT");
return cfg;
}
if(!isFilesNotNull(ftp.listFiles("/*"))){
ftp.configure(cfg = new FTPClientConfig(FTPClientConfig.SYST_L8));
}else{
return cfg;
}
if(!isFilesNotNull(ftp.listFiles("/*"))){
ftp.configure(cfg = new FTPClientConfig(FTPClientConfig.SYST_MVS));
}else{
return cfg;
}
if(!isFilesNotNull(ftp.listFiles("/*"))){
ftp.configure(cfg = new FTPClientConfig(FTPClientConfig.SYST_NETWARE));
}else{
return cfg;
}
if(!isFilesNotNull(ftp.listFiles("/*"))){
ftp.configure(cfg = new FTPClientConfig(FTPClientConfig.SYST_OS2));
}else{
return cfg;
}
if(!isFilesNotNull(ftp.listFiles("/*"))){
ftp.configure(cfg = new FTPClientConfig(FTPClientConfig.SYST_OS400));
}else{
return cfg;
}
if(!isFilesNotNull(ftp.listFiles("/*"))){
ftp.configure(cfg = new FTPClientConfig(FTPClientConfig.SYST_VMS));
}else{
return cfg;
}
if(!isFilesNotNull(ftp.listFiles("/*"))){
ftp.configure(cfg = new FTPClientConfig(FTPClientConfig.SYST_NT));
log.debug("ftp type:NT...last");
return cfg;
}
}catch(Exception e){
log.error("配置FTP客户端时异常", e);
ftp.configure(cfg = new FTPClientConfig(FTPClientConfig.SYST_UNIX));
}
return cfg;
}
/**
* 判断listFiles出来的FTP文件,是否不是空的
*
* @param fs listFiles出来的FTP文件
* @return listFiles出来的FTP文件,是否不是空的
*/
private static boolean isFilesNotNull(FTPFile [] fs){
return isFileNotNull(fs);
}
public static boolean isFileNotNull(FTPFile [] fs){
if(fs == null){
return false;
}
if(fs.length == 0){
return false;
}
boolean b = false;
for(FTPFile f : fs){
if((f != null && StringUtil.isNotEmpty(f.getName()) && !f.getName().contains("\t"))
|| (f != null && StringUtil.isNotEmpty(f.getName()) && f.getName().contains(".loc"))){
return true;
}
}
return b;
}
/**
* FTP服务器linux默认FTP,windows默认GBK<br>
* 通过FEAT命令查看是否支持UTF8模式,如果支持则设置发送OPTS UTF8 ON命令,并返回这只UTF-8编码集<br>
* 如果不支持UTF8模式,则查看FTP服务器的系统类型<br>
* 如果是WINDOWS则默认返回GBK<br>
* 如果不是windows则默认返回UTF-8
*
* @param ftp 登陆后的FTPClient
* @return 服务端编码集
* @throws IOException
*/
public static String autoSetCharset(FTPClient ftp) throws IOException{
ftp.feat();
String replay = ftp.getReplyString();
if(replay.toUpperCase().contains("UTF8")){
ftp.sendCommand("OPTS UTF8", "ON");
return "UTF-8";
}
ftp.sendCommand("SYST");
replay = ftp.getReplyString();
if(replay.toUpperCase().contains("WINDOWS")){
return "GBK";
}
return "UTF-8";
}
public static void main(String [] args) throws Exception{
FTPClient ftp = new FTPClient();
// downLoad("/ftp/lte/unicome/华为/北京-性能/neexport_20140526/FBJ900004/A20140526.0215+0800-0230+0800_FBJ900004.xml.gz","",ftp);
// ftp.connect("ftp.hxjy.com");
ftp.connect("delivery04-mul.dhe.ibm.com");
// ftp.connect("192.168.15.223");
// ftp.login("rd", "uway_rd_good");
ftp.login("anonymous", "");
System.out.println(autoSetCharset(ftp));
// FTPFile [] listFiles = ftp.listFiles("/ftp/lte/unicome/华为");
// for(int i = 0; i < listFiles.length; i++){
// System.out.println(StringUtil.decodeFTPPath(listFiles[i].getName(), "GBK"));
// System.out.println(StringUtil.decodeFTPPath(listFiles[i].getGroup(), "GBK"));
// }
// String filePath = "/临时存放/OMR0003/ST12_17111521_02A.T";
// String filePath = "/ftp/lte/unicome/华为/北京-性能/neexport_20140526/FBJ900001/A20140526.0200+0800-0215+0800_FBJ902499.xml";
// downLoad(StringUtil.encodeFTPPath(filePath, "UTF-8"), "D:/", ftp);
// List<FTPFile> fs = listFilesRecursive(ftp, "/20*/*_1X_*.zip");
// for(FTPFile f : fs)
// System.out.println(f.getName());
}
}
|
package com.example.demo.security;
public class Roles {
public final static String USER = "ROLE_USER";
public final static String ADMIN = "ROLE_ADMIN";
}
|
package com.beiyelin.projectportal.constant;
import java.util.HashMap;
/**
* @Description: 可借款人类型
* @Author: newmannhu@qq.com
* @Date: Created in 2018-04-01 16:16
**/
public enum BorrowMoneyQualificationTypeEnum {
PERSON("个人",1),ORGANIZATION("组织",2), EMPLOYEE("员工",3);
private final int value;
private final String name;
private BorrowMoneyQualificationTypeEnum(String name, int value){
this.name = name;
this.value = value;
}
public String getName(){
return this.name;
}
public int getValue(){
return this.value;
}
public String getName(int value){
for(BorrowMoneyQualificationTypeEnum d: BorrowMoneyQualificationTypeEnum.values()){
if (d.getValue() == value) return d.getName();
}
return null;
}
public String getValueStr(){
return Integer.toString(this.value);
}
private static HashMap<Integer, BorrowMoneyQualificationTypeEnum> codeValueMap = new HashMap<>(BorrowMoneyQualificationTypeEnum.values().length);
static {
for (BorrowMoneyQualificationTypeEnum status : BorrowMoneyQualificationTypeEnum.values()) {
codeValueMap.put(status.getValue(), status);
}
}
public static BorrowMoneyQualificationTypeEnum getInstance(int value) {
return codeValueMap.get(value);
}
}
|
package com.tencent.mm.plugin.traceroute.ui;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
class NetworkDiagnoseUI$7 implements OnClickListener {
final /* synthetic */ NetworkDiagnoseUI oEe;
NetworkDiagnoseUI$7(NetworkDiagnoseUI networkDiagnoseUI) {
this.oEe = networkDiagnoseUI;
}
public final void onClick(DialogInterface dialogInterface, int i) {
NetworkDiagnoseUI.e(this.oEe);
this.oEe.finish();
}
}
|
package WinGame;
import java.util.ArrayList;
public class TestClass {
// Declaring Class Variables
static ArrayList<Square> Board = new ArrayList<>();
static Square winSquare = new Square("BFTB", 0);
static Square square1 = new Square("Square", 1);
static ArrayList<Biome> Biomes = new ArrayList<>();
static Biome biome1 = new Biome("Aquatic");
public static void main(String[] args) {
// Adding winSquare and and 'normal' square to board instance
Board.add(winSquare);
Board.add(square1);
// Initialising player and piece objects
Piece piece = new Piece("Boat", 0);
Player player = new Player("Joe Doe");
player.setPiece(piece);
// Add biome instance to Biomes arraylist
Biomes.add(biome1);
player.setBiomes(Biomes);
player.setMaterial(100);
// Print player, Biomes, materials
System.out.println("Player: " + player.getName() + "\nAt Position: " + Board.get(player.getPiece().getPos()).getName());
System.out.println("Biomes: ");
for (int i = 0; i < player.getBiomes().size(); i++)
System.out.println(i+1 + ") " + player.getBiomes().get(i).getName());
System.out.println("Materials: " + player.getMaterial());
// Conditional for winning
if (checkWin(player))
System.out.println("Congratulations! You win!!");
else System.out.println("Insufficient resources to win.");
}
// Checks if player has enough biomes and materials to win
public static boolean checkWin(Player player)
{
if (player.getBiomes().size() > 0 && player.getMaterial() >= 1000)
return true;
else return false;
}
}
|
package de.fhg.iais.roberta.visitor.validate;
import com.google.common.collect.ClassToInstanceMap;
import de.fhg.iais.roberta.bean.IProjectBean;
import de.fhg.iais.roberta.components.ConfigurationAst;
import de.fhg.iais.roberta.components.ConfigurationComponent;
import de.fhg.iais.roberta.syntax.Phrase;
import de.fhg.iais.roberta.syntax.SC;
import de.fhg.iais.roberta.syntax.actors.arduino.LEDMatrixImageAction;
import de.fhg.iais.roberta.syntax.actors.arduino.LEDMatrixSetBrightnessAction;
import de.fhg.iais.roberta.syntax.actors.arduino.LEDMatrixTextAction;
import de.fhg.iais.roberta.syntax.actors.arduino.mbot.ReceiveIRAction;
import de.fhg.iais.roberta.syntax.actors.arduino.mbot.SendIRAction;
import de.fhg.iais.roberta.syntax.expressions.arduino.LEDMatrixImage;
import de.fhg.iais.roberta.syntax.functions.arduino.LEDMatrixImageInvertFunction;
import de.fhg.iais.roberta.syntax.functions.arduino.LEDMatrixImageShiftFunction;
import de.fhg.iais.roberta.syntax.sensor.ExternalSensor;
import de.fhg.iais.roberta.syntax.sensor.generic.IRSeekerSensor;
import de.fhg.iais.roberta.syntax.sensor.generic.LightSensor;
import de.fhg.iais.roberta.typecheck.NepoInfo;
import de.fhg.iais.roberta.visitor.hardware.IMbotVisitor;
public class MbotSimValidatorVisitor extends AbstractSimValidatorVisitor implements IMbotVisitor<Void> {
public MbotSimValidatorVisitor(ConfigurationAst brickConfiguration, ClassToInstanceMap<IProjectBean.IBuilder<?>> beanBuilders) {
super(brickConfiguration, beanBuilders);
}
@Override
public Void visitIRSeekerSensor(IRSeekerSensor<Void> irSeekerSensor) {
irSeekerSensor.addInfo(NepoInfo.warning("SIM_BLOCK_NOT_SUPPORTED"));
return null;
}
@Override
public Void visitLightSensor(LightSensor<Void> lightSensor) {
lightSensor.addInfo(NepoInfo.warning("SIM_BLOCK_NOT_SUPPORTED"));
return null;
}
@Override
public Void visitSendIRAction(SendIRAction<Void> sendIRAction) {
sendIRAction.addInfo(NepoInfo.warning("SIM_BLOCK_NOT_SUPPORTED"));
return null;
}
@Override
public Void visitReceiveIRAction(ReceiveIRAction<Void> receiveIRAction) {
receiveIRAction.addInfo(NepoInfo.warning("SIM_BLOCK_NOT_SUPPORTED"));
return null;
}
@Override
protected void checkDiffDrive(Phrase<Void> driveAction) {
checkLeftRightMotorPortMbed(driveAction);
}
private void checkLeftRightMotorPortMbed(Phrase<Void> driveAction) {
if ( validNumberOfMotors(driveAction) ) {
ConfigurationComponent leftMotor = this.robotConfiguration.getFirstMotor(SC.LEFT);
ConfigurationComponent rightMotor = this.robotConfiguration.getFirstMotor(SC.RIGHT);
if ( leftMotor == null ) {
driveAction.addInfo(NepoInfo.error("CONFIGURATION_ERROR_MOTOR_LEFT_MISSING"));
this.errorCount++;
if ( rightMotor == null ) {
driveAction.addInfo(NepoInfo.error("CONFIGURATION_ERROR_MOTOR_RIGHT_MISSING"));
this.errorCount++;
}
}
}
}
@Override
protected void checkSensorPort(ExternalSensor<Void> sensor) {
ConfigurationComponent usedSensor = this.robotConfiguration.optConfigurationComponent("ORT_" + sensor.getUserDefinedPort());
if ( usedSensor == null ) {
if ( sensor.getKind().hasName("INFRARED_SENSING") ) {
sensor.addInfo(NepoInfo.warning("SIM_CONFIGURATION_WARNING_WRONG_INFRARED_SENSOR_PORT"));
} else {
sensor.addInfo(NepoInfo.warning("SIM_CONFIGURATION_WARNING_SENSOR_MISSING"));
}
} else {
String type = usedSensor.getComponentType();
switch ( sensor.getKind().getName() ) {
case "COLOR_SENSING":
if ( !type.equals("COLOR") && !type.equals("HT_COLOR") ) {
sensor.addInfo(NepoInfo.warning("SIM_CONFIGURATION_WARNING_WRONG_SENSOR_PORT"));
}
break;
case "TOUCH_SENSING":
if ( !type.equals("TOUCH") ) {
sensor.addInfo(NepoInfo.warning("SIM_CONFIGURATION_WARNING_WRONG_SENSOR_PORT"));
}
break;
case "ULTRASONIC_SENSING":
if ( !type.equals("ULTRASONIC") ) {
sensor.addInfo(NepoInfo.warning("SIM_CONFIGURATION_WARNING_WRONG_SENSOR_PORT"));
}
break;
case "INFRARED_SENSING":
if ( !type.equals("INFRARED") ) {
sensor.addInfo(NepoInfo.warning("SIM_CONFIGURATION_WARNING_WRONG_INFRARED_SENSOR_PORT"));
}
break;
case "GYRO_SENSING":
if ( !type.equals("GYRO") ) {
sensor.addInfo(NepoInfo.warning("SIM_CONFIGURATION_WARNING_WRONG_SENSOR_PORT"));
}
break;
case "COMPASS_SENSING":
if ( !type.equals("COMPASS") ) {
sensor.addInfo(NepoInfo.warning("SIM_CONFIGURATION_WARNING_WRONG_SENSOR_PORT"));
}
break;
case "IRSEEKER_SENSING":
if ( !type.equals("IRSEEKER_SENSING") ) {
sensor.addInfo(NepoInfo.warning("SIM_CONFIGURATION_WARNING_WRONG_SENSOR_PORT"));
}
break;
default:
break;
}
}
}
//TODO Implement validation for LED Matrix
@Override
public Void visitLEDMatrixImageAction(LEDMatrixImageAction<Void> ledMatrixImageAction) {
return null;
}
@Override
public Void visitLEDMatrixTextAction(LEDMatrixTextAction<Void> ledMatrixTextAction) {
return null;
}
@Override
public Void visitLEDMatrixImage(LEDMatrixImage<Void> ledMatrixImage) {
return null;
}
@Override
public Void visitLEDMatrixImageShiftFunction(LEDMatrixImageShiftFunction<Void> ledMatrixImageShiftFunction) {
return null;
}
@Override
public Void visitLEDMatrixImageInvertFunction(LEDMatrixImageInvertFunction<Void> ledMatrixImageInverFunction) {
return null;
}
@Override
public Void visitLEDMatrixSetBrightnessAction(LEDMatrixSetBrightnessAction<Void> ledMatrixSetBrightnessAction) {
return null;
}
}
|
package top.kylewang.bos.service.transit.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.kylewang.bos.dao.transit.SignInfoRepository;
import top.kylewang.bos.dao.transit.TransitRepository;
import top.kylewang.bos.domain.transit.SignInfo;
import top.kylewang.bos.domain.transit.TransitInfo;
import top.kylewang.bos.index.WayBillIndexRepository;
import top.kylewang.bos.service.transit.SignInfoService;
/**
* @author Kyle.Wang
* 2018/1/13 0013 17:08
*/
@Service
@Transactional(rollbackFor = Exception.class)
public class SignInfoServiceImpl implements SignInfoService {
@Autowired
private SignInfoRepository signInfoRepository;
@Autowired
private TransitRepository transitRepository;
@Autowired
private WayBillIndexRepository wayBillIndexRepository;
@Override
public void save(String transitInfoId, SignInfo signInfo) {
// 保存出入库信息
signInfoRepository.save(signInfo);
// 保存运单信息
TransitInfo transitInfo = transitRepository.findOne(Integer.parseInt(transitInfoId));
transitInfo.setSignInfo(signInfo);
// 修改状态
if(signInfo.getSignType().equals("正常")){
transitInfo.setStatus("正常签收");
transitInfo.getWayBill().setSignStatus(3);
wayBillIndexRepository.save(transitInfo.getWayBill());
}else{
transitInfo.setStatus("异常");
transitInfo.getWayBill().setSignStatus(4);
wayBillIndexRepository.save(transitInfo.getWayBill());
}
}
}
|
package com.cimcssc.chaojilanling;
import android.content.Intent;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.List;
public class LoadingActivity extends AppCompatActivity {
/**
* ViewPager展示引导页内容
*/
private ViewPager mPager;
/**
* 引导页显示内容的View
*/
private View mView1, mView2, mView3;
/**
* 下方状态图
*/
private ImageView mPage0, mPage1, mPage2;
/**
* 存放显示内容的View
*/
private List<View> mViews = new ArrayList<View>();
private Button startButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_loading);
/**
* 全屏显示
*/
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
/**
* 获取要显示的引导页内容
*/
mView1 = LayoutInflater.from(this).inflate(R.layout.guide_activity_page1, null);
mView2 = LayoutInflater.from(this).inflate(R.layout.guide_activity_page2, null);
mView3 = LayoutInflater.from(this).inflate(R.layout.guide_activity_page3, null);
mPage0 = (ImageView) findViewById(R.id.page0);
mPage1 = (ImageView) findViewById(R.id.page1);
mPage2 = (ImageView) findViewById(R.id.page2);
findViewById();
/**
* 添加View
*/
mViews.add(mView1);
mViews.add(mView2);
mViews.add(mView3);
/**
* ViewPager设置适配器
*/
mPager.setAdapter(new ViewPagerAdapter());
mPager.setOnPageChangeListener(new MyOnPageChangeListener());
}
/**
* 绑定界面UI
*/
private void findViewById() {
mPager = (ViewPager) findViewById(R.id.guide_activity_viewpager);
startButton = (Button) mView3.findViewById(R.id.start_button);
startButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
finish();
}
});
}
/**
* ViewPager适配器
*
* @author 00012741
*/
private class ViewPagerAdapter extends PagerAdapter {
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView(mViews.get(arg1));
}
public void finishUpdate(View arg0) {
}
public int getCount() {
return mViews.size();
}
public Object instantiateItem(View arg0, int arg1) {
((ViewPager) arg0).addView(mViews.get(arg1));
return mViews.get(arg1);
}
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
public void restoreState(Parcelable arg0, ClassLoader arg1) {
}
public Parcelable saveState() {
return null;
}
public void startUpdate(View arg0) {
}
}
public class MyOnPageChangeListener implements ViewPager.OnPageChangeListener {
public void onPageSelected(int page) {
// 翻页时当前page,改变当前状态园点图片
switch (page) {
case 0:
mPage0.setImageDrawable(getResources().getDrawable(R.mipmap.blue_dot));
mPage1.setImageDrawable(getResources().getDrawable(R.mipmap.white_dot));
break;
case 1:
mPage1.setImageDrawable(getResources().getDrawable(R.mipmap.blue_dot));
mPage0.setImageDrawable(getResources().getDrawable(R.mipmap.white_dot));
mPage2.setImageDrawable(getResources().getDrawable(R.mipmap.white_dot));
break;
case 2:
mPage2.setImageDrawable(getResources().getDrawable(R.mipmap.blue_dot));
mPage1.setImageDrawable(getResources().getDrawable(R.mipmap.white_dot));
break;
}
}
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
public void onPageScrollStateChanged(int arg0) {
}
}
}
|
package pe.gob.trabajo.web.rest;
import com.codahale.metrics.annotation.Timed;
import pe.gob.trabajo.domain.Bensocial;
import pe.gob.trabajo.repository.BensocialRepository;
import pe.gob.trabajo.repository.search.BensocialSearchRepository;
import pe.gob.trabajo.web.rest.util.HeaderUtil;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import static org.elasticsearch.index.query.QueryBuilders.*;
/**
* REST controller for managing Bensocial.
*/
@RestController
@RequestMapping("/api")
public class BensocialResource {
private final Logger log = LoggerFactory.getLogger(BensocialResource.class);
private static final String ENTITY_NAME = "bensocial";
private final BensocialRepository bensocialRepository;
private final BensocialSearchRepository bensocialSearchRepository;
public BensocialResource(BensocialRepository bensocialRepository, BensocialSearchRepository bensocialSearchRepository) {
this.bensocialRepository = bensocialRepository;
this.bensocialSearchRepository = bensocialSearchRepository;
}
/**
* POST /bensocials : Create a new bensocial.
*
* @param bensocial the bensocial to create
* @return the ResponseEntity with status 201 (Created) and with body the new bensocial, or with status 400 (Bad Request) if the bensocial has already an ID
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@PostMapping("/bensocials")
@Timed
public ResponseEntity<Bensocial> createBensocial(@Valid @RequestBody Bensocial bensocial) throws URISyntaxException {
log.debug("REST request to save Bensocial : {}", bensocial);
if (bensocial.getId() != null) {
return ResponseEntity.badRequest().headers(HeaderUtil.createFailureAlert(ENTITY_NAME, "idexists", "A new bensocial cannot already have an ID")).body(null);
}
Bensocial result = bensocialRepository.save(bensocial);
bensocialSearchRepository.save(result);
return ResponseEntity.created(new URI("/api/bensocials/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
.body(result);
}
/**
* PUT /bensocials : Updates an existing bensocial.
*
* @param bensocial the bensocial to update
* @return the ResponseEntity with status 200 (OK) and with body the updated bensocial,
* or with status 400 (Bad Request) if the bensocial is not valid,
* or with status 500 (Internal Server Error) if the bensocial couldn't be updated
* @throws URISyntaxException if the Location URI syntax is incorrect
*/
@PutMapping("/bensocials")
@Timed
public ResponseEntity<Bensocial> updateBensocial(@Valid @RequestBody Bensocial bensocial) throws URISyntaxException {
log.debug("REST request to update Bensocial : {}", bensocial);
if (bensocial.getId() == null) {
return createBensocial(bensocial);
}
Bensocial result = bensocialRepository.save(bensocial);
bensocialSearchRepository.save(result);
return ResponseEntity.ok()
.headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, bensocial.getId().toString()))
.body(result);
}
/**
* GET /bensocials : get all the bensocials.
*
* @return the ResponseEntity with status 200 (OK) and the list of bensocials in body
*/
@GetMapping("/bensocials")
@Timed
public List<Bensocial> getAllBensocials() {
log.debug("REST request to get all Bensocials");
return bensocialRepository.findAll();
}
/**
* GET /bensocials/:id : get the "id" bensocial.
*
* @param id the id of the bensocial to retrieve
* @return the ResponseEntity with status 200 (OK) and with body the bensocial, or with status 404 (Not Found)
*/
@GetMapping("/bensocials/{id}")
@Timed
public ResponseEntity<Bensocial> getBensocial(@PathVariable Long id) {
log.debug("REST request to get Bensocial : {}", id);
Bensocial bensocial = bensocialRepository.findOne(id);
return ResponseUtil.wrapOrNotFound(Optional.ofNullable(bensocial));
}
/** JH
* GET /bensocials/activos : get all the bensocials.
*
* @return the ResponseEntity with status 200 (OK) and the list of bensocials in body
*/
@GetMapping("/bensocials/activos")
@Timed
public List<Bensocial> getAll_Activos() {
log.debug("REST request to get all bensocials");
return bensocialRepository.findAll_Activos();
}
/**
* DELETE /bensocials/:id : delete the "id" bensocial.
*
* @param id the id of the bensocial to delete
* @return the ResponseEntity with status 200 (OK)
*/
@DeleteMapping("/bensocials/{id}")
@Timed
public ResponseEntity<Void> deleteBensocial(@PathVariable Long id) {
log.debug("REST request to delete Bensocial : {}", id);
bensocialRepository.delete(id);
bensocialSearchRepository.delete(id);
return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
}
/**
* SEARCH /_search/bensocials?query=:query : search for the bensocial corresponding
* to the query.
*
* @param query the query of the bensocial search
* @return the result of the search
*/
@GetMapping("/_search/bensocials")
@Timed
public List<Bensocial> searchBensocials(@RequestParam String query) {
log.debug("REST request to search Bensocials for query {}", query);
return StreamSupport
.stream(bensocialSearchRepository.search(queryStringQuery(query)).spliterator(), false)
.collect(Collectors.toList());
}
}
|
package task3;
/*NewThread implements Runnable {
public void run() {
try {
for(int i=5;i>0;i++) {
System.out.println("child thread:"+i);
Thread.Sleep(600);
}
}catch(InterruptedException e) {
System.out.println("child interrupted");
}
System.out.println("exiting child thread");
}*/
//}
public class ExtendThread {
public static void main(String[] args) throws InterruptedException {
// TODO Auto-generated method stub
NewThread t=new NewThread();
t.setName("Demo Thread");
System.out.println("child thread:"+t);
t.start();
try {
for(int i=5;i>0;i--) {
System.out.println("Main thread:"+i);
Thread.sleep(300);
}
}catch(InterruptedException e){
System.out.println("main thread interrupted");
}
System.out.println("main thread exiting");
}
}
|
package server.rmi;
import Domain.DTO.AzioneBonusDTO;
import Domain.DTO.PiazzaFamiliareDTO;
import Domain.Risorsa;
import Exceptions.DomainException;
import rmi.IRMIClient;
import server.AbstractServer;
import server.GiocatoreRemoto;
import server.Server;
import java.awt.*;
import java.io.IOException;
import java.rmi.AlreadyBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
/**
* Created by Portatile on 19/05/2017.
*/
public class RMIServer extends AbstractServer implements IRMIServer {
/**
* Costruttore
*/
public RMIServer(Server server)
{
super(server);
}
/**
* Avvia il server rmi
*/
@Override
public void StartServer(int porta) throws Exception {
Registry registro = creaCaricaRegistro(porta);
try {
registro.bind("IRMIServer", this);
UnicastRemoteObject.exportObject(this, porta);
} catch (RemoteException e) {
e.printStackTrace();
} catch (AlreadyBoundException e) {
e.printStackTrace();
}
}
/**
* Se non è ancora stato creato, crea il registro.
* Altrimenti prova a ritornare il registro creato in precedenza.
*/
private Registry creaCaricaRegistro(int porta) throws Exception {
try {
return LocateRegistry.createRegistry(porta);
} catch (RemoteException e) {
//Il registro è già stato creato
}
try {
return LocateRegistry.getRegistry(porta);
} catch (RemoteException e) {
throw new Exception("Impossibile avviare il registro rmi");
}
}
/**
* Ottiene il giocatore dato l'id
*/
private GiocatoreRemoto GetGiocatoreById(short idGiocatore)
{
return getServer().GetGiocatoreById(idGiocatore);
}
/**
* Effettua il login del giocatore
* Salva anche il riferimento per chiamare i metodi lato client attraverso rmi
*/
@Override
public short Login(String nome, IRMIClient rmiClient) throws DomainException {
return getServer().AggiungiGiocatore(nome, new GiocatoreRMI(rmiClient));
}
/**
* Se è stato raggiunto il limite massimo di giocatori la partita inizia automaticamente
*/
@Override
public void VerificaInizioAutomatico(short idGiocatore) throws DomainException {
GetGiocatoreById(idGiocatore).getPartita().VerificaInizioAutomatico();
}
/**
* Inizia una nuova partita
*/
@Override
public void IniziaPartita(short idGiocatore) throws DomainException {
GetGiocatoreById(idGiocatore).getPartita().IniziaPartita();
}
/**
* Gestisce la risposta del client alla domanda sul sostegno della chiesa
* @param risposta true se sostiene, con false il giocatore viene scomunicato
*/
@Override
public void RispostaSostegnoChiesa(short idGiocatore, Boolean risposta) {
GiocatoreRemoto giocatoreRemoto = GetGiocatoreById(idGiocatore);
giocatoreRemoto.getPartita().RispostaSostegnoChiesa(giocatoreRemoto, risposta);
}
/**
* Evento scatenato dal client per comunicare l'intenzione di piazzare un familiare nello spazio azione specificato
* @param idGiocatore id del giocatore che ha effettuato la chiamata
* @param piazzaFamiliareDTO parametri relativi al piazzamento del familiare
*/
@Override
public void PiazzaFamiliare(short idGiocatore, PiazzaFamiliareDTO piazzaFamiliareDTO) throws IOException {
GetGiocatoreById(idGiocatore).getPartita().PiazzaFamiliare(idGiocatore, piazzaFamiliareDTO);
}
/**
* Evento scatenato dal client per comunicare l'intenzione di effettuare un'azione bonus
* @param idGiocatore id del giocatore che ha effettuato la chiamata
* @param azioneBonusDTO parametri relativi all'azione bonus
*/
@Override
public void AzioneBonusEffettuata(short idGiocatore, AzioneBonusDTO azioneBonusDTO) throws IOException{
GetGiocatoreById(idGiocatore).getPartita().AzioneBonusEffettuata(idGiocatore, azioneBonusDTO);
}
/**
* Evento scatenato dal client quando l'utente salta l'azione bonus
* @param idGiocatore id del giocatore che ha effettuato la chiamata
*/
@Override
public void AzioneBonusSaltata(short idGiocatore) throws IOException{
GiocatoreRemoto giocatoreRemoto = GetGiocatoreById(idGiocatore);
giocatoreRemoto.setAzioneBonusDaEffettuare(false);
giocatoreRemoto.getPartita().AzioneBonusSaltata();
}
/**
* Gestisce l'evento di riscossione del privilegio del consiglio
* @param risorsa risorse da aggiungere al giocatore
*/
@Override
public void RiscuotiPrivilegiDelConsiglio(short idGiocatore, Risorsa risorsa) throws IOException {
GetGiocatoreById(idGiocatore).getPartita().RiscuotiPrivilegiDelConsiglio(idGiocatore, risorsa);
}
/**
* Gestisce l'evento di scelta dell'effetto di default da attivare per le carte con scambia risorse
* @param nomeCarta nome della carta alla quale impostare la scelta
* @param sceltaEffetto indidce della scelta effettuata
*/
@Override
public void SettaSceltaEffetti(short idGiocatore, String nomeCarta, Integer sceltaEffetto) throws IOException
{
GiocatoreRemoto giocatoreRemoto = GetGiocatoreById(idGiocatore);
giocatoreRemoto.getPartita().getTabellone().SettaSceltaEffetti(giocatoreRemoto, nomeCarta, sceltaEffetto);
}
/**
* Gestisce l'evento di chiusura di un client
*/
@Override
public void NotificaChiusuraClient(short idGiocatore) throws IOException
{
GetGiocatoreById(idGiocatore).NotificaChiusuraClient();
}
}
|
package org.incredible.certProcessor.views;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.incredible.pojos.CertificateExtension;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class HTMLVarResolver {
private CertificateExtension certificateExtension;
public HTMLVarResolver(CertificateExtension certificateExtension) {
this.certificateExtension = certificateExtension;
}
private ObjectMapper mapper = new ObjectMapper();
public String getRecipient() {
return certificateExtension.getRecipient().getName();
}
public String getCourse() {
return certificateExtension.getBadge().getName();
}
public String getImg() {
return certificateExtension.getId().split("Certificate/")[1] + ".png";
}
public String getTitle() {
return "certificate";
}
public String getDated() {
return certificateExtension.getIssuedOn();
}
public String getDateInFormatOfWords() {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
String dateInFormat;
try {
Date parsedIssuedDate = simpleDateFormat.parse(certificateExtension.getIssuedOn());
DateFormat format = new SimpleDateFormat("dd MMMM yyy");
format.format(parsedIssuedDate);
dateInFormat = format.format(parsedIssuedDate);
return dateInFormat;
} catch (ParseException e) {
e.printStackTrace();
return null;
}
}
// public String getSignatoryName() {
// return certificateExtension.getSignatory()[1].getName();
// }
//
// public String getSignatory() {
// return certificateExtension.getSignatory()[1].getId();
// }
}
|
package com.tencent.mm.plugin.label.ui;
import com.tencent.mm.sdk.e.j.a;
import com.tencent.mm.sdk.e.l;
import com.tencent.mm.sdk.platformtools.bi;
class ContactLabelManagerUI$7 implements a {
final /* synthetic */ ContactLabelManagerUI kBk;
ContactLabelManagerUI$7(ContactLabelManagerUI contactLabelManagerUI) {
this.kBk = contactLabelManagerUI;
}
public final void a(String str, l lVar) {
if (!bi.oW(str)) {
ContactLabelManagerUI.a(this.kBk);
}
}
}
|
package Metodos;
import java.util.ArrayList;//importamos para utilizar el Arraylist
import java.util.Collections;
public class Array {
ArrayList<Valores> arreglo;//creamos un atributo que se llame arreglo y que sea un aarylist de tipo persona
public Array() {
arreglo = new ArrayList<Valores>();//en el constructor instanciamos el atributo arreglo para utilizarlo en un nuevo arraylist
}
public void adicionar(Valores p) {//con este metodo podemos adicionar un objeto de tipo persona a nuestro array list
arreglo.add(p);
}
public Valores obtenerposcion(int posicion) {//con este metodo obtenemos la posicion
return arreglo.get(posicion);
}
public int tamaño() {//y con este el tama�o en numero del arraylist
return arreglo.size();
}
public void BorrarTodo() {//con este borramos todos los datos del Array
arreglo.removeAll(arreglo);
}
public void Ordenar(){// con este ordenamos el array
Collections.sort(arreglo);
}
}
|
package com.tencent.mm.plugin.backup.e;
import android.text.TextUtils;
import com.tencent.mm.a.e;
import com.tencent.mm.kernel.g;
import com.tencent.mm.plugin.backup.g.c;
import com.tencent.mm.plugin.backup.g.d;
import com.tencent.mm.plugin.backup.h.u;
import com.tencent.mm.protocal.c.bhz;
import com.tencent.mm.protocal.c.ey;
import com.tencent.mm.sdk.platformtools.bi;
import com.tencent.mm.sdk.platformtools.bl;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.storage.an;
import com.tencent.mm.storage.ap;
import com.tencent.mm.storage.bd;
import com.tencent.mm.storage.emotion.EmojiInfo;
import java.io.File;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import org.xmlpull.v1.XmlPullParserFactory;
import org.xmlpull.v1.XmlSerializer;
public final class b implements l {
private static class a {
public static String gVL = "<msg>";
public static String gVM = "</msg>";
public static String wC(String str) {
com.tencent.mm.plugin.backup.e.k.a wD = k.wD(str);
return wD == null ? null : wD.gWj;
}
public static String a(bd bdVar, ey eyVar) {
EmojiInfo Zy = d.asG().asH().asE().Zy(bdVar.field_imgPath);
if (Zy == null) {
return null;
}
com.tencent.mm.plugin.backup.e.k.a wE = k.wE(Zy.Xh());
if (wE == null) {
wE = new com.tencent.mm.plugin.backup.e.k.a(Zy.Xh(), Zy.Xh(), Zy.Xh(), Zy.Xh());
}
Writer stringWriter = new StringWriter();
try {
String aG;
XmlSerializer newSerializer = XmlPullParserFactory.newInstance().newSerializer();
newSerializer.setOutput(stringWriter);
newSerializer.startDocument("UTF-8", Boolean.valueOf(true));
newSerializer.startTag(null, "msg");
newSerializer.startTag(null, "emoji");
newSerializer.attribute(null, "fromusername", eyVar.rcj.siM);
newSerializer.attribute(null, "tousername", eyVar.rck.siM);
newSerializer.attribute(null, "type", Zy.field_type);
newSerializer.attribute(null, "idbuffer", Zy.cnC());
newSerializer.attribute(null, "md5", wE.gWk);
newSerializer.attribute(null, "len", "1024");
newSerializer.attribute(null, "androidmd5", wE.gWj);
newSerializer.attribute(null, "androidlen", "1024");
newSerializer.attribute(null, "productid", Zy.field_groupId);
newSerializer.endTag(null, "emoji");
if (Zy.aaq()) {
newSerializer.startTag(null, "gameext");
Map z = bl.z(Zy.getContent(), "gameext");
String aG2 = bi.aG((String) z.get(".gameext.$type"), "");
aG = bi.aG((String) z.get(".gameext.$content"), "");
if (aG2.equals("") || aG.equals("")) {
stringWriter.close();
return "";
}
newSerializer.attribute(null, "type", aG2);
newSerializer.attribute(null, "content", aG);
newSerializer.endTag(null, "gameext");
}
newSerializer.endTag(null, "msg");
newSerializer.endDocument();
stringWriter.flush();
stringWriter.close();
aG = stringWriter.getBuffer().toString();
try {
aG = aG.substring(aG.indexOf(gVL), aG.indexOf(gVM) + gVM.length());
x.d("MicroMsg.EmojiConvert", "xml " + aG);
return aG;
} catch (Exception e) {
return "";
}
} catch (Throwable e2) {
x.printErrStackTrace("MicroMsg.EmojiConvert", e2, "", new Object[0]);
return "";
} catch (Throwable e22) {
x.printErrStackTrace("MicroMsg.EmojiConvert", e22, "", new Object[0]);
return "";
} catch (Throwable e222) {
x.printErrStackTrace("MicroMsg.EmojiConvert", e222, "", new Object[0]);
return "";
} catch (Throwable e2222) {
x.printErrStackTrace("MicroMsg.EmojiConvert", e2222, "", new Object[0]);
return "";
}
}
}
private static boolean wx(String str) {
int indexOf = str.indexOf(60);
if (indexOf > 0) {
str = str.substring(indexOf);
}
return bl.z(str, "msg") != null;
}
public final int a(ey eyVar, boolean z, bd bdVar, String str, LinkedList<u> linkedList, HashMap<Long, com.tencent.mm.plugin.backup.e.h.a> hashMap, boolean z2, long j) {
int i;
if (bi.oW(bdVar.field_content)) {
i = 0;
} else {
i = bdVar.field_content.getBytes().length;
}
String trim = an.YJ(bdVar.field_content).taT.trim();
if (!wx(trim)) {
trim = bdVar.field_content;
if (!wx(trim)) {
trim = a.a(bdVar, eyVar);
if (bdVar.field_isSend != 1 && c.fq(bdVar.field_talker)) {
trim = bdVar.field_talker + " :\n " + trim;
}
}
}
if (trim == null || !wx(trim)) {
x.d("MicroMsg.BackupItemEmoji", "emoji error" + trim);
return -1;
}
bhz bhz = new bhz();
bhz.VO(bi.aG(trim, ""));
eyVar.rcl = bhz;
EmojiInfo Zy = d.asG().asH().asE().Zy(bdVar.field_imgPath);
if ((Zy != null && Zy.cny()) || Zy == null) {
return i;
}
String str2;
if (TextUtils.isEmpty(Zy.field_groupId)) {
str2 = d.asG().asH().Gg() + Zy.Xh() + "_thumb";
if (e.cm(str2) < 0) {
x.e("MicroMsg.BackupItemEmoji", "thumbPath error");
return -1;
}
i = i.a(new i$a(str2, eyVar, (LinkedList) linkedList, 4, z, "_thumb", z2)) + i;
} else {
str2 = d.asG().asH().Gg() + Zy.field_groupId + File.separator + Zy.Xh() + "_cover";
if (e.cm(str2) < 0) {
x.e("MicroMsg.BackupItemEmoji", "thumbPath error");
return -1;
}
i = i.a(new i$a(str2, eyVar, (LinkedList) linkedList, 4, z, "_thumb", z2)) + i;
}
if (TextUtils.isEmpty(Zy.field_groupId) && Zy.cnv()) {
return i + i.a(new i$a(d.asG().asH().Gg() + Zy.Xh(), eyVar, (LinkedList) linkedList, 5, z, z2, null));
} else if (!Zy.cnx()) {
return i;
} else {
return i + i.a(new i$a(d.asG().asH().Gg() + Zy.field_groupId + File.separator + Zy.Xh(), eyVar, (LinkedList) linkedList, 5, z, z2, null));
}
}
public final int a(String str, ey eyVar, bd bdVar) {
boolean z = true;
bdVar.setContent(eyVar.rcl.siM);
String str2 = eyVar.rcj.siM;
String str3 = eyVar.rck.siM;
if (!((String) d.asG().asH().DT().get(2, null)).equals(str2)) {
str3 = str2;
}
str2 = eyVar.rcl.siM;
Map z2 = bl.z(str2, "msg");
ap cu = ((com.tencent.mm.plugin.emoji.b.c) g.n(com.tencent.mm.plugin.emoji.b.c.class)).getEmojiMgr().cu(str2, str3);
if (cu == null) {
x.w("MicroMsg.BackupItemEmoji", "EmojiMsgInfo is null");
return -1;
}
EmojiInfo zi = ((com.tencent.mm.plugin.emoji.b.c) g.n(com.tencent.mm.plugin.emoji.b.c.class)).getEmojiMgr().zi(cu.bKg);
if (zi == null) {
x.w("MicroMsg.BackupItemEmoji", "EmojiInfo is null");
return -1;
}
String wC;
if (z2.get(".msg.emoji.$androidmd5") == null) {
wC = a.wC(cu.bKg);
if (!bi.oW(wC)) {
cu.bKg = wC;
x.d("MicroMsg.BackupItemEmoji", "convert ip to android md5 %s", new Object[]{wC});
}
}
wC = (String) z2.get(".msg.emoji.$productid");
if (!TextUtils.isEmpty(wC)) {
cu.bKk = wC;
}
bdVar.setType(47);
bdVar.eq(cu.bKg);
str3 = cu.enF;
if (zi.aaq() || zi.isGif()) {
z = false;
}
bdVar.setContent(an.a(str3, 0, z, cu.bKg, false, ""));
if (!zi.cnv()) {
str3 = d.asG().asH().Gg();
if (TextUtils.isEmpty(wC)) {
com.tencent.mm.plugin.backup.a.g.b(eyVar, 4, str3 + cu.bKg + "_thumb");
com.tencent.mm.plugin.backup.a.g.b(eyVar, 5, str3 + cu.bKg);
} else {
File file = new File(str3 + wC);
if (!file.exists()) {
file.mkdirs();
}
com.tencent.mm.plugin.backup.a.g.b(eyVar, 4, str3 + wC + File.separator + cu.bKg + "_cover");
com.tencent.mm.plugin.backup.a.g.b(eyVar, 5, str3 + wC + File.separator + cu.bKg);
}
EmojiInfo emojiInfo = new EmojiInfo(str3);
emojiInfo.field_md5 = cu.bKg;
emojiInfo.field_svrid = cu.id;
emojiInfo.field_catalog = EmojiInfo.tcB;
emojiInfo.field_type = cu.taZ;
emojiInfo.field_size = cu.tba;
emojiInfo.field_state = EmojiInfo.tcN;
if (!TextUtils.isEmpty(wC)) {
emojiInfo.field_groupId = wC;
}
if (!bi.oW(cu.tbi)) {
emojiInfo.field_activityid = cu.tbi;
}
d.asG().asH().asE().a(emojiInfo);
}
x.d("MicroMsg.BackupItemEmoji", "id " + c.i(bdVar));
return 0;
}
}
|
package kh.picsell.dto;
public class BuySellDTO {
private String deal_date;
private int deal_img_seq;
private int deal_price;
private String sysname;
public BuySellDTO() {
super();
// TODO Auto-generated constructor stub
}
public BuySellDTO(String deal_date, int deal_img_seq, int deal_price, String sysname) {
super();
this.deal_date = deal_date;
this.deal_img_seq = deal_img_seq;
this.deal_price = deal_price;
this.sysname = sysname;
}
public String getDeal_date() {
return deal_date;
}
public void setDeal_date(String deal_date) {
this.deal_date = deal_date;
}
public int getDeal_img_seq() {
return deal_img_seq;
}
public void setDeal_img_seq(int deal_img_seq) {
this.deal_img_seq = deal_img_seq;
}
public int getDeal_price() {
return deal_price;
}
public void setDeal_price(int deal_price) {
this.deal_price = deal_price;
}
public String getSysname() {
return sysname;
}
public void setSysname(String sysname) {
this.sysname = sysname;
}
}
|
package com.tencent.mm.plugin.appbrand.jsapi;
import android.content.Intent;
import com.tencent.mm.plugin.appbrand.l;
import com.tencent.mm.sdk.platformtools.x;
import com.tencent.mm.ui.MMActivity.a;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
class au$1 implements a {
final /* synthetic */ l fGs;
final /* synthetic */ int fGt;
final /* synthetic */ au fGu;
au$1(au auVar, l lVar, int i) {
this.fGu = auVar;
this.fGs = lVar;
this.fGt = i;
}
public final void b(int i, int i2, Intent intent) {
if (i == 1) {
String stringExtra;
Object jSONArray;
String str = "";
if (intent != null) {
stringExtra = intent.getStringExtra("key_app_authorize_state");
} else {
stringExtra = str;
}
try {
jSONArray = new JSONArray(stringExtra);
} catch (JSONException e) {
jSONArray = new JSONArray();
}
JSONObject jSONObject = new JSONObject();
try {
jSONObject.put("errMsg", this.fGu.getName() + ":ok");
jSONObject.put("authSetting", jSONArray);
} catch (Throwable e2) {
x.e("MicroMsg.JsApiOpenSetting", "set json error!");
x.printErrStackTrace("MicroMsg.JsApiOpenSetting", e2, "", new Object[0]);
}
this.fGs.E(this.fGt, jSONObject.toString());
}
}
}
|
package com.gtfs.dao.impl;
import java.io.Serializable;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Repository;
import com.gtfs.bean.RbiBankDtls;
import com.gtfs.dao.interfaces.RbiBankDtlsDao;
@Repository
public class RbiBankDtlsDaoImpl implements RbiBankDtlsDao,Serializable{
@Autowired
private SessionFactory sessionFactory;
public List<RbiBankDtls> findRbiBankDtlsByIfscCode(String ifscCode){
List<RbiBankDtls> list=null;
Session session = null;
try {
session = sessionFactory.openSession();
Criteria criteria=session.createCriteria(RbiBankDtls.class);
criteria.add(Restrictions.eq("ifscCode", ifscCode));
list=criteria.list();
} catch (Exception e) {
} finally {
session.close();
}
return list;
}
}
|
package com.kingcar.rent.pro.ui.mine;
import com.kingcar.rent.pro.R;
import com.kingcar.rent.pro.base.ToolBarActivity;
public class MyCollectActivity extends ToolBarActivity {
@Override
protected int getLayoutResId() {
return R.layout.act_collect;
}
@Override
protected void init() {
initTitleAndCanBack("我的收藏");
}
}
|
execute(des, src, registers, memory) {
int desBitSize;
String desValue;
String srcValue;
// Checks if DESTINATION is either REGISTER or MEMORY
if ( des.isRegister() ) {
desBitSize = registers.getBitSize(des);
desValue = registers.get(des);
} else if ( des.isMemory() && src.isRegister() ) {
desBitSize = registers.getBitSize(src);
desValue = memory.read(des, desBitSize);
} else {
desBitSize = memory.getBitSize(des);
desValue = memory.read(des, desBitSize);
}
// Checks if SOURCE is either REGISTER, MEMORY or IMMEDIATE
if ( src.isRegister() ) {
srcValue = registers.get(src);
} else if ( src.isMemory() ) {
srcValue = memory.read(src, desBitSize);
} else if( src.isHex() ) {
srcValue = src.getValue();
}
Calculator calculator = new Calculator(registers, memory);
EFlags eFlags = registers.getEFlags();
// ADDITION
BigInteger biDesValue = new BigInteger(desValue, 16);
BigInteger biSrcValue = new BigInteger(srcValue, 16);
BigInteger biResult = biDesValue.add(biSrcValue);
String finalResult;
if ( biResult.toString(16).length() > desBitSize/4 ) {
finalResult = biResult.toString(16).substring(1);
} else {
finalResult = biResult.toString(16);
}
// Check if DESTINATION is either REGISTER or MEMORY
if ( des.isRegister() ) {
registers.set( des, finalResult );
} else if ( des.isMemory() ) {
memory.write( des, finalResult, desBitSize );
}
String desHexValue = biDesValue.toString(16);
String srcHexValue = biSrcValue.toString(16);
String resultHexValue = biResult.toString(16);
String desBinaryValue = biDesValue.toString(2);
String srcBinaryValue = biSrcValue.toString(2);
String resultBinaryValue = biResult.toString(2);
// Create the MAX HEX VALUE depends on the HEX SIZE of DESTINATION
String maxHexValue = "";
for(int i = 0; i < desBitSize/4; i++) {
maxHexValue = maxHexValue + "F";
}
// Checks Carry Flag
BigInteger biCF = new BigInteger(maxHexValue, 16);
if ( biResult.compareTo(biCF) == 1 ) {
eFlags.setCarryFlag("1");
}
else {
eFlags.setCarryFlag("0");
}
// Checks Parity Flag
String resultBinaryValueZeroExtend = calculator.binaryZeroExtend(resultBinaryValue, des);
String parityFlag = calculator.checkParity( resultBinaryValueZeroExtend );
eFlags.setParityFlag( parityFlag );
// Checks Auxialiary Flag
String auxialiaryFlag = calculator.checkAuxiliary( srcHexValue, desHexValue );
eFlags.setAuxiliaryFlag( auxialiaryFlag );
// Checks Sign Flag
if ( biResult.testBit(desBitSize - 1) ) {
eFlags.setSignFlag("1");
} else {
eFlags.setSignFlag("0");
}
// Checks Zero Flag
if ( finalResult.equals("0") ) {
eFlags.setZeroFlag("1");
} else {
eFlags.setZeroFlag("0");
}
// Checks Overflow Flag
char desMSB = calculator.binaryZeroExtend(desBinaryValue, des).charAt(0);
char srcMSB = calculator.binaryZeroExtend(srcBinaryValue, src).charAt(0);
char resultMSB = calculator.binaryZeroExtend(resultBinaryValue, des).charAt(0);
String overflowFlag = calculator.checkOverflowAddWithFlag( srcMSB, desMSB, resultMSB, eFlags.getOverflowFlag() );
eFlags.setOverflowFlag( overflowFlag );
}
|
package com.example.demo.utils;
import org.apache.commons.lang3.StringUtils;
/**
* 咕泡学院,只为更好的你
* 咕泡学院-Mic: 2082233439
* http://www.gupaoedu.com
**/
public class FileUtils {
public static final String DOT = ".";
/**
* 获取扩展名
*
* @param fileName
* @return
*/
public static String getExtension(String fileName) {
if (StringUtils.INDEX_NOT_FOUND == StringUtils.indexOf(fileName, DOT))
return StringUtils.EMPTY;
String ext = StringUtils.substring(fileName,
StringUtils.lastIndexOf(fileName, DOT));
return StringUtils.trimToEmpty(ext);
}
/**
* 判断是否同为扩展名
*
* @param fileName
* @param ext
* @return
*/
public static boolean isExtension(String fileName, String ext) {
return StringUtils.equalsIgnoreCase(getExtension(fileName), ext);
}
}
|
package com.sysh.dto;
import java.io.Serializable;
/**
* ClassName: <br/>
* Function: 五项退出指标<br/>
* date: 2018年06月08日 <br/>
*
* @author 苏积钰
* @since JDK 1.8
*/
public class INcomeDto implements Serializable {
private String NetIncome;//纯收入
private String IsNetIncome;//是否达标
private String ScoreNetIncome;//分数
/*private String DropOutSChool;//有无辍学学生
private String IsSafeWater;//饮水是否安全
private String IsDifficultyWater;//饮水是否困难
private String SafeWater;//是否达标
private String ScoreSafeWater;//分数
private String IsNotSafePoverty;//是否为危房户
private String SafeHouse;//安全住房是否达标
private String SafeHouseScore;//住房分数
private String joinAab013;//参加新型农村合作医疗
private String joinAab022;//是否参加大病保险
private String JoinNcms;//参加新农合是否达标
private String JoinScore;//分数*/
public INcomeDto(String netIncome, String isNetIncome, String scoreNetIncome) {
NetIncome = netIncome;
IsNetIncome = isNetIncome;
ScoreNetIncome = scoreNetIncome;
}
public INcomeDto() {
super();
}
public String getNetIncome() {
return NetIncome;
}
public void setNetIncome(String netIncome) {
NetIncome = netIncome;
}
public String getIsNetIncome() {
return IsNetIncome;
}
public void setIsNetIncome(String isNetIncome) {
IsNetIncome = isNetIncome;
}
public String getScoreNetIncome() {
return ScoreNetIncome;
}
public void setScoreNetIncome(String scoreNetIncome) {
ScoreNetIncome = scoreNetIncome;
}
@Override
public String toString() {
return "FivePovertyDto{" +
"NetIncome='" + NetIncome + '\'' +
", IsNetIncome='" + IsNetIncome + '\'' +
", ScoreNetIncome='" + ScoreNetIncome + '\'' +
'}';
}
}
|
package tarea3;
interface Personaje{
//Asigna el tipo de raza
void asignarRaza(int RazaJug);
//Asigna el tipo de clase
void asignarClase(int ClaseJug);
//Asigna la vida
void asignarVida();
//Asigna el nombre
void asignarNombre(String nombre);
//Imprime en pantalla la informacion del Personaje
void ToString();
//Retorna la vida actual del Personaje
int getPS();
//Suma el valor danio a la vida actual del personaje
void setPS(int danio);
//Entrega el tipo de clase
Clase getClase();
// Cambia la tipo de clase
void setClase(Clase clase);
//Entrega el tipo de raza
Raza getRaza();
// Cambia la tipo de raza
void setRaza(Raza raza);
//Retorna el nombre del Personaje
String getNombre();
// Cambia el nombre del Personaje
void setNombre(String nombre);
//Retorna el nombre de la raza del Personaje
String getNombR();
// Cambia el nombre de la raza del Personaje
void setNombR(String NombR);
//Retorna el nombre de la clase del Personaje
String getNombC();
// Cambia el nombre de la clase del Personaje
void setNombC(String NombC);
}
|
package simple.mvc.service;
import java.util.List;
import simple.mvc.bean.ProductBean;
public interface ProductService {
List<ProductBean> getAllProducts();
}
|
package components;
import java.awt.Color;
import java.awt.Graphics;
public class BlocGraphique {
/** Abscisse */
private int posX;
/** Ordonnee */
private int posY;
/** Couleur du bloc graphique. */
private Color couleur;
/**
* Constructeur du bloc graphique. On donne sa couleur et sa position dans
* la matrice.
*
* @param couleur
* Couleur de remplissage du bloc graphique.
* @param posX
* Position en X du bloc graphique
* @param posY
* Position en Y du bloc graphique
*/
public BlocGraphique(Color couleur, int posX, int posY) {
this.couleur = couleur;
this.posX = posX;
this.posY = posY;
}
/**
* Dessine le bloc graphique.
*
* @param g
* Graphics d'affichage.
*/
public void draw(Graphics g) {
g.setColor(couleur);
g.fill3DRect(posX * 24 + 1, posY * 24 + 1, 24, 24, true);
}
/**
* Retourne la position X du bloc dans la matrice.
*
* @return L'abscisse du bloc.
*/
public int getPosX() {
return posX;
}
/**
* Retourne la position en Y du bloc dans la matrice.
*
* @return L'ordonnee du bloc.
*/
public int getPosY() {
return posY;
}
/**
* Positionne en X l'affichage du bloc dans la matrice.
*
* @param posX
* L'abscisse du bloc.
*/
public void setPosX(int posX) {
this.posX = posX;
}
/**
* Positionne en Y l'affichage du bloc dans la matrice.
*
* @param posY
* L'ordonnee du bloc.
*/
public void setPosY(int posY) {
this.posY = posY;
}
}
|
package com.microsilver.mrcard.basicservice.controller;
import com.microsilver.mrcard.basicservice.common.Consts;
import com.microsilver.mrcard.basicservice.dto.*;
import com.microsilver.mrcard.basicservice.model.FxSdSysArea;
import com.microsilver.mrcard.basicservice.model.FxSdSysAreaopen;
import com.microsilver.mrcard.basicservice.model.FxSdSysVersion;
import com.microsilver.mrcard.basicservice.model.MobileCheckCode;
import com.microsilver.mrcard.basicservice.model.enums.EWarning;
import com.microsilver.mrcard.basicservice.service.FxSdSysVersionServices;
import com.microsilver.mrcard.basicservice.service.SysAreasServices;
import com.microsilver.mrcard.basicservice.utils.JuheMsg;
import com.microsilver.mrcard.basicservice.vo.MobileVo;
import com.microsilver.mrcard.basicservice.vo.VersionVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@Api(value = "/api/Common", description = "通用方法API")
@RestController
@RequestMapping("/api/Common")
@SuppressWarnings("unchecked")
public class CommonController extends BaseController {
private final SysAreasServices sysAreasServices;
private final FxSdSysVersionServices fxSdSysVersionServices;
private final StringRedisTemplate stringRedisTemplate;
private final RedisTemplate redisTemplate;
@Autowired
public CommonController(SysAreasServices sysAreasServices, FxSdSysVersionServices fxSdSysVersionServices, StringRedisTemplate stringRedisTemplate, RedisTemplate redisTemplate) {
this.sysAreasServices = sysAreasServices;
this.fxSdSysVersionServices = fxSdSysVersionServices;
this.stringRedisTemplate = stringRedisTemplate;
this.redisTemplate = redisTemplate;
}
@ApiOperation(value = "发送短信验证码并保存", httpMethod = "POST")
@RequestMapping( value = "/sendAndSaveCheckCode", method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public RespBaseDto<CheckCodeDto> sendAndSaveCheckCode(
@RequestBody MobileVo mobileVo
) {
RespBaseDto<CheckCodeDto> result = new RespBaseDto<>();
Long mobile = mobileVo.getMobile();
short type = mobileVo.getType();
try {
if (mobile != null ) {
//CheckBasicMsg.checkMobile(mobile+"")
if(true){
// 生成验证码
String checkCode = (Math.random() + "").substring(2, 8);
// 存入redis中.一分钟过期
MobileCheckCode mobileCheckCode = new MobileCheckCode();
mobileCheckCode.setCheckCode(Integer.parseInt(checkCode));
mobileCheckCode.setMobile(mobile);
mobileCheckCode.setType(type);
redisTemplate.opsForValue().set(mobile,mobileCheckCode,60,TimeUnit.SECONDS);
JuheMsg.sendMsg(mobile+"", checkCode);
CheckCodeDto checkCodeDto = new CheckCodeDto();
checkCodeDto.setMobile(mobile+"");
checkCodeDto.setCheckCode(checkCode);
result.setData(checkCodeDto);
result.setMessage("发送成功");
result.setState(200);
return result;
}else{
result.setData(new CheckCodeDto());
result.setMessage(EWarning.MobileNotConformingToSpecifications.getName());
result.setState(EWarning.MobileNotConformingToSpecifications.getValue());
}
}else{
result.setData(new CheckCodeDto());
result.setMessage(EWarning.MessageIsNull.getName());
result.setState(EWarning.MessageIsNull.getValue());
}
} catch (Exception e) {
logger.error("sendAndSaveCheckCode error:{}", e.getMessage());
result.setMessage(EWarning.Unknown.getName() + e.getMessage());
result.setState(EWarning.Unknown.getValue());
}
return result;
}
@ApiOperation(value = "获取服务器时间", httpMethod = "POST")
@PostMapping(value = "/getSysTime",produces ="application/json;charset=UTF-8")
@ResponseBody
public RespBaseDto<String> getSysTime() {
RespBaseDto<String> result = new RespBaseDto<>();
result.setData(String.valueOf(System.currentTimeMillis()));
result.setMessage("OK");
return result;
}
@ApiOperation(value = "获取全部区域", httpMethod = "POST")
@PostMapping(value = "/getAllArea",produces ="application/json;charset=UTF-8")
@ResponseBody
public RespBaseDto<List<AllAreaDto>> getAllArea() {
RespBaseDto<List<AllAreaDto>> result = new RespBaseDto<>();
List<AllAreaDto> listAllArea = new ArrayList<>();
try {
List<FxSdSysArea> allArea = sysAreasServices.getAllSysAreas();
if(allArea!=null){
for (FxSdSysArea area:
allArea ) {
AllAreaDto allAreaDto = new AllAreaDto();
allAreaDto.setId(area.getId());
allAreaDto.setCode((long)area.getCode());
allAreaDto.setLevel((short)area.getLevel().intValue());
allAreaDto.setName(area.getName());
allAreaDto.setParentCode((long)area.getParentCode());
listAllArea.add(allAreaDto);
}
result.setData(listAllArea);
}else{
result.setMessage(EWarning.Unknown.getName());
result.setState(EWarning.Unknown.getValue());
result.setData(listAllArea);
}
} catch (Exception ex) {
logger.error("getAllArea error:{}", ex.getMessage());
result.setMessage(EWarning.Unknown.getName() + ex.getMessage());
result.setState(EWarning.Unknown.getValue());
}
return result;
}
@ApiOperation(value = "获取已开通区域", httpMethod = "POST")
@PostMapping(value = "/getOpenArea",produces ="application/json;charset=UTF-8")
@ResponseBody
public RespBaseDto<List<FxAreaDto>> getOpenArea() {
RespBaseDto<List<FxAreaDto>> result = new RespBaseDto<>();
List<FxAreaDto> list = new ArrayList<>();
try {
List<FxSdSysAreaopen> openSysAreasList = sysAreasServices.getOpenSysAreas();
if (openSysAreasList != null) {
for (FxSdSysAreaopen fxSdSysAreaopen : openSysAreasList) {
FxAreaDto fxAreaDto = new FxAreaDto();
fxAreaDto.setProvince(sysAreasServices.getOpenAreaAttribute((long) fxSdSysAreaopen.getProvince()));
fxAreaDto.setCity(sysAreasServices.getOpenAreaAttribute((long) fxSdSysAreaopen.getCity()));
fxAreaDto.setCounty(fxSdSysAreaopen.getName());
fxAreaDto.setCityNum(fxSdSysAreaopen.getCity()+"");
fxAreaDto.setCountyNum(fxSdSysAreaopen.getCounty()+"");
fxAreaDto.setProvinceNum(fxSdSysAreaopen.getProvince()+"");
fxAreaDto.setId(fxSdSysAreaopen.getId().intValue());
list.add(fxAreaDto);
}
result.setData(list);
result.setMessage("Ok");
result.setState(200);
}else{
result.setData(null);
result.setMessage(EWarning.NoAreaMsg.getName());
result.setState(EWarning.NoAreaMsg.getValue());
}
} catch (Exception ex) {
logger.error("getOpenArea error:{}", ex.getMessage());
result.setMessage(EWarning.Unknown.getName() + ex.getMessage());
result.setState(EWarning.Unknown.getValue());
}
return result;
}
@ApiOperation(value = "APP版本检查更新", httpMethod = "POST")
@ResponseBody
@PostMapping(value = "/getAppVersion",produces ="application/json;charset=UTF-8")
public RespBaseDto<VersionDto> getAppVersion(
@RequestBody VersionVo versionVo
) {
RespBaseDto<VersionDto> result = new RespBaseDto<>();
try {
VersionDto versionDto = new VersionDto();
FxSdSysVersion version = fxSdSysVersionServices.checkVersion(versionVo.getAppType(), versionVo.getClientType());
if (version == null ) {
result.setMessage(EWarning.UninitializedVersion.getName());
result.setState(EWarning.UninitializedVersion.getValue());
result.setData(versionDto);
} else {
versionDto.setId(version.getId());
versionDto.setAppType(version.getAppType());
versionDto.setClientType(version.getClientType());
versionDto.setCode(version.getCode());
versionDto.setDescription(version.getDescription());
versionDto.setIsForce(version.getIsForce().shortValue());
versionDto.setCode(version.getCode());
versionDto.setDownAddress(version.getDownDdress());
versionDto.setVersion(version.getVersion());
result.setMessage("ok");
result.setData(versionDto);
result.setState(200);
}
}catch(Exception ex) {
logger.error("getAppVersion error:{}", ex.getMessage());
result.setMessage(EWarning.Unknown.getName()+ex.getMessage());
result.setState(EWarning.Unknown.getValue());
}
return result;
}
@ApiOperation(value = "上传图片到服务器", httpMethod = "POST")
@RequestMapping(value = "/UploadPicture")
@ResponseBody
public RespBaseDto<PrctureDto> uploadPicture(@RequestParam("file") MultipartFile file) {
RespBaseDto<PrctureDto> result = new RespBaseDto<>();
PrctureDto prctureDto = new PrctureDto();
// 创建日期文件夹
String path = Consts.PICTURES_ADDRESS +File.separator+ new SimpleDateFormat("MM/").format(new Date());
String pathFile = null;
// 如果不存在,创建文件夹
File f = new File(path);
UUID uuid = UUID.randomUUID();
System.out.println("path:"+path);
if (!f.exists()) {
f.mkdirs();
}
if (!file.isEmpty()) {
try {
// 根路径
//File.separator 根据系统下识别分割器
String fileName = file.getOriginalFilename();
pathFile = f.getPath() + File.separator + uuid+"."+fileName.substring(fileName.lastIndexOf(".")+1);
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(new File(pathFile)));
out.write(file.getBytes());
out.flush();
out.close();
//http://211.149.164.182/uploads2018/05/ea7779fc-5f8c-43e5-88fe-95c862a2fcef.png
//new SimpleDateFormat("MM/").format(new Date()
prctureDto.setPictureUrl("http://211.149.164.182/uploads2018/"+File.separator+new SimpleDateFormat("MM/").format(new Date())+File.separator+uuid+"."+fileName.substring(fileName.lastIndexOf(".")+1));
result.setData(prctureDto);
result.setMessage("上传成功");
result.setState(200);
return result;
} catch (Exception e) {
e.printStackTrace();
result.setData(prctureDto);
result.setMessage("上传失败," + e.getMessage());
result.setState(2100);
return result;
}
} else {
result.setData(prctureDto);
result.setMessage("上传失败,因为文件是空的.");
result.setState(2100);
return result;
}
}
}
|
package br.com.alura.carteira.dto;
import java.math.BigDecimal;
import java.time.LocalDate;
import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.PastOrPresent;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonAlias;
import br.com.alura.carteira.modelo.TipoTransacao;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class TransacaoFormDto {
@NotBlank
@Size(min = 5, max = 6)
@Pattern(regexp = "[a-zA-Z]{4}[0-9][0-9]?", message = "{transacao.ticker.formato.invalido}")
private String ticker;
@NotNull
@DecimalMin("0.01")
private BigDecimal preco;
@PastOrPresent
private LocalDate data;
@NotNull
@Min(1)
private int quantidade;
@NotNull
private TipoTransacao tipo;
@JsonAlias("usuario_id")
@NotNull
private Long usuarioId;
}
|
package com.podarbetweenus.Adapter;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CheckedTextView;
import android.widget.CompoundButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.podarbetweenus.Activities.DataTransferInterface;
import com.podarbetweenus.Activities.TeacherSendSMSActivity;
import com.podarbetweenus.Entity.SmsStudentResult;
import com.podarbetweenus.R;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
/**
* Created by Gayatri on 2/4/2016.
*/
public class ShowSMSStudentListAdapter extends BaseAdapter {
LayoutInflater layoutInflater;
Context context;
DataTransferInterface dtInterface;
String selectAll,stud_id,contact_number,class_id,clt_id,usl_id,school_name,teacher_name,version_name,board_name;
boolean checkboxStatus;
public ArrayList<SmsStudentResult> SmsStudentResult = new ArrayList<SmsStudentResult>();
public static ArrayList<String> stud_id_data = new ArrayList<String>();
public static ArrayList<String> contact_no_data = new ArrayList<String>();
boolean selectAllCheckboxStatus;
public static SharedPreferences resultpreLoginData;
public ShowSMSStudentListAdapter(Context context,DataTransferInterface dataTransferInterface, ArrayList<SmsStudentResult> SmsStudentResult,boolean selectAllCheckboxStatus,String selectAll,String clt_id,String usl_id,String school_name,String teacher_name,String version_name,String board_name) {
this.context = context;
this.SmsStudentResult = SmsStudentResult;
this.selectAllCheckboxStatus = selectAllCheckboxStatus;
this.selectAll = selectAll;
this.clt_id = clt_id;
this.usl_id = usl_id;
this.dtInterface = dataTransferInterface;
this.school_name = school_name;
this.teacher_name = teacher_name;
this.version_name = version_name;
this.board_name = board_name;
this.layoutInflater = layoutInflater.from(this.context);
layoutInflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return SmsStudentResult.size();
}
@Override
public Object getItem(int position) {
return SmsStudentResult.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
View showLeaveStatus = convertView;
if (showLeaveStatus == null)
{
holder = new ViewHolder();
showLeaveStatus = layoutInflater.inflate(R.layout.studentlist_item,null);
holder.tv_student_name = (TextView) showLeaveStatus.findViewById(R.id.tv_student_name);
holder.tv_roll_no_value = (TextView) showLeaveStatus.findViewById(R.id.tv_roll_no_value);
// holder.tv_reg_no = (TextView)showLeaveStatus.findViewById(R.id.tv_reg_no);
holder.checkbox = (CheckBox) showLeaveStatus.findViewById(R.id.select_checkbox);
holder.ll_main = (LinearLayout) showLeaveStatus.findViewById(R.id.ll_main);
holder.ll_checkbox = (LinearLayout) showLeaveStatus.findViewById(R.id.ll_checkbox);
holder.ll_roll_no = (LinearLayout) showLeaveStatus.findViewById(R.id.ll_roll_no);
// holder.checkbox.setChecked(true);
} else
{
holder = (ViewHolder) showLeaveStatus.getTag();
}
showLeaveStatus.setTag(holder);
holder.tv_roll_no_value.setText(SmsStudentResult.get(position).Roll_No);
holder.tv_student_name.setText(SmsStudentResult.get(position).Student_Name);
if(position % 2 ==0){
holder.ll_roll_no.setBackgroundResource(R.color.sms_listview_even_row);
holder.ll_main.setBackgroundColor(Color.parseColor("#dbb5ab"));
holder.ll_checkbox.setBackgroundResource(R.color.sms_listview_even_row);
holder.tv_student_name.setBackgroundResource(R.color.sms_listview_even_row);
}
else {
holder.ll_main.setBackgroundColor(Color.parseColor("#dbb5ab"));
holder.ll_roll_no.setBackgroundResource(R.color.sms_listview_odd_row);
holder.tv_student_name.setBackgroundResource(R.color.sms_listview_odd_row);
holder.ll_checkbox.setBackgroundResource(R.color.sms_listview_odd_row);
}
// holder.tv_reg_no.setText(SmsStudentResult.get(position).Reg_No);
if(selectAll.equalsIgnoreCase("true"))
{
holder.checkbox.setChecked(true);
}
else{
holder.checkbox.setChecked(false);
}
checkboxStatus = holder.checkbox.isChecked();
final ViewHolder finalHolder = holder;
finalHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int position = (Integer) buttonView.getTag();
if(isChecked){
finalHolder.checkbox.setChecked(true);
stud_id = SmsStudentResult.get(position).stu_ID;
contact_number =SmsStudentResult.get(position).con_MNo;
stud_id_data.add(position,stud_id);
contact_no_data.add(position, contact_number);
ShowSMSStudentListAdapter.Set_id(stud_id_data, contact_no_data, context);
ShowSMSStudentListAdapter.get_ContactData(context);
ShowSMSStudentListAdapter.get_studId(context);
}
else{
finalHolder.checkbox.setChecked(false);
}
}
});
/* finalHolder.checkbox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finalHolder.checkbox.setChecked(true);
stud_id = SmsStudentResult.get(position).stu_ID;
contact_number =SmsStudentResult.get(position).con_MNo;
stud_id_data.add(position,stud_id);
contact_no_data.add(position,contact_number);
// dtInterface.setValues(stud_id_data, contact_no_data);
ShowSMSStudentListAdapter.Set_id(stud_id_data, contact_no_data, context);
ShowSMSStudentListAdapter.get_ContactData(context);
ShowSMSStudentListAdapter.get_studId(context);
// notifyDataSetChanged();
*//* if(checkboxStatus==false){
finalHolder.checkbox.setChecked(true);
stud_id = SmsStudentResult.get(position).stu_ID;
contact_number =SmsStudentResult.get(position).con_MNo;
stud_id_data.add(position,stud_id);
contact_no_data.add(position,contact_number);
dtInterface.setValues(stud_id_data, contact_no_data);
ShowSMSStudentListAdapter.Set_id(stud_id_data, contact_no_data, context);
ShowSMSStudentListAdapter.get_ContactData(context);
ShowSMSStudentListAdapter.get_studId(context);
notifyDataSetChanged();
}
else{
finalHolder.checkbox.setChecked(false);
notifyDataSetChanged();
}
*//*
*//* stud_id = SmsStudentResult.get(position).stu_ID;
contact_number =SmsStudentResult.get(position).con_MNo;
class_id = SmsStudentResult.get(position).cls_ID;
Intent sendSMS = new Intent(context,TeacherSendSMSActivity.class);
sendSMS.putExtra("class_id",class_id);
sendSMS.putExtra("clt_id",clt_id);
sendSMS.putExtra("usl_id", usl_id);
sendSMS.putExtra("School_name", school_name);
sendSMS.putExtra("Teacher_name", teacher_name);
sendSMS.putExtra("version_name", version_name);
sendSMS.putExtra("board_name",board_name);
sendSMS.putExtra("stud_id",stud_id);
sendSMS.putExtra("Contact_Number",contact_number);
context.startActivity(sendSMS);*//*
}
});
*/
return showLeaveStatus;
}
public static void Set_id(ArrayList<String> studData,ArrayList<String> contactData,Context context) {
resultpreLoginData = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor editor = resultpreLoginData.edit();
Set<String> setStudId = new HashSet<String>();
setStudId.addAll(studData);
Set<String> setContactNo = new HashSet<String>();
setContactNo.addAll(contactData);
editor.putStringSet("StudId", setStudId);
editor.putStringSet("ContactData", setContactNo);
editor.commit();
}
public static Set<String> get_studId(Context context) {
resultpreLoginData = PreferenceManager.getDefaultSharedPreferences(context);
Set<String> setStudId = new HashSet<String>();
setStudId = resultpreLoginData.getStringSet("StudId", null);
return setStudId;
}
public static Set<String> get_ContactData(Context context) {
resultpreLoginData = PreferenceManager.getDefaultSharedPreferences(context);
Set<String> setContact = new HashSet<String>();
setContact = resultpreLoginData.getStringSet("ContactData", null);
return setContact;
}
public static class ViewHolder
{
TextView tv_roll_no_value,tv_student_name,tv_reg_no;
CheckBox checkbox;
LinearLayout ll_main,ll_checkbox,ll_roll_no;
}
}
|
package com.wt.jiaduo.service.impl;
import javax.transaction.Transactional;
import org.springframework.beans.BeanUtils;
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.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.stereotype.Service;
import com.wt.jiaduo.dao.XiaomaiCongaibingBingqingpuchaDao;
import com.wt.jiaduo.dto.jpa.XiaomaiCongaibingBingqingpucha;
import com.wt.jiaduo.service.XiaomaiCongaibingBingqingpuchaService;
import com.wt.jiaduo.utils.BeanUtilsUtil;
@Service
@Transactional
public class XiaomaiCongaibingBingqingpuchaServiceImpl implements XiaomaiCongaibingBingqingpuchaService {
@Autowired
private XiaomaiCongaibingBingqingpuchaDao xiaomaiCongaibingBingqingpuchaDao;
@Override
public Page<XiaomaiCongaibingBingqingpucha> findAll(Integer pageNum, Integer pageSize) {
Sort sort = new Sort(Direction.ASC, "id");
Pageable pageable = new PageRequest(pageNum - 1, pageSize, sort);
return xiaomaiCongaibingBingqingpuchaDao.findAll(pageable);
}
@Override
public XiaomaiCongaibingBingqingpucha saveOne(XiaomaiCongaibingBingqingpucha xiaomaiCongaibingBingqingpucha) {
return xiaomaiCongaibingBingqingpuchaDao.save(xiaomaiCongaibingBingqingpucha);
}
@Override
public XiaomaiCongaibingBingqingpucha modify(XiaomaiCongaibingBingqingpucha xiaomaiCongaibingBingqingpucha) {
XiaomaiCongaibingBingqingpucha xiaomaiCongaibingBingqingpuchaDatabase = xiaomaiCongaibingBingqingpuchaDao
.getOne(xiaomaiCongaibingBingqingpucha.getId());
if (xiaomaiCongaibingBingqingpuchaDatabase != null) {
BeanUtils.copyProperties(xiaomaiCongaibingBingqingpucha, xiaomaiCongaibingBingqingpuchaDatabase,
BeanUtilsUtil.getNullPropertyNames(xiaomaiCongaibingBingqingpucha));
return xiaomaiCongaibingBingqingpuchaDao.save(xiaomaiCongaibingBingqingpuchaDatabase);
}
return null;
}
@Override
public void delete(Integer id) {
xiaomaiCongaibingBingqingpuchaDao.delete(id);
}
@Override
public XiaomaiCongaibingBingqingpucha getOne(Integer id) {
return xiaomaiCongaibingBingqingpuchaDao.findOne(id);
}
}
|
package com.sinata.rwxchina.component_home.activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Vibrator;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import com.jaeger.library.StatusBarUtil;
import com.sinata.rwxchina.basiclib.base.BaseActivity;
import com.sinata.rwxchina.basiclib.utils.immersionutils.ImmersionUtils;
import com.sinata.rwxchina.component_home.R;
import cn.bingoogolapple.qrcode.core.QRCodeView;
/**
* @author:wj
* @datetime:2017/12/27
* @describe:
* @modifyRecord:
*/
public class ScanCodeActivity extends BaseActivity implements QRCodeView.Delegate{
private QRCodeView mQRCodeView;
private TextView title;
private ImageView back;
private View statusBar;
@Override
public void initParms(Bundle params) {
setSetStatusBar(true);
}
@Override
public View bindView() {
return null;
}
@Override
public int bindLayout() {
return R.layout.activity_scan_code;
}
@Override
public void initView(View view, Bundle savedInstanceState) {
mQRCodeView = view.findViewById(R.id.scan_code_zxing);
title = view.findViewById(R.id.food_comment_title_tv);
back = view.findViewById(R.id.food_comment_back);
statusBar = findViewById(R.id.normal_fakeview);
title.setText("二维码扫描");
mQRCodeView.setDelegate(this);
}
@Override
public void setListener() {
back.setOnClickListener(this);
}
@Override
public void widgetClick(View v) {
if(v.getId() == R.id.food_comment_back){
finish();
}
}
@Override
public void doBusiness(Context mContext) {
setTitleBarView();
}
@Override
protected void onStart() {
super.onStart();
mQRCodeView.startCamera();
// mQRCodeView.startCamera(Camera.CameraInfo.CAMERA_FACING_FRONT);
mQRCodeView.showScanRect();
}
@Override
protected void onStop() {
mQRCodeView.stopCamera();
super.onStop();
}
@Override
protected void onDestroy() {
mQRCodeView.onDestroy();
super.onDestroy();
}
private void vibrate() {
Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
vibrator.vibrate(200);
}
@Override
public void onScanQRCodeSuccess(String result) {
}
@Override
public void onScanQRCodeOpenCameraError() {
}
/**
* 设置标题栏
*/
private void setTitleBarView(){
ImmersionUtils.setListImmersion(getWindow(),this,statusBar);
}
@Override
public void steepStatusBar() {
super.steepStatusBar();
//状态栏透明
StatusBarUtil.setTranslucentForImageViewInFragment(ScanCodeActivity.this, null);
}
}
|
package com.cmcc.pay;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* @author chendewei@cmhi.chinamobile.com
* @version V1.0
* @date 2016年11月18日 下午1:34:02
* @since JDK1.8
* <p>
* 功能说明: 支付平台请求工具类
*/
public class PayUtil {
// 通过浏览器请求
public static String orderToXml(PayOrderDo payOrderDo) throws Exception {
return orderToXml(payOrderDo, true);
}
public static String orderToXml(PayOrderDo payOrderDo, boolean isbrowser) throws Exception {
Document document = DocumentHelper.createDocument();
Element root = document.addElement(CommonNode.ADVPAY);
Element pubInfo = root.addElement(CommonNode.PUBINFO);
Element busiData = root.addElement(CommonNode.BUSIDATA);
Element version = pubInfo.addElement(CommonNode.VERSION);
version.addText("1.00");
// 必填节点
pubInfo.addElement(CommonNode.TRANSACTIONID).addText(payOrderDo.getTransactionid());
pubInfo.addElement(CommonNode.TRANSACTIONDATE)
.addText(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()));
pubInfo.addElement(CommonNode.ORIGINID).addText(payOrderDo.getPlatformid());
pubInfo.addElement(CommonNode.DIGESTALG).addText(payOrderDo.getDigestAlg());
busiData.addElement(CommonNode.PRODUCTID).addText(String.valueOf(payOrderDo.getProductid()));
busiData.addElement(CommonNode.MERCHANTID).addText(String.valueOf(payOrderDo.getMerchantid()));
busiData.addElement(CommonNode.PAYAMOUNT).addText(payOrderDo.getPrice());
busiData.addElement(CommonNode.ORDERID).addText(payOrderDo.getOrderid());
busiData.addElement(CommonNode.PROCOUNT).addText(String.valueOf(payOrderDo.getProCount()));
busiData.addElement(CommonNode.ACCOUNTTYPE).addText(String.valueOf(payOrderDo.getAccountType()));
busiData.addElement(CommonNode.ACCOUNTCODE).addText(String.valueOf(payOrderDo.getAccountCode()));
// 可选节点
addElement(busiData, CommonNode.PAYINFO, payOrderDo.getOrderinfo());
addElement(busiData, CommonNode.PAYNOTIFYINTURL, payOrderDo.getReturnUrl());
addElement(busiData, CommonNode.PAYNOTIFYPAGEURL, payOrderDo.getNotifyUrl());
String platformkey = payOrderDo.getPlatformKey();
String sign = SignUtil.sign(pubInfo, busiData, platformkey);
Element verifyCode = pubInfo.addElement(CommonNode.VERIFYCODE);
verifyCode.addText(sign);
// 如果通过浏览器请求
if (isbrowser) {
busiData.remove(busiData.element(CommonNode.PAYINFO));
addElement(busiData, CommonNode.PAYINFO, URLEncoder.encode(payOrderDo.getOrderinfo(), "utf-8"));
}
return root.asXML();
}
/**
* 同步通知返回BUSIDATA节点
*/
public static PayOrderDo verifyNotifyMsg(String xml, String platformKey) throws Exception {
Document document = DocumentHelper.parseText(xml);
Element root = document.getRootElement();
Element pubInfo = root.element(CommonNode.PUBINFO);
Element busiData = root.element(CommonNode.BUSIDATA);
String verifyCode = pubInfo.elementTextTrim(CommonNode.VERIFYCODE);
String digestAlg = pubInfo.elementTextTrim(CommonNode.DIGESTALG);
String busiDataStr = busiData.asXML();// TODO:
if (busiDataStr == null) {
throw new Exception("同步通知busiData转为字符串出错:busiData={}");
}
String signData = SignUtil.getSignData(pubInfo, busiData);
boolean isPass = SignUtil.verify(signData, verifyCode, platformKey, digestAlg);
if (!isPass) {
throw new Exception("验签失败");
}
/** 必填 */
PayOrderDo payOrderDo = new PayOrderDo();
payOrderDo.setOrderid(busiData.elementTextTrim(CommonNode.ORDERID)); // 业务平台订单号
payOrderDo.setPayOrderid(busiData.elementTextTrim(CommonNode.DONECODE)); // 支付平台订单号
payOrderDo.setOrderStatus(Integer.valueOf(busiData.elementTextTrim(CommonNode.STATUS))); // 支付状态0:支付成功
// 1:支付失败
// 2:等待支付
payOrderDo.setPrice(busiData.elementTextTrim(CommonNode.PAYAMOUNT)); // 支付金额
payOrderDo.setType(busiData.elementTextTrim(CommonNode.TYPE)); // 支付方式
/** 可选 */
payOrderDo.setThirdPrice(busiData.elementTextTrim(CommonNode.THIRDAMOUNT)); // 第三方金额
payOrderDo.setVirtualCoinCount(Integer.valueOf(busiData.elementTextTrim(CommonNode.VIRTUALCURRENCY))); // 支付平台订单号
payOrderDo.setMergeInfo(busiData.elementTextTrim(CommonNode.MERGEINFO)); // 购物车订单
payOrderDo.setPayDate(busiData.elementTextTrim(CommonNode.PAYDATE)); // 支付时间
return payOrderDo;
}
public static RefundResult verifyRefundNotifyXml(String xml, String platformKey) throws Exception {
Document document = DocumentHelper.parseText(xml);
Element root = document.getRootElement();
Element pubInfo = root.element(CommonNode.PUBINFO);
Element busiData = root.element(CommonNode.BUSIDATA);
String verifyCode = pubInfo.elementTextTrim(CommonNode.VERIFYCODE);
String digestAlg = pubInfo.elementTextTrim(CommonNode.DIGESTALG);
String busiDataStr = busiData.asXML();
if (busiDataStr == null) {
throw new Exception("异步通知busiData转为字符串出错:busiData={}");
}
String signData = SignUtil.getSignData(pubInfo, busiData);
boolean isPass = SignUtil.verify(signData, verifyCode, platformKey, digestAlg);
if (!isPass) {
throw new Exception("验签失败");
}
RefundResult refundResult = new RefundResult();
/** 必填 */
refundResult.setTradeNO(busiData.elementTextTrim(CommonNode.TRADENO));
refundResult.setReturnCode(busiData.elementTextTrim(CommonNode.RETURNCODE));
refundResult.setReturnMsg(busiData.elementTextTrim(CommonNode.RETURNMSG));
/** 可选 */
refundResult.setRefundOrderid(busiData.elementTextTrim(CommonNode.REFUNDORDERID));
return refundResult;
}
public static BarCodePayResult xmlToBarCodeResult(String xml, String key) throws Exception {
Document document;
try {
document = DocumentHelper.parseText(xml);
} catch (DocumentException e) {
throw new Exception("xml格式错误", e);
}
Element root = document.getRootElement();
Element pubInfo = root.element(CommonNode.PUBINFO);
Element busiData = root.element(CommonNode.BUSIDATA);
// String verifyCode = pubInfo.elementTextTrim(CommonNode.VERIFYCODE);
// String sign = SignUtil.sign(pubInfo, busiData, key);
// if (verifyCode == null || !verifyCode.equals(sign)) {
// throw new Exception("验签错误 VerifyCode=" + verifyCode);
// }
BarCodePayResult result = new BarCodePayResult();
result.setStatus(busiData.elementTextTrim(CommonNode.STATUS));
result.setStatusCode(busiData.elementTextTrim(CommonNode.STATUSCODE));
result.setStatusInfo(busiData.elementTextTrim(CommonNode.STATUSINFO));
result.setOrderId(busiData.elementTextTrim(CommonNode.ORDERID));
result.setDoneCode(busiData.elementTextTrim(CommonNode.DONECODE));
result.setPayAmount(busiData.elementTextTrim(CommonNode.PAYAMOUNT));
result.setPayDate(busiData.elementTextTrim(CommonNode.PAYDATE));
result.setType(busiData.elementTextTrim(CommonNode.TYPE));
return result;
}
private static void addElement(Element element, String nodeName, String text) {
if (text == null || text.trim().length() == 0) {
return;
}
element.addElement(nodeName).addText(text);
}
public static String refundToXml(RefundDo refundDo) {
Document document = DocumentHelper.createDocument();
Element root = document.addElement(CommonNode.ADVPAY);
Element pubInfo = root.addElement(CommonNode.PUBINFO);
Element busiData = root.addElement(CommonNode.BUSIDATA);
Element version = pubInfo.addElement(CommonNode.VERSION);
version.addText("1.00");
// 必填节点
pubInfo.addElement(CommonNode.TRANSACTIONID).addText(refundDo.getTransactionid());
pubInfo.addElement(CommonNode.TRANSACTIONDATE).addText(refundDo.getTransactionDate());
pubInfo.addElement(CommonNode.ORIGINID).addText(refundDo.getPlatformid());
pubInfo.addElement(CommonNode.DIGESTALG).addText(refundDo.getDigestAlg());
addElement(busiData, CommonNode.TRADENO, refundDo.getTradeNo());
addElement(busiData, CommonNode.REFUNDREADON, refundDo.getRefundReason());
// 可选节点
addElement(busiData, CommonNode.REFUNDNOTIFYURL, refundDo.getRefundNotifyUrl());
addElement(busiData, CommonNode.REFUNDAMOUNT, refundDo.getRefundAmount());
addElement(busiData, CommonNode.REFUNDORDERID, refundDo.getRefundOrderid());
addElement(busiData, CommonNode.REFUNDTYPE, String.valueOf(refundDo.getRefundType()));
String platformkey = refundDo.getPlatformKey();
String sign = SignUtil.sign(pubInfo, busiData, platformkey);
Element verifyCode = pubInfo.addElement(CommonNode.VERIFYCODE);
verifyCode.addText(sign);
return root.asXML();
}
public static RefundResult xmlToRefundResult(String resultXml, String md5Key) throws Exception {
Document document;
try {
document = DocumentHelper.parseText(resultXml);
} catch (DocumentException e) {
throw new Exception("xml格式错误", e);
}
Element root = document.getRootElement();
Element pubInfo = root.element(CommonNode.PUBINFO);
Element busiData = root.element(CommonNode.BUSIDATA);
String verifyCode = pubInfo.elementTextTrim(CommonNode.VERIFYCODE);
String sign = SignUtil.sign(pubInfo, busiData, md5Key);
if (verifyCode == null || !verifyCode.equals(sign)) {
throw new Exception("验签错误 VerifyCode=" + verifyCode);
}
RefundResult result = new RefundResult();
result.setReturnCode(busiData.elementTextTrim(CommonNode.RETURNCODE));
result.setReturnMsg(busiData.elementTextTrim(CommonNode.RETURNMSG));
result.setTradeNO(busiData.elementTextTrim(CommonNode.TRADENO));
result.setRefundOrderid(busiData.elementTextTrim(CommonNode.REFUNDORDERID));
return result;
}
}
|
package com.cs4125.bookingapp.model;
import com.cs4125.bookingapp.model.entities.User;
import org.springframework.stereotype.Service;
@Service
public interface UserFactory {
User getUser(String userType, String username, String password, String email);
}
|
/**
*
* Bank Account.java
* TCSS-143 - Summer 2019
* Assignment 4
* Create a safe deposit Box for a customer
* Implement NamedAccount interface to implement the two methods get/set owner name
* Take a look of BankAccoun.java class for the entire details
*/
/**
* @author Adam Shandi
* @version July 28 2019
* @University of Washington
* */
public class SafeDepositBoxAccount implements NamedAccount{
/**
* Private String owner's name
*/
private String myOwnerName;
/**
* CONSTRUCTOR - set the owner's name who they are willing to open a bank box
*
* @param theOwnerName
*/
public SafeDepositBoxAccount(String theOwnerName){
this.myOwnerName= theOwnerName;
}
/**
* Set the Box holder's name
* @param String theOwner name
*/
@Override
public void setAccountHolderName(String theOwner) {
this.myOwnerName=theOwner;
}
/**
*
* @return String account holder name
*/
@Override
public String getAccountHolderName(){
return myOwnerName;
}
/**
*
* Print a statement that a customer has requested to open a box
* @return Void
*/
public void createBoxAccount(){
System.out.println("Creating a safe deposit box account"+getAccountHolderName());
}
/**
* This class implements its own toString() method to print the customer's info if they have a box
*
* @return String of the customer's info
*/
@Override
public String toString(){
StringBuilder myStr = new StringBuilder();
myStr.append(this.getClass().getName()+ "[owner :"+ this.myOwnerName+"]");
return myStr.toString();
}
}
|
package dp.AdapterPatternLanguageTranslator;
public interface EnglishSpeaker {
public String askQuestion(String words);
public String answerFortheQuestion(String words);
}
|
package animatronics.common.tile;
import animatronics.api.misc.Vector3;
import animatronics.utils.misc.MiscUtils;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
public class TileEntityNothing extends TileEntity {
public boolean canUpdate() {
return false;
}
@SideOnly(Side.CLIENT)
public AxisAlignedBB getRenderBoundingBox() {
return MiscUtils.boundingBoxFromTo(Vector3.fromTileEntity(this), Vector3.fromTileEntity(this).add(1));
}
}
|
package com.bdb.servlet;
import javax.servlet.http.HttpServlet;
import org.apache.log4j.Logger;
public class BDBHttpServlet extends HttpServlet {
/**
* Comment for <code>serialVersionUID</code>
*/
private static final Logger log;
static {
log = Logger.getLogger(com.bdb.servlet.BDBHttpServlet.class);
}
private static final long serialVersionUID = 1L;
public BDBHttpServlet() {
log.debug("BDBHttpServlet");
}
}
|
package com.ts.dao;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.rest.dto.Faculty;
import com.rest.dto.Review;
import com.rest.dto.Submit;
import com.rest.dto.Tasks;
import com.ts.db.HibernateTemplate;
public class SubmitDAO {
private SessionFactory factory = null;
private static SessionFactory sessionFactory;
static {
sessionFactory = new Configuration().configure().buildSessionFactory();
}
public int register(Submit submit) {
return HibernateTemplate.addObject(submit);
}
public List<Submit> getAllSubmissions(String subject) {
String query= "from Submit where subject=:subject";
Query query1 = sessionFactory.openSession().createQuery(query);
query1.setParameter("subject",subject);
System.out.println(subject);
List <Submit> obj = query1.list();
for(Object submit: obj){
Submit tasks1 = (Submit)submit;
//System.out.println(tasks1.getDescription());
}
return obj;
/*List<Submit> submit=(List)HibernateTemplate.getObjectListByQuery("From Submit");
for(Object fac: submit){
Submit fac1 = (Submit)fac;
System.out.println(fac1);
}
return submit; */
}
public Submit getSubmission(int taskId, int studentId) {
String query= "from Submit where taskId=:taskId and studentId=:studentId";
Query query1 = sessionFactory.openSession().createQuery(query);
query1.setParameter("taskId",taskId);
query1.setParameter("studentId",studentId);
System.out.println(taskId);
//Faculty obj = query1.list();
Object queryResult = query1.uniqueResult();
Submit submit = (Submit)queryResult;
return submit;
}
}
|
package com.espendwise.manta.web.controllers;
import com.espendwise.manta.model.data.PropertyData;
import com.espendwise.manta.model.view.SiteListView;
import com.espendwise.manta.service.SiteService;
import com.espendwise.manta.service.UserService;
import com.espendwise.manta.spi.AutoClean;
import com.espendwise.manta.spi.SuccessMessage;
import com.espendwise.manta.util.AppComparator;
import com.espendwise.manta.util.Constants;
import com.espendwise.manta.util.RefCodeNames;
import com.espendwise.manta.util.SelectableObjects;
import com.espendwise.manta.util.Utility;
import com.espendwise.manta.util.alert.ArgumentedMessage;
import com.espendwise.manta.util.criteria.SiteListViewCriteria;
import com.espendwise.manta.web.forms.UserLocationFilterForm;
import com.espendwise.manta.web.forms.UserLocationFilterResultForm;
import com.espendwise.manta.web.util.*;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.context.request.WebRequest;
import java.util.List;
import javax.servlet.http.HttpSession;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.validation.DataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.SessionAttributes;
@Controller
@RequestMapping(UrlPathKey.USER.LOCATION)
@SessionAttributes({SessionKey.USER_LOCATION_FILTER, SessionKey.USER_LOCATION_FILTER_RESULT})
@AutoClean(SessionKey.USER_LOCATION_FILTER)
public class UserLocationController extends BaseController {
private static final Logger logger = Logger.getLogger(UserLocationController.class);
private UserService userService;
private SiteService siteService;
@Autowired
public UserLocationController(UserService userService,
SiteService siteService) {
this.userService = userService;
this.siteService = siteService;
}
@InitBinder
@Override
public void initBinder(DataBinder binder) {
binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
}
@RequestMapping(value = "/view", method = RequestMethod.GET)
public String view(@ModelAttribute(SessionKey.USER_LOCATION_FILTER) UserLocationFilterForm filterForm) {
return "user/location";
}
@RequestMapping(value = "/filter", method = RequestMethod.GET)
public String findSites(WebRequest request,
@ModelAttribute(SessionKey.USER_LOCATION_FILTER) UserLocationFilterForm filterForm,
@ModelAttribute(SessionKey.USER_LOCATION_FILTER_RESULT) UserLocationFilterResultForm resultForm) throws Exception {
WebErrors webErrors = new WebErrors(request);
List<? extends ArgumentedMessage> validationErrors = WebAction.validate(filterForm);
if (!validationErrors.isEmpty()) {
webErrors.putErrors(validationErrors);
return "user/location";
}
resultForm.reset();
Long siteId = null;
if (Utility.isSet(filterForm.getSiteId())) {
siteId = Long.valueOf(filterForm.getSiteId());
}
SiteListViewCriteria criteria = new SiteListViewCriteria(getStoreId(), Constants.FILTER_RESULT_LIMIT.SITE);
criteria.setUserId(filterForm.getUserId());
criteria.setSiteId(siteId);
criteria.setActiveOnly(!filterForm.getShowInactive());
criteria.setSiteNameFilterType(filterForm.getSiteNameFilterType());
criteria.setSiteName(filterForm.getSiteName());
criteria.setRefNumber(filterForm.getReferenceNumber(), filterForm.getRefNumberFilterType());
criteria.setCity(filterForm.getCity(), Constants.FILTER_TYPE.CONTAINS);
criteria.setState(filterForm.getStateProvince(), Constants.FILTER_TYPE.CONTAINS);
criteria.setPostalCode(filterForm.getPostalCode(), Constants.FILTER_TYPE.START_WITH);
criteria.setUseUserToAccountAssoc(true);
criteria.setConfiguredOnly(true);
List<SiteListView> configured = userService.findUserSitesByCriteria(criteria);
criteria.setConfiguredOnly(false);
List<SiteListView> sites = filterForm.getShowConfiguredOnly()
? configured : userService.findUserSitesByCriteria(criteria);
logger.info("findSites()=> sites: " + sites.size());
logger.info("findSites()=> configured: " + configured.size());
SelectableObjects<SiteListView> selectableObj = new SelectableObjects<SiteListView>(
sites,
configured,
AppComparator.SITE_LIST_VIEW_COMPARATOR);
resultForm.setSites(selectableObj);
List<PropertyData> properties = userService.findUserProperty(filterForm.getUserId(), RefCodeNames.PROPERTY_TYPE_CD.DEFAULT_SITE);
if (Utility.isSet(properties)) {
resultForm.setDefaultLocation(properties.get(0).getValue());
}
WebSort.sort(resultForm, SiteListView.SITE_NAME);
return "user/location";
}
@SuccessMessage
@RequestMapping(value = "/update", method = RequestMethod.POST)
public String update(@PathVariable Long userId,
@ModelAttribute(SessionKey.USER_LOCATION_FILTER_RESULT) UserLocationFilterResultForm resultForm) throws Exception {
logger.info("user/location/update()=> BEGIN");
Long storeId = getStoreId();
logger.info("user/location/update()=> userId: " + userId);
logger.info("user/location/update()=> storeId: " + storeId);
List<SiteListView> selected = resultForm.getSites().getSelected();
List<SiteListView> deselected = resultForm.getSites().getNewlyDeselected();
userService.configureUserSitesList(userId,
storeId,
selected,
deselected);
userService.configureUserProperty(userId, RefCodeNames.PROPERTY_TYPE_CD.DEFAULT_SITE, resultForm.getDefaultLocation());
logger.info("user/location/update()=> END.");
return "user/location";
}
@RequestMapping(value = "/filter/sortby/{field}", method = RequestMethod.GET)
public String sort(@ModelAttribute(SessionKey.USER_LOCATION_FILTER_RESULT) UserLocationFilterResultForm form, @PathVariable String field) throws Exception {
WebSort.sort(form, field);
return "user/location";
}
@ModelAttribute(SessionKey.USER_LOCATION_FILTER_RESULT)
public UserLocationFilterResultForm init(HttpSession session) {
logger.info("init()=> init....");
UserLocationFilterResultForm form = (UserLocationFilterResultForm) session.getAttribute(SessionKey.USER_LOCATION_FILTER_RESULT);
logger.info("init()=> form: " + form);
if (form == null) {
form = new UserLocationFilterResultForm();
}
if (Utility.isSet(form.getResult())) {
form.reset();
}
logger.info("init()=> init.OK!");
return form;
}
@ModelAttribute(SessionKey.USER_LOCATION_FILTER)
public UserLocationFilterForm initFilter(HttpSession session, @PathVariable Long userId) {
logger.info("initFilter()=> init....");
UserLocationFilterForm form = (UserLocationFilterForm) session.getAttribute(SessionKey.USER_LOCATION_FILTER);
if (form == null || !form.isInitialized()) {
form = new UserLocationFilterForm(userId);
form.initialize();
}
logger.info("initFilter()=> form: " + form);
logger.info("initFilter()=> init.OK!");
return form;
}
}
|
package it.uniroma3.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class WebController {
@RequestMapping(value={"/","/welcome"})
public String welcome(){
return "welcome";
}
@RequestMapping(value="/admin")
public String admin(){
return "admin";
}
@RequestMapping(value={"/login"})
public String login(){
return "login";
}
@RequestMapping(value={"/logout"})
public String logout(){
return "logout";
}
@RequestMapping(value="/403")
public String Error403(){
return "403";
}
@RequestMapping("/login-error.html")
public String loginError(Model model) {
model.addAttribute("loginError", true);
return "login";
}
@RequestMapping(value="/galleria")
public String gallery(){
return "galleria";
}
}
|
package cqu.shy.calculator;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import cqu.shy.arithmetic.Arithmetic;
import cqu.shy.arithmetic.Element;
import cqu.shy.arithmetic.ElementType;
public class MainActivity extends ActionBarActivity implements View.OnClickListener{
private TextView resultText;
private EditText expText;private RadioButton radianBtn;private RadioButton degreeBtn;
private Button historyBtn;private Button saveBtn;private Button acBtn;
private Button sinBtn;private Button cosBtn;private Button tanBtn;
private Button lnBtn;private Button backspaceBtn;private Button leftPaBtn;
private Button sevenBtn;private Button eightBtn;private Button nineBtn;private Button addBtn;
private Button rightPaBtn;private Button fourBtn;private Button fiveBtn;
private Button sixBtn;private Button subBtn;private Button powBtn;
private Button oneBtn;private Button twoBtn;private Button threeBtn;
private Button multiBtn;private Button sqrtBtn;private Button zeroBtn;
private Button dotBtn;private Button equalBtn;private Button divisionBtn;
private int startIndex=-1,endIndex=-1;
private boolean startInputNum=false;
private boolean equalfinished=false;
private StringBuffer numBuffer = new StringBuffer();
private ArrayList<Element> infix = new ArrayList<Element>(30);
private List<Double> historyDatas = new ArrayList<Double>(10);
private void initVariable(){
startIndex=-1;endIndex=-1;
startInputNum=false;
equalfinished=false;
}
private void initViews(){
expText = (EditText)findViewById(R.id.ExpText);
expText.setOnTouchListener(null);
//expText.setInputType(InputType.TYPE_NULL);
expText.setFocusable(false);
resultText = (TextView)findViewById(R.id.ResultText);
radianBtn = (RadioButton)findViewById(R.id.radianBtn);radianBtn.setOnClickListener(this);
degreeBtn = (RadioButton)findViewById(R.id.degreeBtn);degreeBtn.setOnClickListener(this);
historyBtn = (Button)findViewById(R.id.historyBtn);historyBtn.setOnClickListener(this);
saveBtn = (Button)findViewById(R.id.saveBtn);saveBtn.setOnClickListener(this);
acBtn = (Button)findViewById(R.id.acBtn);acBtn.setOnClickListener(this);
sinBtn = (Button)findViewById(R.id.sinBtn);sinBtn.setOnClickListener(this);
cosBtn = (Button)findViewById(R.id.cosBtn);cosBtn.setOnClickListener(this);
tanBtn = (Button)findViewById(R.id.tanBtn);tanBtn.setOnClickListener(this);
lnBtn = (Button)findViewById(R.id.lnBtn);lnBtn.setOnClickListener(this);
backspaceBtn = (Button)findViewById(R.id.backBtn);backspaceBtn.setOnClickListener(this);
leftPaBtn = (Button)findViewById(R.id.leftPaBtn);leftPaBtn.setOnClickListener(this);
sevenBtn = (Button)findViewById(R.id.sevenBtn);sevenBtn.setOnClickListener(this);
eightBtn = (Button)findViewById(R.id.eightBtn);eightBtn.setOnClickListener(this);
nineBtn = (Button)findViewById(R.id.nineBtn);nineBtn.setOnClickListener(this);
addBtn = (Button)findViewById(R.id.addBtn);addBtn.setOnClickListener(this);
rightPaBtn = (Button)findViewById(R.id.rightPaBtn);rightPaBtn.setOnClickListener(this);
fourBtn = (Button)findViewById(R.id.fourBtn);fourBtn.setOnClickListener(this);
fiveBtn = (Button)findViewById(R.id.fiveBtn);fiveBtn.setOnClickListener(this);
sixBtn = (Button)findViewById(R.id.sixBtn);sixBtn.setOnClickListener(this);
subBtn = (Button)findViewById(R.id.subBtn);subBtn.setOnClickListener(this);
powBtn = (Button)findViewById(R.id.powBtn);powBtn.setOnClickListener(this);
oneBtn = (Button)findViewById(R.id.oneBtn);oneBtn.setOnClickListener(this);
twoBtn = (Button)findViewById(R.id.twoBtn);twoBtn.setOnClickListener(this);
threeBtn = (Button)findViewById(R.id.threeBtn);threeBtn.setOnClickListener(this);
multiBtn = (Button)findViewById(R.id.multiBtn);multiBtn.setOnClickListener(this);
sqrtBtn = (Button)findViewById(R.id.sqrtBtn);sqrtBtn.setOnClickListener(this);
zeroBtn = (Button)findViewById(R.id.zeroBtn);zeroBtn.setOnClickListener(this);
dotBtn = (Button)findViewById(R.id.dotBtn);dotBtn.setOnClickListener(this);
equalBtn = (Button)findViewById(R.id.equalBtn);equalBtn.setOnClickListener(this);
divisionBtn = (Button)findViewById(R.id.divisionBtn);divisionBtn.setOnClickListener(this);
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
@Override
public void onClick(View v) {
switch(v.getId()){
case R.id.radianBtn: //弧度选项被点击
doRadianClicked();
break;
case R.id.degreeBtn: //角度选项被点击
doDegreeClicked();
break;
case R.id.historyBtn://查看历史保存数据
doHistoryClicked();
break;
case R.id.saveBtn: //保存当前计算结果
doSaveClicked();
break;
case R.id.acBtn: //AC被点击
doAcClicked();
break;
case R.id.sinBtn: //sin被点击
doSinClicked();
break;
case R.id.cosBtn: //cos被点击
doCosClicked();
break;
case R.id.tanBtn: //tan被点击
doTanClicked();
break;
case R.id.lnBtn: //log被点击
doLnClicked();
break;
case R.id.backBtn: //退格键被点击
doBackClicked();
break;
case R.id.leftPaBtn: //左括号被点击
doLeftPaClicked();
break;
case R.id.sevenBtn: //7
doSevenClicked();
break;
case R.id.eightBtn: //8
doEightClicked();
break;
case R.id.nineBtn: //9
doNineClicked();
break;
case R.id.addBtn: // 加号
doAddClicked();
break;
case R.id.rightPaBtn: //右括号被点击
doRightPaClicked();
break;
case R.id.fourBtn: //4
doFourClicked();
break;
case R.id.fiveBtn: //5
doFiveClicked();
break;
case R.id.sixBtn: //6
doSixClicked();
break;
case R.id.subBtn: //减号
doSubClicked();
break;
case R.id.powBtn: //次方
doPowClicked();
break;
case R.id.oneBtn: //1
doOneClicked();
break;
case R.id.twoBtn: //2
doTwoClicked();
break;
case R.id.threeBtn: //3
doThreeClicked();
break;
case R.id.multiBtn: //乘号
doMultiClicked();
break;
case R.id.sqrtBtn: //根号
doSqrtClicked();
break;
case R.id.zeroBtn: //0
doZeroClicked();
break;
case R.id.dotBtn: //.
doDotClicked();
break;
case R.id.equalBtn: //=
doEqualClicked();
break;
case R.id.divisionBtn: //除号
doDivisionClicked();
break;
}
}
private void doRadianClicked(){
if(Arithmetic.mode==1){
//已经是弧度制,do nothing
}
else{
Arithmetic.mode=1;
radianBtn.setChecked(true);
degreeBtn.setChecked(false);
}
}
private void doDegreeClicked(){
//TextView t = new TextView(this);
if(Arithmetic.mode==2){
//已经是角度制,do nothing
}
else{
Arithmetic.mode=2;
radianBtn.setChecked(false);
degreeBtn.setChecked(true);
}
}
private void doHistoryClicked(){
if(allowInsertHistory()==0){
Toast.makeText(MainActivity.this,"请不要在小数点后插入数据",Toast.LENGTH_SHORT).show();
return;
}
if(allowInsertHistory()==3){
Toast.makeText(MainActivity.this,"请不要在数字后插入数据",Toast.LENGTH_SHORT).show();
return;
}
if(historyDatas.size()==0){
Toast.makeText(MainActivity.this,"目前没有存储的数据",Toast.LENGTH_SHORT).show();
return;
}
final LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.historydatalayout,
(ViewGroup) findViewById(R.id.historydialog));
final ListView listview = (ListView)layout.findViewById(R.id.listView);
listview.setAdapter(new ArrayAdapter<Double>(this,
android.R.layout.simple_list_item_single_choice, historyDatas));
listview.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
final AlertDialog dialog = new AlertDialog.Builder(this).setTitle("请选择要插入的历史数据,最下面的是最近的数据").setView(layout)
.setNegativeButton("取消",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
}).show();
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Double d = historyDatas.get(position);
if(allowInsertHistory()==1){
Element ele = new Element();
ele.type=ElementType.OPERATION;
ele.length=0;
ele.ope='×';
infix.add(ele);
}
Element ed = new Element();
ed.type=ElementType.NUM;
ed.value = historyDatas.get(position);
ed.length = ed.value.toString().length()+2;
infix.add(ed);
expText.getText().insert(expText.getSelectionStart(),"("+ed.value.toString()+")");
dialog.dismiss();
}
});
}
private void doSaveClicked(){
String value = resultText.getText().toString();
if(value.equals("value invalid") || value.equals("")){
Toast.makeText(MainActivity.this,"不能存储无效值",Toast.LENGTH_SHORT).show();
}
else{
Double d = Double.parseDouble(value);
if(historyDatas.size()>0&&d.equals(historyDatas.get(historyDatas.size()-1))) {
Toast.makeText(MainActivity.this,"该数据已经存储",Toast.LENGTH_SHORT).show();
return;
}
historyDatas.add(d);
Toast.makeText(MainActivity.this,"存储成功",Toast.LENGTH_SHORT).show();
}
}
private void doAcClicked(){
Editable editable = expText.getText();
editable.clear();
infix.clear();
initVariable();
}
private void doSinClicked(){
if(equalfinished) {
doAcClicked();
equalfinished = false;
}
//检查是否在小数点后
System.out.println("sin按钮被点击");
int index = expText.getText().length();
System.out.println("index:"+index);
String text = expText.getText().toString();
if(index>0 && text.charAt(index-1)=='.'){
return;
}
if(startInputNum){
startInputNum=false;
Element ed = new Element();
ed.type=ElementType.NUM;
ed.value = Double.parseDouble(numBuffer.toString());
ed.length=numBuffer.length();
infix.add(ed);
}
//检查是否在数字或者右括号后面,若是,则加一个乘号
if(index>0 && (text.charAt(index-1)==')'||Character.isDigit(text.charAt(index-1)) )){
Element temp = new Element();
temp.type=ElementType.OPERATION;
temp.length=0;
temp.ope='×';
infix.add(temp);
}
String mode;
if(Arithmetic.mode==1)
mode = new String("弧度");
else
mode = new String("角度");
final EditText editText = new EditText(this);
//editText.setInputType(InputType.TYPE_CLASS_NUMBER);
new AlertDialog.Builder(this).setTitle("插入sin函数,请输入" + mode).setIcon(
android.R.drawable.ic_dialog_info).setView(
editText)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = editText.getText().toString();
if (value.matches("^[-+]{0,1}[0-9]+\\.{0,1}[0-9]*$")) {
Double d = Double.parseDouble(value);
if (Arithmetic.mode == 2) {
d = d/180*Math.PI;
}
d = Math.sin(d);
Element t = new Element();
t.length = editText.getText().length() + 5;
t.type = ElementType.FUNCTION;
t.value = d;
infix.add(t);
String s = new String("sin(" + editText.getText().toString() + ")");
expText.getText().insert(expText.length(), s);
try {
Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
field.setAccessible(true);
// 将mShowing变量设为true,表示关闭对话框
field.set(dialog, true);
dialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(MainActivity.this,"请输入正确的数",Toast.LENGTH_SHORT).show();
try {
Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
field.setAccessible(true);
// 将mShowing变量设为false,表示不关闭对话框
field.set(dialog, false);
dialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
try {
Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
field.setAccessible(true);
// 将mShowing变量设为true,表示关闭对话框
field.set(dialog, true);
dialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}).show();
}
private void doCosClicked(){
if(equalfinished) {
doAcClicked();
equalfinished = false;
}
//检查是否在小数点后
int index = expText.getSelectionStart();
String text = expText.getText().toString();
if(index>0 && text.charAt(index-1)=='.'){
return;
}
if(startInputNum){
startInputNum=false;
Element ed = new Element();
ed.type=ElementType.NUM;
ed.value = Double.parseDouble(numBuffer.toString());
ed.length=numBuffer.length();
infix.add(ed);
}
//检查是否在数字或者右括号后面,若是,则加一个乘号
if(index>0 && (text.charAt(index-1)==')'||Character.isDigit(text.charAt(index-1)) )){
Element temp = new Element();
temp.type=ElementType.OPERATION;
temp.length=0;
temp.ope='×';
infix.add(temp);
}
String mode;
if(Arithmetic.mode==1)
mode = new String("弧度");
else
mode = new String("角度");
final EditText editText = new EditText(this);
//editText.setInputType(InputType.TYPE_CLASS_NUMBER);
new AlertDialog.Builder(this).setTitle("插入cos函数,请输入" + mode).setIcon(
android.R.drawable.ic_dialog_info).setView(
editText)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = editText.getText().toString();
if (value.matches("^[-+]{0,1}[0-9]+\\.{0,1}[0-9]*$")) {
Double d = Double.parseDouble(value);
if (Arithmetic.mode == 2) {
d = d/180*Math.PI;
}
d = Math.cos(d);
Element t = new Element();
t.length = editText.getText().length() + 5;
t.type = ElementType.FUNCTION;
t.value = d;
infix.add(t);
String s = new String("cos(" + editText.getText().toString() + ")");
expText.getText().insert(expText.length(), s);
try {
Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
field.setAccessible(true);
// 将mShowing变量设为true,表示关闭对话框
field.set(dialog, true);
dialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(MainActivity.this,"请输入正确的数",Toast.LENGTH_SHORT).show();
try {
Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
field.setAccessible(true);
// 将mShowing变量设为false,表示不关闭对话框
field.set(dialog, false);
dialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
try {
Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
field.setAccessible(true);
// 将mShowing变量设为true,表示关闭对话框
field.set(dialog, true);
dialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}).show();
}
private void doTanClicked(){
if(equalfinished) {
doAcClicked();
equalfinished = false;
}
//检查是否在小数点后
int index = expText.getSelectionStart();
String text = expText.getText().toString();
if(index>0 && text.charAt(index-1)=='.'){
return;
}
if(startInputNum){
startInputNum=false;
Element ed = new Element();
ed.type=ElementType.NUM;
ed.value = Double.parseDouble(numBuffer.toString());
ed.length=numBuffer.length();
infix.add(ed);
}
//检查是否在数字或者右括号后面,若是,则加一个乘号
if(index>0 && (text.charAt(index-1)==')'||Character.isDigit(text.charAt(index-1)) )){
Element temp = new Element();
temp.type=ElementType.OPERATION;
temp.length=0;
temp.ope='×';
infix.add(temp);
}
String mode;
if(Arithmetic.mode==1)
mode = new String("弧度");
else
mode = new String("角度");
final EditText editText = new EditText(this);
//editText.setInputType(InputType.TYPE_CLASS_NUMBER);
new AlertDialog.Builder(this).setTitle("插入tan函数,请输入" + mode).setIcon(
android.R.drawable.ic_dialog_info).setView(
editText)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = editText.getText().toString();
if (value.matches("^[-+]{0,1}[0-9]+\\.{0,1}[0-9]*$")) {
Double d = Double.parseDouble(value);
if (Arithmetic.mode == 2) {
d = d/180*Math.PI;
}
d = Math.tan(d);
Element t = new Element();
t.length = editText.getText().length() + 5;
t.type = ElementType.FUNCTION;
t.value = d;
infix.add(t);
String s = new String("tan(" + editText.getText().toString() + ")");
expText.getText().insert(expText.length(), s);
try {
Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
field.setAccessible(true);
// 将mShowing变量设为true,表示关闭对话框
field.set(dialog, true);
dialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(MainActivity.this,"请输入正确的数",Toast.LENGTH_SHORT).show();
try {
Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
field.setAccessible(true);
// 将mShowing变量设为false,表示不关闭对话框
field.set(dialog, false);
dialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
try {
Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
field.setAccessible(true);
// 将mShowing变量设为true,表示关闭对话框
field.set(dialog, true);
dialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}).show();
}
private void doLnClicked(){
if(equalfinished) {
doAcClicked();
equalfinished = false;
}
//检查是否在小数点后
int index = expText.getSelectionStart();
String text = expText.getText().toString();
if(index>0 && text.charAt(index-1)=='.'){
return;
}
if(startInputNum){
startInputNum=false;
Element ed = new Element();
ed.type=ElementType.NUM;
ed.value = Double.parseDouble(numBuffer.toString());
ed.length=numBuffer.length();
infix.add(ed);
}
//检查是否在数字或者右括号后面,若是,则加一个乘号
if(index>0 && (text.charAt(index-1)==')'||Character.isDigit(text.charAt(index-1)) )){
Element temp = new Element();
temp.type=ElementType.OPERATION;
temp.length=0;
temp.ope='×';
infix.add(temp);
}
final EditText editText = new EditText(this);
//editText.setInputType(InputType.TYPE_CLASS_NUMBER);
new AlertDialog.Builder(this).setTitle("插入ln函数,请输入数值").setIcon(
android.R.drawable.ic_dialog_info).setView(
editText)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = editText.getText().toString();
if (value.matches("^[0-9]+\\.{0,1}[0-9]*$")) {
Double d = Double.parseDouble(value);
d = Math.log(d);
Element t = new Element();
t.length = editText.getText().length() + 4;
t.type = ElementType.FUNCTION;
t.value = d;
infix.add(t);
String s = new String("ln(" + editText.getText().toString() + ")");
expText.getText().insert(expText.length(), s);
try {
Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
field.setAccessible(true);
// 将mShowing变量设为true,表示关闭对话框
field.set(dialog, true);
dialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(MainActivity.this,"请输入正数",Toast.LENGTH_SHORT).show();
try {
Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
field.setAccessible(true);
// 将mShowing变量设为false,表示不关闭对话框
field.set(dialog, false);
dialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
try {
Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
field.setAccessible(true);
// 将mShowing变量设为true,表示关闭对话框
field.set(dialog, true);
dialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}).show();
}
private void doBackClicked(){
if(equalfinished) {
doAcClicked();
equalfinished = false;
}
int index = expText.getSelectionStart();
Editable editable = expText.getText();
if(infix.size()>0){
if(!startInputNum)
{
Element toBeDelete=infix.get(infix.size()-1);
if(toBeDelete.length!=0) {
int length = toBeDelete.length;
int delStart = index - length;
if (delStart < 0)
delStart = 0;
editable.delete(delStart, index);
infix.remove(infix.size() - 1);
if (editable.length() == 0) {
initVariable();
}
}
else{
infix.remove(infix.size()-1);
doBackClicked();
}
}
else{
numBuffer.deleteCharAt(numBuffer.length()-1);
editable.delete(index-1,index);
if(numBuffer.length()==0)
startInputNum=false;
}
}
else{
if(startInputNum){
numBuffer.deleteCharAt(numBuffer.length()-1);
editable.delete(index-1,index);
if(numBuffer.length()==0)
startInputNum=false;
}
}
}
private void doLeftPaClicked(){
if(equalfinished) {
doAcClicked();
equalfinished = false;
}
//检查是否在小数点后
int index = expText.getSelectionStart();
String text = expText.getText().toString();
if(index>0 && text.charAt(index-1)=='.'){
return;
}
//检查是否在数字或者函数右括号后面,若是,则加一个乘号
if(index>0 && (text.charAt(index-1)==')'||Character.isDigit(text.charAt(index-1)))){
Element temp = new Element();
temp.type=ElementType.OPERATION;
temp.length=0;
temp.ope='×';
infix.add(temp);
}
if(startInputNum) {
startInputNum = false;
}
expText.getText().insert(expText.getSelectionStart(),"(");
Element ele = new Element();
ele.type=ElementType.OPERATION;
ele.length=1;
ele.ope='(';
infix.add(ele);
}
private void doSevenClicked(){
if(equalfinished) {
doAcClicked();
equalfinished = false;
}
int index = expText.getSelectionStart();
String text = expText.getText().toString();
//检查是否在右括号后面,若是,则加一个乘号
if(!startInputNum && (index>0 && (text.charAt(index-1)==')'||Character.isDigit(text.charAt(index-1))))){
Element temp = new Element();
temp.type=ElementType.OPERATION;
temp.length=0;
temp.ope='×';
infix.add(temp);
}
if(!startInputNum){
numBuffer.delete(0,numBuffer.length());
startInputNum=true;
}
numBuffer.append("7");
expText.getText().insert(expText.getSelectionStart(),"7");
}
private void doEightClicked(){
if(equalfinished) {
doAcClicked();
equalfinished = false;
}
int index = expText.getSelectionStart();
String text = expText.getText().toString();
//检查是否在右括号后面,若是,则加一个乘号
if(!startInputNum && (index>0 && (text.charAt(index-1)==')'||Character.isDigit(text.charAt(index-1))))){
Element temp = new Element();
temp.type=ElementType.OPERATION;
temp.length=0;
temp.ope='×';
infix.add(temp);
}
if(!startInputNum){
numBuffer.delete(0,numBuffer.length());
startInputNum=true;
}
numBuffer.append("8");
expText.getText().insert(expText.getSelectionStart(),"8");
}
private void doNineClicked(){
if(equalfinished) {
doAcClicked();
equalfinished = false;
}
int index = expText.getSelectionStart();
String text = expText.getText().toString();
//检查是否在右括号后面,若是,则加一个乘号
if(!startInputNum && (index>0 && (text.charAt(index-1)==')'||Character.isDigit(text.charAt(index-1))))){
Element temp = new Element();
temp.type=ElementType.OPERATION;
temp.length=0;
temp.ope='×';
infix.add(temp);
}
if(!startInputNum){
numBuffer.delete(0,numBuffer.length());
startInputNum=true;
}
numBuffer.append("9");
expText.getText().insert(expText.getSelectionStart(),"9");
}
private void doAddClicked(){
if(equalfinished) {
doAcClicked();
equalfinished = false;
}
//检查是否在小数点或者运算符后
int index = expText.getSelectionStart();
String text = expText.getText().toString();
if(index>0 && (text.charAt(index-1)=='.' || isOpe(text.charAt(index-1)))){
return;
}
if(startInputNum){
startInputNum=false;
Double d = Double.parseDouble(numBuffer.toString());
Element ed = new Element();
ed.type=ElementType.NUM;
ed.length = numBuffer.length();
ed.value=d;
infix.add(ed);
}
if(index==0 || text.charAt(index-1)=='('){
//添加一个0
Element ele = new Element();
ele.type=ElementType.NUM;
ele.length=0;
ele.value=0.0;
infix.add(ele);
}
Element ea = new Element();
ea.type=ElementType.OPERATION;
ea.ope='+';
ea.length=1;
infix.add(ea);
expText.getText().insert(expText.length(),"+");
}
private void doRightPaClicked(){
if(equalfinished) {
doAcClicked();
equalfinished = false;
}
//检查是否在小数点或者运算符后
int index = expText.getSelectionStart();
String text = expText.getText().toString();
if(index==0 || (index>0 && (text.charAt(index-1)=='.' || isOpe(text.charAt(index-1))))){
return;
}
if(startInputNum){
startInputNum=false;
Double d = Double.parseDouble(numBuffer.toString());
Element ed = new Element();
ed.type=ElementType.NUM;
ed.length = numBuffer.length();
ed.value=d;
infix.add(ed);
}
Element er = new Element();
er.type=ElementType.OPERATION;
er.ope=')';
er.length=1;
infix.add(er);
expText.getText().insert(expText.length(),")");
}
private void doFourClicked(){
if(equalfinished) {
doAcClicked();
equalfinished = false;
}
int index = expText.getSelectionStart();
String text = expText.getText().toString();
//检查是否在右括号后面,若是,则加一个乘号
if(!startInputNum && (index>0 && (text.charAt(index-1)==')'||Character.isDigit(text.charAt(index-1))))){
Element temp = new Element();
temp.type=ElementType.OPERATION;
temp.length=0;
temp.ope='×';
infix.add(temp);
}
if(!startInputNum){
numBuffer.delete(0,numBuffer.length());
startInputNum=true;
}
numBuffer.append("4");
expText.getText().insert(expText.getSelectionStart(),"4");
}
private void doFiveClicked(){
if(equalfinished) {
doAcClicked();
equalfinished = false;
}
int index = expText.getSelectionStart();
String text = expText.getText().toString();
//检查是否在右括号后面,若是,则加一个乘号
if(!startInputNum && (index>0 && (text.charAt(index-1)==')'||Character.isDigit(text.charAt(index-1))))){
Element temp = new Element();
temp.type=ElementType.OPERATION;
temp.length=0;
temp.ope='×';
infix.add(temp);
}
if(!startInputNum){
numBuffer.delete(0,numBuffer.length());
startInputNum=true;
}
numBuffer.append("5");
expText.getText().insert(expText.getSelectionStart(),"5");
}
private void doSixClicked(){
if(equalfinished) {
doAcClicked();
equalfinished = false;
}
int index = expText.getSelectionStart();
String text = expText.getText().toString();
//检查是否在右括号后面,若是,则加一个乘号
if(!startInputNum && (index>0 && (text.charAt(index-1)==')'||Character.isDigit(text.charAt(index-1))))){
Element temp = new Element();
temp.type=ElementType.OPERATION;
temp.length=0;
temp.ope='×';
infix.add(temp);
}
if(!startInputNum){
numBuffer.delete(0,numBuffer.length());
startInputNum=true;
}
numBuffer.append("6");
expText.getText().insert(expText.getSelectionStart(),"6");
}
private void doSubClicked(){
if(equalfinished) {
doAcClicked();
equalfinished = false;
}
//检查是否在小数点或者运算符后
int index = expText.getSelectionStart();
String text = expText.getText().toString();
if(index>0 && (text.charAt(index-1)=='.' || isOpe(text.charAt(index-1)))){
return;
}
if(startInputNum){
startInputNum=false;
Double d = Double.parseDouble(numBuffer.toString());
Element ed = new Element();
ed.type=ElementType.NUM;
ed.length = numBuffer.length();
ed.value=d;
infix.add(ed);
}
if(index==0 || text.charAt(index-1)=='('){
//添加一个0
Element ele = new Element();
ele.type=ElementType.NUM;
ele.length=0;
ele.value=0.0;
infix.add(ele);
}
Element ea = new Element();
ea.type=ElementType.OPERATION;
ea.ope='-';
ea.length=1;
infix.add(ea);
expText.getText().insert(expText.length(),"-");
}
private void doPowClicked(){
if(equalfinished) {
doAcClicked();
equalfinished = false;
}
int index = expText.getSelectionStart();
String text = expText.getText().toString();
if(index>0 && text.charAt(index-1)=='.'){
return;
}
if(startInputNum){
startInputNum=false;
Element ed = new Element();
ed.type=ElementType.NUM;
ed.value = Double.parseDouble(numBuffer.toString());
ed.length=numBuffer.length();
infix.add(ed);
}
//检查是否在数字或者右括号后面,若是,则加一个乘号
if(index>0 && (text.charAt(index-1)==')'||Character.isDigit(text.charAt(index-1)) )){
Element temp = new Element();
temp.type=ElementType.OPERATION;
temp.length=0;
temp.ope='×';
infix.add(temp);
}
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.powdialoglayout,
(ViewGroup) findViewById(R.id.powdialog));
final EditText powXtext = (EditText)layout.findViewById(R.id.powXtext);
final EditText powYtext = (EditText)layout.findViewById(R.id.powYtext);
new AlertDialog.Builder(this).setTitle("幂函数,X^Y,请分别输入X和Y").setView(layout)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String valueX = powXtext.getText().toString();
String valueY = powYtext.getText().toString();
if (valueX.matches("^[-+]{0,1}[0-9]+\\.{0,1}[0-9]*$") && valueY.matches("^[-+]{0,1}[0-9]+\\.{0,1}[0-9]*$")) {
Double dX = Double.parseDouble(valueX);
Double dY = Double.parseDouble(valueY);
Double d = Math.pow(dX,dY);
Element t = new Element();
t.length = powXtext.getText().length()+powYtext.getText().length()+3;
t.type = ElementType.FUNCTION;
t.value = d;
infix.add(t);
String s = new String("("+powXtext.getText().toString()+"^"+powYtext.getText().toString()+")");
expText.getText().insert(expText.length(), s);
try {
Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
field.setAccessible(true);
// 将mShowing变量设为true,表示关闭对话框
field.set(dialog, true);
dialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(MainActivity.this,"请输入正确的X和Y",Toast.LENGTH_SHORT).show();
try {
Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
field.setAccessible(true);
// 将mShowing变量设为false,表示不关闭对话框
field.set(dialog, false);
dialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
try {
Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
field.setAccessible(true);
// 将mShowing变量设为true,表示关闭对话框
field.set(dialog, true);
dialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}).show();
}
private void doOneClicked(){
if(equalfinished) {
doAcClicked();
equalfinished = false;
}
int index = expText.getSelectionStart();
String text = expText.getText().toString();
//检查是否在右括号后面,若是,则加一个乘号
if(!startInputNum && (index>0 && (text.charAt(index-1)==')'||Character.isDigit(text.charAt(index-1))))){
Element temp = new Element();
temp.type=ElementType.OPERATION;
temp.length=0;
temp.ope='×';
infix.add(temp);
}
if(!startInputNum){
numBuffer.delete(0,numBuffer.length());
startInputNum=true;
}
numBuffer.append("1");
expText.getText().insert(expText.getSelectionStart(),"1");
}
private void doTwoClicked(){
if(equalfinished) {
doAcClicked();
equalfinished = false;
}
int index = expText.getSelectionStart();
String text = expText.getText().toString();
//检查是否在右括号后面,若是,则加一个乘号
if(!startInputNum && (index>0 && (text.charAt(index-1)==')'||Character.isDigit(text.charAt(index-1))))){
Element temp = new Element();
temp.type=ElementType.OPERATION;
temp.length=0;
temp.ope='×';
infix.add(temp);
}
if(!startInputNum){
numBuffer.delete(0,numBuffer.length());
startInputNum=true;
}
numBuffer.append("2");
expText.getText().insert(expText.getSelectionStart(),"2");
}
private void doThreeClicked(){
if(equalfinished) {
doAcClicked();
equalfinished = false;
}
int index = expText.getSelectionStart();
String text = expText.getText().toString();
//检查是否在右括号后面,若是,则加一个乘号
if(!startInputNum && (index>0 && (text.charAt(index-1)==')'||Character.isDigit(text.charAt(index-1))))){
Element temp = new Element();
temp.type=ElementType.OPERATION;
temp.length=0;
temp.ope='×';
infix.add(temp);
}
if(!startInputNum){
numBuffer.delete(0,numBuffer.length());
startInputNum=true;
}
numBuffer.append("3");
expText.getText().insert(expText.getSelectionStart(),"3");
}
private void doMultiClicked(){
if(equalfinished) {
doAcClicked();
equalfinished = false;
}
int index = expText.getSelectionStart();
String text = expText.getText().toString();
if(index==0 || (index>0 && (text.charAt(index-1)=='.' || isOpe(text.charAt(index-1)) ||
text.charAt(index-1)=='(' )) ){
return;
}
if(startInputNum){
startInputNum=false;
Double d = Double.parseDouble(numBuffer.toString());
Element ed = new Element();
ed.type=ElementType.NUM;
ed.length = numBuffer.length();
ed.value=d;
infix.add(ed);
}
Element em = new Element();
em.type=ElementType.OPERATION;
em.length=1;
em.ope='×';
infix.add(em);
expText.getText().insert(expText.getSelectionStart(),"×");
}
private void doSqrtClicked(){
if(equalfinished) {
doAcClicked();
equalfinished = false;
}
int index = expText.getSelectionStart();
String text = expText.getText().toString();
if(index>0 && text.charAt(index-1)=='.'){
return;
}
if(startInputNum){
startInputNum=false;
Element ed = new Element();
ed.type=ElementType.NUM;
ed.value = Double.parseDouble(numBuffer.toString());
ed.length=numBuffer.length();
infix.add(ed);
}
//检查是否在数字或者右括号后面,若是,则加一个乘号
if(index>0 && (text.charAt(index-1)==')'||Character.isDigit(text.charAt(index-1)) )){
Element temp = new Element();
temp.type=ElementType.OPERATION;
temp.length=0;
temp.ope='×';
infix.add(temp);
}
final EditText editText = new EditText(this);
editText.setInputType(InputType.TYPE_CLASS_NUMBER);
new AlertDialog.Builder(this).setTitle("插入平方根函数,请输入数值").setIcon(
android.R.drawable.ic_dialog_info).setView(
editText)
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String value = editText.getText().toString();
if (value.matches("^[0-9]+\\.{0,1}[0-9]*$")) {
Double d = Double.parseDouble(value);
d = Math.sqrt(d);
Element t = new Element();
t.length = editText.getText().length() + 3;
t.type = ElementType.FUNCTION;
t.value = d;
infix.add(t);
String s = new String("√(" + editText.getText().toString() + ")");
expText.getText().insert(expText.length(), s);
try {
Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
field.setAccessible(true);
// 将mShowing变量设为true,表示关闭对话框
field.set(dialog, true);
dialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
} else {
Toast.makeText(MainActivity.this,"请输入正数",Toast.LENGTH_SHORT).show();
try {
Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
field.setAccessible(true);
// 将mShowing变量设为false,表示不关闭对话框
field.set(dialog, false);
dialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
try {
Field field = dialog.getClass().getSuperclass().getDeclaredField("mShowing");
field.setAccessible(true);
// 将mShowing变量设为true,表示关闭对话框
field.set(dialog, true);
dialog.dismiss();
} catch (Exception e) {
e.printStackTrace();
}
}
}).show();
}
private void doZeroClicked(){
if(equalfinished) {
doAcClicked();
equalfinished = false;
}
int index = expText.getSelectionStart();
String text = expText.getText().toString();
//检查是否在右括号后面,若是,则加一个乘号
if(!startInputNum && (index>0 && (text.charAt(index-1)==')'||Character.isDigit(text.charAt(index-1))))){
Element temp = new Element();
temp.type=ElementType.OPERATION;
temp.length=0;
temp.ope='×';
infix.add(temp);
}
if(!startInputNum){
numBuffer.delete(0,numBuffer.length());
startInputNum=true;
}
numBuffer.append("0");
expText.getText().insert(expText.getSelectionStart(),"0");
}
private void doDotClicked(){
if(equalfinished) {
doAcClicked();
equalfinished = false;
}
int index = expText.getSelectionStart();
String text = expText.getText().toString();
if(index==0 || ( index>0 && (text.charAt(index-1)=='.' || isOpe(text.charAt(index-1)) ||
text.charAt(index-1)=='(' || text.charAt(index-1)==')') ) ){
return;
}
if(startInputNum){
numBuffer.append(".");
expText.getText().insert(expText.getSelectionStart(),".");
}
}
private void doEqualClicked(){
if(startInputNum){
startInputNum=false;
Double d = Double.parseDouble(numBuffer.toString());
Element ed = new Element();
ed.type=ElementType.NUM;
ed.length = numBuffer.length();
ed.value=d;
infix.add(ed);
}
String result = Arithmetic.getResult(infix);
if(result.equals("表达式输入有误")){
Toast.makeText(MainActivity.this,"表达式输入有误",Toast.LENGTH_SHORT).show();
}
else
resultText.setText(result);
equalfinished=true;
}
private void doDivisionClicked(){
if(equalfinished) {
doAcClicked();
equalfinished = false;
}
int index = expText.getSelectionStart();
String text = expText.getText().toString();
if(index==0 || (index>0 && (text.charAt(index-1)=='.' || isOpe(text.charAt(index-1)) ||
text.charAt(index-1)=='(' )) ){
return;
}
if(startInputNum){
startInputNum=false;
Double d = Double.parseDouble(numBuffer.toString());
Element ed = new Element();
ed.type=ElementType.NUM;
ed.length = numBuffer.length();
ed.value=d;
infix.add(ed);
}
Element em = new Element();
em.type=ElementType.OPERATION;
em.length=1;
em.ope='/';
infix.add(em);
expText.getText().insert(expText.getSelectionStart(),"/");
}
private boolean isOpe(char c){
if(c=='+' || c=='-' || c=='×' || c=='/')
return true;
else
return false;
}
private int allowInsertHistory(){
if(startInputNum)
return 3;
int index = expText.getSelectionStart();
String text = expText.getText().toString();
if(index>0 && text.charAt(index-1)=='.'){
return 0;
}
else if(index>0 && Character.isDigit(text.charAt(index-1)))
return 3;
else if(index>0 && text.charAt(index-1)==')')
return 1;
else
return 2;
}
}
|
package dev.gerardo.shortener.utils;
import java.util.Random;
public class YahooShortener implements Shortener {
@Override
public String processUrl(String url) {
Random rd = new Random();
int cont = 0;
String validCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvxyz0123456789";
String shortenedtUrl = "";
while(cont < 7) {
char letter = validCharacters.charAt(rd.nextInt(validCharacters.length()));
shortenedtUrl += String.valueOf(letter);
cont ++;
}
return shortenedtUrl;
}
}
|
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;
public class 插入语句 {
public static void main(String[] args) {
ResourceBundle bundle = ResourceBundle.getBundle("JDBC配置文件");
String url = bundle.getString("url");
String user = bundle.getString("user");
String password = bundle.getString("password");
String driver = bundle.getString("Driver");
Statement stm = null;
ResultSet rs = null;
Connection conn = null;
// 1:注册驱动,但我貌似发现不需要注册驱动也能加载到
try {
// DriverManager.registerDriver(new com.mysql.jdbc.Driver()); // 因为Driver中有个静态代码块,只要加载这个类就可以注册驱动,所以采用反射机制来写
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
// 2:获取连接
try {
conn = DriverManager.getConnection(url,user,password);
System.out.println("MySQL数据库连接成功!"+conn);
// 3:获取数据库操作对象。Statement是专门用来执行 sql 语句的
stm = conn.createStatement();
// 4:执行 sql。
String sql01 = "select * from emp";
String sql02 = "insert into emp(empno,ename,job,mgr,hiredate,sal,comm,deptno) values(1001,'毛不易掉的牙刷','程序员',null,'2021-02-21',8000,500,40)";
String sql03 = "delete from emp where emp.ename='毛不易掉的牙刷'";
stm.executeUpdate(sql03);
int count = stm.executeUpdate(sql02);
System.out.println(count == 1? "插入成功" : "插入失败");
// 5:处理查询结果集
//ResultSet就是结果集,全部提取出来需要迭代
rs = stm.executeQuery(sql01);
while(rs.next()) {
String empno = rs.getString(1);
String ename = rs.getString(2);
String JOB = rs.getString(3);
String mgr = rs.getString(4);
String HIREDATE = rs.getString(5);
String SAL = rs.getString(6);
String COMM = rs.getString(7);
String DEPTNO = rs.getString(8);
System.out.println(empno+","+ename+","+JOB+","+mgr+","+HIREDATE+","+SAL+","+COMM+","+DEPTNO);
System.out.println();
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
// 6:释放资源,写在finally中,并且要遵循从小到大的顺序依次关闭,因为有异常,所以还要注意分别对其 try catch,即:先关查询结果集,再关数据库操作对象,最后关连接
if(rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stm != null) {
try {
stm.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
|
package br.org.funcate.glue.model.cache;
/**
* @author Juliana \brief Enum that represents the types that a tile could be.
*/
public enum TileType {
GOOGLE, WMS, TERRALIB, OPENSTREET , CGI , INSTITUTO;
public String toString() {
if (this == GOOGLE) {
return "Google";
} else if (this == WMS) {
return "WMS";
} else if (this == OPENSTREET){
return "OpenStreet";
} else if (this == CGI){
return "CGI";
} else if (this == INSTITUTO){
return "INSTITUTO";
}
return "TerraLib";
}
}
|
package com.aitest.web.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.aitest.web.entity.CategoryEntity;
@Repository
@Transactional
public interface CategoryMapper {
public List<CategoryEntity> getAllCategory();
public CategoryEntity getCategoryById(@Param(value="categoryId")String categoryId);
}
|
package camel.serial;
/**
* Parse a given uri and set the configuration for the specified parameters in the uri
*
*/
public class SerialConfiguration {
private String portName;
private int baudrate;
private int databits;
private int stopbits;
/**
* PARITY_ODD = 1;
* PARITY_EVEN = 2;
* PARITY_MARK = 3;
* PARITY_SPACE = 4;
*/
private int parity;
public String getPortName() {
return portName;
}
public void setPortName(String portName) {
this.portName = portName;
}
public int getBaudrate() {
return baudrate;
}
public void setBaudrate(int baudrate) {
this.baudrate = baudrate;
}
public int getDatabits() {
return databits;
}
public void setDatabits(int databits) {
this.databits = databits;
}
public int getStopbits() {
return stopbits;
}
public void setStopbits(int stopbits) {
this.stopbits = stopbits;
}
public int getParity() {
return parity;
}
public void setParity(int parity) {
this.parity = parity;
}
}
|
/*
* 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 zip;
import java.io.File;
import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
/**
*
* @author Ahmed
*/
public class ZipApp extends javax.swing.JFrame {
JFileChooser fChooser = new JFileChooser();
File sourceFile = null;
File destinationFile = null;
public ZipApp() {
initComponents();
ImageIcon icon = new ImageIcon(getClass().getResource("icon.jpg"));
this.setIconImage(icon.getImage());
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jPanel1 = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
txtdestination = new javax.swing.JTextField();
txtSource = new javax.swing.JTextField();
btnSource = new javax.swing.JButton();
btnDestination = new javax.swing.JButton();
btnSave = new javax.swing.JButton();
btnCancel = new javax.swing.JButton();
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 100, Short.MAX_VALUE)
);
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Zip Converter");
setLocation(new java.awt.Point(300, 150));
jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel1.setForeground(new java.awt.Color(0, 0, 153));
jLabel1.setText("Zip Converter");
jLabel2.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel2.setForeground(new java.awt.Color(0, 0, 153));
jLabel2.setText("source file");
jLabel3.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
jLabel3.setForeground(new java.awt.Color(0, 0, 153));
jLabel3.setText("destination");
txtdestination.setText("C:\\Users\\Ahmed\\Documents/");
txtSource.setText("C:\\Users\\Ahmed\\Documents/");
btnSource.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
btnSource.setForeground(new java.awt.Color(102, 0, 102));
btnSource.setText("browse");
btnSource.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
btnSource.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSourceActionPerformed(evt);
}
});
btnDestination.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
btnDestination.setForeground(new java.awt.Color(102, 0, 102));
btnDestination.setText("browse");
btnDestination.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
btnDestination.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnDestinationActionPerformed(evt);
}
});
btnSave.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
btnSave.setForeground(new java.awt.Color(102, 0, 102));
btnSave.setText("Save");
btnSave.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
btnSave.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSaveActionPerformed(evt);
}
});
btnCancel.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
btnCancel.setForeground(new java.awt.Color(102, 0, 102));
btnCancel.setText("cancel");
btnCancel.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
btnCancel.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnCancelActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(48, 48, 48)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addComponent(jLabel3)
.addComponent(jLabel2))
.addGap(34, 34, 34)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addGroup(layout.createSequentialGroup()
.addComponent(txtSource, javax.swing.GroupLayout.PREFERRED_SIZE, 292, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btnSource, javax.swing.GroupLayout.DEFAULT_SIZE, 105, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(txtdestination)
.addGap(18, 18, 18)
.addComponent(btnDestination, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE))))
.addGroup(layout.createSequentialGroup()
.addGap(304, 304, 304)
.addComponent(jLabel1)))
.addContainerGap(11, Short.MAX_VALUE))
.addGroup(layout.createSequentialGroup()
.addGap(122, 122, 122)
.addComponent(btnSave, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(159, 159, 159))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(21, 21, 21)
.addComponent(jLabel1)
.addGap(77, 77, 77)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(txtSource, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnSource))
.addGap(62, 62, 62)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(txtdestination, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel3)
.addComponent(btnDestination))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 73, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(btnSave)
.addComponent(btnCancel))
.addGap(76, 76, 76))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void btnCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelActionPerformed
System.exit(0);
}//GEN-LAST:event_btnCancelActionPerformed
private void btnSourceActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSourceActionPerformed
int result = fChooser.showOpenDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
sourceFile = fChooser.getSelectedFile();
txtSource.setText(sourceFile.getAbsolutePath());
}
}//GEN-LAST:event_btnSourceActionPerformed
private void btnDestinationActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDestinationActionPerformed
int result = fChooser.showSaveDialog(this);
if (result == JFileChooser.APPROVE_OPTION) {
destinationFile = fChooser.getSelectedFile();
txtdestination.setText(destinationFile.getAbsolutePath());
}
}//GEN-LAST:event_btnDestinationActionPerformed
private void btnSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveActionPerformed
try {
if (sourceFile.exists() && destinationFile != null) {
Progress progressForm = new Progress();
ProcessBuilder server = new ProcessBuilder("ZipServer.exe");
try {
server.start();
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "server not found+++" + e.getMessage());
}
//start zip the file
zip.Client c = new zip.Client(sourceFile.getAbsolutePath(), destinationFile.getAbsolutePath(), progressForm);
c.start();
} else {
JOptionPane.showMessageDialog(this, "invalied input");
}
} catch (Exception ex) {
JOptionPane.showMessageDialog(this, "error invalied input ");
}
}//GEN-LAST:event_btnSaveActionPerformed
/**
* @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(ZipApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(ZipApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(ZipApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(ZipApp.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new ZipApp().setVisible(true);
}
});
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnCancel;
private javax.swing.JButton btnDestination;
private javax.swing.JButton btnSave;
private javax.swing.JButton btnSource;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JTextField txtSource;
private javax.swing.JTextField txtdestination;
// End of variables declaration//GEN-END:variables
}
|
import java.util.Scanner;
// 연결 요소의 개수
public class p11724 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int N = sc.nextInt();
int M = sc.nextInt();
Graph11724 graph = new Graph11724(N);
for (int i = 0; i < M; i++) {
graph.addVertex(sc.nextInt(), sc.nextInt());
}
graph.search();
}
}
class Graph11724 {
private int n;
private int[][] graph;
private boolean[] visited;
private int nCC;
public Graph11724(int n) {
this.n = n;
this.graph = new int[n][n];
this.visited = new boolean[n];
this.nCC = 0;
}
public void addVertex (int x, int y) {
this.graph[x-1][y-1] = this.graph[y-1][x-1] = 1;
}
public void search() {
for (int i = 0; i < this.n; i++) {
if (!visited[i]) {
dfs(i);
nCC++;
}
}
System.out.println(nCC);
}
private void dfs(int s) {
visited[s] = true;
for (int i = 0; i < this.n; i++) {
if (this.graph[s][i] == 1 && !visited[i]) {
dfs(i);
}
}
}
}
|
package service;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* Created by iriemo on 4/6/15.
*/
public class Server extends Service {
Messenger messenger = new Messenger(new LocalHandler());
Messenger clientMessenger;
public static final int SystemTime = 0;
public static final int AddHandler = 1;
List<Handler> mHandlers;
@Override
public void onCreate() {
super.onCreate();
mHandlers = new ArrayList<Handler>();
}
@Override
public IBinder onBind(Intent intent) {
return messenger.getBinder();
}
public class LocalHandler extends Handler {
@Override
public void handleMessage(Message msg) {
switch (msg.what){
case SystemTime:
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try{
clientMessenger.send(Message.obtain(null, SystemTime, dateFormat.format(new Date())));
} catch (RemoteException e) {
e.printStackTrace();
}
break;
case AddHandler:
clientMessenger = new Messenger((Handler)msg.obj);
try {
clientMessenger.send(Message.obtain(null, AddHandler, "Registered messenger"));
} catch (RemoteException e) {
e.printStackTrace();
}
break;
default:
break;
}
super.handleMessage(msg);
}
}
}
|
package demo;
// 返回她可以在 H 小时内吃掉所有喵粮的最小速度 K(K 为整数)。
// 3 6 7 11
// 8
// 4
import java.util.Arrays;
import java.util.Scanner;
public class CatEatFood {
public static void main(String[] args) {
// Scanner sc = new Scanner(System.in);
// String str1 = sc.nextLine();
// int h = sc.nextInt();
String str1 = "3";
int h = 1;
String[] s = str1.split(" ");
int total = 0;
int[] arr = new int[s.length];
for (int i = 0; i < s.length; i++) {
arr[i] = Integer.parseInt(s[i]);
total += arr[i];
}
int k = total / h; // 每个小时最少的食量
while (true) {
int sum = 0;
for (int num : arr) {
sum += (num + k - 1) / k; // 上取整
}
if (sum == h) {
break;
}
k++;
}
System.out.println(k);
}
}
|
import java.awt.Button;
import java.awt.Label;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
@SuppressWarnings("serial")
public class TTTGUI extends JFrame implements ActionListener
{
TTTGame theGame;
Button start;
Label title;
Button [] board;
Label WL;
Button again;
public TTTGUI()
{
again = new Button("NEW GAME");
again.setBounds(100, 200, 100, 20);
again.setVisible(false);
again.addActionListener(this);
add(again);
theGame = new TTTGame();
WL = new Label("");
WL.setBounds(75, 100, 200, 100);
WL.setVisible(false);
add(WL);
setTitle("TIC TAC TOE");
setSize(300,320);
setDefaultCloseOperation(EXIT_ON_CLOSE);
title = new Label("WELCOME TO TIC TAC TOE");
title.setBounds(70, 100, 200, 20);
add(title);
start = new Button("START");
start.setBounds(100, 200, 100, 20);
start.addActionListener(this);
add(start);
board = new Button [9];
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource() == start)
{
start.setVisible(false);
title.setVisible(false);
renderBoard(theGame.getBoard());
}
else if(e.getSource() == again)
{
theGame = new TTTGame();
renderBoard(theGame.getBoard());
}
else
{
if(theGame.isFull())
{
WL.setText("DRAW");
WL.setBounds(125, 100, 200, 100);
WL.setVisible(true);
again.setVisible(true);
for(int i = 0; i < 9; i ++)
{
board[i].setVisible(false);
}
}
if(!(theGame.checkWin('O')))
{
Button temp = (Button) e.getSource();
int index = 0;
for(int i = 0; i < 9; i ++)
{
if(board[i] == temp)
{
index = i;
}
}
if(theGame.userInput(index/3 + 1, index%3 + 1))
{
updateBoard(theGame.getBoard());
if(!theGame.checkWin('X'))
{
theGame.aiInput();
updateBoard(theGame.getBoard());
}
else
{
for(int i = 0; i < 9; i ++)
{
board[i].setVisible(false);
}
}
}
}
else if(theGame.checkWin('O'))
{
//OWIN
for(int i = 0; i < 9; i ++)
{
WL.setText("COMPUTER WINS");
again.setVisible(true);
WL.setBounds(100, 100, 200, 100);
WL.setVisible(true);
board[i].setVisible(false);
}
}
}
}
public void renderBoard(char [] a)
{
again.setVisible(false);
WL.setVisible(false);
for(int i = 0; i < 9; i++)
{
board[i] = new Button(""+a[i]);
board[i].setBackground(Color.BLACK);
board[i].setVisible(true);
board[i].setBounds((i%3) *100, (i/3) *100, 100, 100);
board[i].setFont(getFont().deriveFont(40.0f));
board[i].addActionListener(this);
add(board[i]);
}
}
public void updateBoard(char [] a)
{
for(int i = 0; i < 9; i++)
{
board[i].setLabel(a[i] + "");;
}
}
public static void main(String [] args)
{
TTTGUI a = new TTTGUI();
}
}
|
class bokCar{
int year;
int mileage;
static int numOfCars;
public bokCar(){
numOfCars++;
}
public bokCar(int year){
this();
this.year=year;
}
public bokCar(int year, int mileage){
this(year);
this.mileage=mileage;
numOfCars++;
}
}
class bCar{
public static void main(String [] args){
bokCar [] carList = new bokCar [10];
for(int i=0; i<10; i++){
carList[i]= new bokCar(2010+i);
}
System.out.print("총 자동차 대수:"+bokCar.numOfCars);
}
}
|
package com.xiaoma.dd.service.impl;
import com.xiaoma.dd.dto.CompCreateParam;
import com.xiaoma.dd.mapper.CompanyMapper;
import com.xiaoma.dd.mapper.CompanyStaffMapper;
import com.xiaoma.dd.pojo.Company;
import com.xiaoma.dd.pojo.CompanyExample;
import com.xiaoma.dd.pojo.CompanyStaff;
import com.xiaoma.dd.pojo.CompanyStaffExample;
import com.xiaoma.dd.service.CompService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class CompServiceImpl implements CompService {
@Autowired
private CompanyStaffMapper companyStaffMapper;
@Autowired
private CompanyMapper companyMapper;
@Override
public boolean checkHasComp(int uid) {
CompanyStaffExample example = new CompanyStaffExample();
example.createCriteria().andUidEqualTo(uid);
List<CompanyStaff> list = companyStaffMapper.selectByExample(example);
if (list.size() > 0)
return true;
return false;
}
@Override
public boolean createComp(CompCreateParam param, int createUid) {
Company company = new Company();
company.setName(param.getName());
company.setRepName(param.getRepName());
company.setCreateMoney(param.getCreateMoney());
company.setCreateTime(param.getCreateTime());
company.setTel(param.getTel());
company.setAddress(param.getAddress());
company.setCreateUid(createUid);
CompanyExample example = new CompanyExample();
example.createCriteria();
long count = companyMapper.countByExample(example);
System.out.println("------------------------------"+count);
if (count == 0) {
company.setId(1);
}
companyMapper.insertSelective(company);
CompanyStaff staff = new CompanyStaff();
CompanyExample example2 = new CompanyExample();
example.createCriteria().andCreateUidEqualTo(createUid);
List<Company> list = companyMapper.selectByExample(example2);
staff.setCid(list.get(0).getId());
staff.setUid(createUid);
staff.setLevel(5);
companyStaffMapper.insertSelective(staff);
return true;
}
}
|
package com.androiddevios.simpletabs;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
public abstract class BaseFragment extends Fragment {
protected void addFragment(Fragment child) {
getParentFrag(this).beginTransaction()
.replace(R.id.child_container, child, "innerfrag")
.addToBackStack(null).commitAllowingStateLoss();
}
public boolean onBackPressed() {
if (getChildFragmentManager().getBackStackEntryCount() > 1) {
getChildFragmentManager().popBackStack();
return true;
}
return false;
}
public FragmentManager getParentFrag(Fragment frag) {
Fragment f = frag.getParentFragment();
if (f != null) {
return getParentFrag(f);
} else
return frag.getChildFragmentManager();
}
}
|
package br.com.exercicios;
public class Produtos {
private String nomeProduto;
private String categoria;
private int qtdEstoque;
public Produtos(String nomeProduto, String categoria, int qtdEstoque) {
super();
this.nomeProduto = nomeProduto;
this.categoria = categoria;
this.qtdEstoque = qtdEstoque;
}
public String getNomeProduto() {
return nomeProduto;
}
public void setNomeProduto(String nomeProduto) {
this.nomeProduto = nomeProduto;
}
public String getCategoria() {
return categoria;
}
public void setCategoria(String categoria) {
this.categoria = categoria;
}
public int getQtdEstoque() {
return qtdEstoque;
}
public void setQtdEstoque(int qtdEstoque) {
this.qtdEstoque = qtdEstoque;
}
public void adiconarProduto(String nome, String categoria, int qtdEstoque){
}
public void removerProduto(String nome) {
}
}
|
package Model;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.persistence.CascadeType;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/*
* 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.
*/
/**
*
* @author Niklas
* Useless class, not used in this project remnant of a long gone age of primtive project planning
*
*
*/
@XmlRootElement
public class Board {
private long id;
private String name;
private Map<Long,Note> openTasks;
private Map<Long,Person> personMap;
public Board() {
this.id = 0L;
openTasks = new HashMap<Long,Note>();
personMap = new HashMap<Long,Person>();
}
@XmlElement
@Id
@GeneratedValue
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
@XmlElement
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@XmlElement
@OneToMany(targetEntity = Note.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
public Map<Long, Note> getOpenTasks() {
return openTasks;
}
public void setOpenTasks(Map<Long, Note> openTasks) {
this.openTasks = openTasks;
}
@XmlElement
@OneToMany(targetEntity = Person.class, fetch = FetchType.EAGER, cascade = CascadeType.ALL)
public Map<Long, Person> getPersonMap() {
return personMap;
}
public void setPersonMap(Map<Long, Person> personMap) {
this.personMap = personMap;
}
/**
Adds note in parameter to Open Note List.
*/
public void addNote(long noteID,Note note){
openTasks.put(noteID,note);
}
/**
* edits the note and changes heading and content to values given in the parameter.
*
*
* @param noteID
* @param noteHeading
* @param noteContent
*/
public void editNote(long noteID,String noteHeading,String noteContent){
Note noteToEdit = getOpenTasks().get(noteID);
noteToEdit.setHeading(noteHeading);
noteToEdit.setContent(noteContent);
}
public void editNote(long personID,long noteID,String noteHeading,String noteContent){
Note noteToEdit = getPersonMap().get(personID).getPersonalNotes().get(noteID);
noteToEdit.setHeading(noteHeading);
noteToEdit.setContent(noteContent);
}
public void assignNote(long personID,long noteID){
Note noteToEdit = getOpenTasks().get(noteID);
getPersonMap().get(personID).getPersonalNotes().put(noteID,noteToEdit);
getOpenTasks().remove(noteID);
}
}
|
package com.shift.timer.di.components;
import com.shift.timer.di.OrderGuidePresenterModule;
import com.shift.timer.di.scope.FragmentScoped;
import com.shift.timer.ui.settingfragments.AdditionalHoursSettingFragment;
import com.shift.timer.ui.settingfragments.BreaksSettingFragment;
import com.shift.timer.ui.CompletedShiftFragment;
import com.shift.timer.ui.CurrentShiftFragment;
import com.shift.timer.ui.EditShiftFragment;
import com.shift.timer.ui.settingfragments.HourlyPaymentSettingFragment;
import com.shift.timer.ui.SettingsFragment;
import com.shift.timer.ui.settingfragments.MonthlyCalculationCycleFragment;
import com.shift.timer.ui.settingfragments.NotifyEndOfShiftSettingFragment;
import com.shift.timer.ui.settingfragments.RatePerDaySettingFragment;
import com.shift.timer.ui.settingfragments.TravelExpensesSettingFragment;
import com.shift.timer.ui.workplace.NoAdditionalWorkplacesDialog;
import dagger.Component;
/**
* Created by roy on 5/31/2017.
*/
@FragmentScoped
@Component(dependencies = NetComponent.class, modules = OrderGuidePresenterModule.class)
public abstract class OrderGuideComponent {
public abstract void inject(CurrentShiftFragment fragment);
public abstract void inject(EditShiftFragment fragment);
public abstract void inject(SettingsFragment fragment);
public abstract void inject(CompletedShiftFragment fragment);
public abstract void inject(HourlyPaymentSettingFragment fragment);
public abstract void inject(AdditionalHoursSettingFragment fragment);
public abstract void inject(TravelExpensesSettingFragment fragment);
public abstract void inject(BreaksSettingFragment fragment);
public abstract void inject(MonthlyCalculationCycleFragment fragment);
public abstract void inject(RatePerDaySettingFragment fragment);
public abstract void inject(NotifyEndOfShiftSettingFragment fragment);
public abstract void inject(NoAdditionalWorkplacesDialog dialog);
}
|
package be.pxl.ja.week4.oefening2;
import java.util.ArrayList;
import java.util.function.Predicate;
public class GameBrowser {
private GameCollection gameCollection;
public GameBrowser(GameCollection gameCollection) {
this.gameCollection = gameCollection;
}
public ArrayList<VideoGame> showGamesForSearch(String search) {
return gameCollection.selectGames(new Predicate<VideoGame>() {
@Override
public boolean test(VideoGame videoGame) {
if (videoGame.getName().toUpperCase().contains(search.toUpperCase())) {
return true;
}
return false;
}
});
}
public ArrayList<VideoGame> showFreeGames() {
Predicate<VideoGame> freeGamesFilter = v -> (v.getPrice() == 0.0);
return gameCollection.selectGames(freeGamesFilter);
}
public ArrayList<VideoGame> showGamesInGenre(String genre) {
Predicate<VideoGame> genreFilter = v -> (v.getGenres().contains(genre));
return gameCollection.selectGames(genreFilter);
}
}
|
package kyle.game.besiege.title;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.Table;
import kyle.game.besiege.WarchiefGame;
import kyle.game.besiege.battle.QuickBattleTable;
import kyle.game.besiege.battle.Simulation;
import kyle.game.besiege.party.ClickListenerWithHover;
public class QuickBattleScreen implements Screen {
private WarchiefGame main;
private Stage stage;
private MainMenuScreen mainMenuScreen;
private MenuBackground menuBackground;
private Table mainTable;
private QuickBattleTable quickBattleTable;
private Label start;
private Label back;
public QuickBattleScreen(WarchiefGame main, MainMenuScreen mainMenuScreen, MenuBackground menuBackground) {
this.main = main;
this.mainMenuScreen = mainMenuScreen;
this.menuBackground = menuBackground;
stage = new Stage();
stage.addActor(menuBackground);
menuBackground.drawWithTint(true);
mainTable = new Table();
stage.addActor(mainTable);
mainTable.setFillParent(true);
quickBattleTable = new QuickBattleTable();
mainTable.add(quickBattleTable).padBottom(60).colspan(2);
mainTable.row();
start = new Label("S T A R T", MainMenuScreen.styleButtons);
start.addListener(new ClickListenerWithHover(start) {
@Override
public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
startBattle();
}
});
mainTable.add(start).padRight(60);
back = new Label("B A C K", MainMenuScreen.styleButtons);
back.addListener(new ClickListenerWithHover(back) {
@Override
public void touchUp(InputEvent event, float x, float y, int pointer, int button) {
returnToMain();
}
});
mainTable.add(back);
mainTable.row();
}
public void startBattle() {
System.out.println("starting bqttle");
// Launch a new battle, with specified options.
Simulation simulation = new Simulation(quickBattleTable.getCurrentOptions(), this);
main.setScreen(simulation.getMapScreen()); // eventually make mainMenu
}
@Override
public void render(float delta) {
stage.act(delta);
Gdx.gl.glClearColor(.1f,.1f,.1f,0);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.draw();
// Table.drawDebug(stage);
}
@Override
public void resize(int width, int height) {
WarchiefGame.HEIGHT = height;
WarchiefGame.WIDTH = width;
mainTable.setWidth(width);
mainTable.setHeight(height);
// lowerTable.setWidth(width);
// lowerTable.setHeight(height/2);
menuBackground.resize(width, height);
// topTable.getCells().get(1).padLeft(width-WIDTH).padRight(SEPARATE);
// topTable.getCells().get(2).padRight(width-WIDTH).padLeft(SEPARATE);
// stage.setViewport(WarchiefGame.WIDTH, WarchiefGame.HEIGHT, false);
}
@Override
public void show() {
Gdx.input.setInputProcessor(stage);
}
@Override
public void hide() {
}
@Override
public void pause() {
}
@Override
public void resume() {
}
@Override
public void dispose() {
}
public void returnToThis() {
main.setScreen(this);
stage.clear();
stage.addActor(menuBackground);
stage.addActor(mainTable);
menuBackground.drawWithTint(true);
}
public void returnToMain() {
main.setScreen(mainMenuScreen);
mainMenuScreen.returnFromOtherPanel(false);
}
}
|
package com.bridgelabz.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;
public class PreparedStatementPractice {
static Scanner scanner = new Scanner(System.in);
static int choice = 0;
public static void main(String[] args) {
do {
System.out.println("**********************Menu**********************");
System.out.println("1)Create Table in DataBase");
System.out.println("2)Insert employee details into table");
System.out.println("3)Update emplyoee in table");
System.out.println("4)Delete employee from table");
System.out.println("5)Display employees Details");
System.out.println("6)Multiple Insert into table");
System.out.println("7)Exit");
System.out.println("*************************************************");
System.out.println("Enter Your choice:");
choice = scanner.nextInt();
switch (choice) {
case 1:
createTable();
break;
case 2:
insert();
break;
case 3:
update();
break;
case 4:
delete();
break;
case 5:
display();
break;
case 6:
multipleInsert();
break;
default:
break;
}
} while (choice != 9);
scanner.close();
}
private static void display() {
Connection connection = null;
PreparedStatement preparedStatement = null;
String selectQuery = "select * from students";
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/user", "root", "root");
preparedStatement = connection.prepareStatement(selectQuery);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
System.out.println("Id=" + resultSet.getInt(1) + " Name=" + resultSet.getString(2) + " Age="
+ resultSet.getInt(3) + " Course=" + resultSet.getString(4));
}
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
private static void delete() {
int result = 0;
Connection connection = null;
PreparedStatement preparedStatement = null;
System.out.println("Enter id of user to be deleted");
int id = scanner.nextInt();
String deleteQuery = "delete from students where id=?";
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/user", "root", "root");
preparedStatement = connection.prepareStatement(deleteQuery);
preparedStatement.setInt(1, id);
result = preparedStatement.executeUpdate();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
System.out.println(result + " Employee with id=" + id + " deleted!!");
}
private static void update() {
Connection connection = null;
int result = 0;
PreparedStatement preparedStatement = null;
System.out.println("Enter Name to be replaced");
String replaceName = scanner.next();
System.out.println("Enter Name from where to replace");
String name = scanner.next();
String updatequery = "update students set name=? where name=?";
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/user", "root", "root");
preparedStatement = connection.prepareStatement(updatequery);
preparedStatement.setString(1, replaceName);
preparedStatement.setString(2, name);
result = preparedStatement.executeUpdate();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
System.out.println(result + " User Updated!!!");
}
private static void multipleInsert() {
Connection connection = null;
PreparedStatement preparedStatement = null;
String sql = "insert into students(name,age,course) values(?,?,?)";
try {
System.out.println("Enter no of column");
int rows = scanner.nextInt();
for (int i = 0; i < rows; i++) {
System.out.println("Enter Name:");
String name = scanner.next();
System.out.println("Enter Age:");
int age = scanner.nextInt();
System.out.println("Enter Course:");
String course = scanner.next();
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/user", "root", "root");
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, name);
preparedStatement.setInt(2, age);
preparedStatement.setString(3, course);
int result = preparedStatement.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
private static void insert() {
Connection connection = null;
PreparedStatement preparedStatement = null;
System.out.println("Enter Name:");
String name = scanner.next();
System.out.println("Enter Age:");
int age = scanner.nextInt();
System.out.println("Enter Course:");
String course = scanner.next();
String sql = "insert into students(name,age,course) values(?,?,?)";
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/user", "root", "root");
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1, name);
preparedStatement.setInt(2, age);
preparedStatement.setString(3, course);
int result = preparedStatement.executeUpdate();
System.out.println(result + " row inserted successfully");
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
private static void createTable() {
Connection connection = null;
PreparedStatement preparedStatement = null;
String createQuery = "create table students(id int(4) auto_increment primary key,name varchar(20),age int(10),course int(4))";
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/user", "root", "root");
preparedStatement = connection.prepareStatement(createQuery);
preparedStatement.execute();
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
} finally {
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
|
// assignment 8
// pair p134
// Singh, Bhavneet
// singhb
// Wang, Shiyu
// shiyu
// This class represents a node
class Node {
String data;
Node next;
Node prev;
public Node(String data, Node next, Node prev) {
this.data = data;
this.next = next;
this.prev = prev;
}
/*TEMPELATE
* FIELDS:
* this.data.......data
* this.next.......node
*
* METHODS:
* this.addNext(Node)....................void
* this.addPrev(Node)....................void
* this.isSentinel()..................Boolean
* this.size()............................int
* this.removeFromHead(Sentinel).........void
* this.insertSorted(String).............void
* this.removeFromTail(String, Sentinel).void
* this.removeSorted(String).............void
*
* METHODS FOR FIELDS:
* this.prev.isSentinel()................void
* this.prev.size().......................int
* this.prev.addNext(Node)...............void
* this.prev.insertSorted(s).............void
* this.prev.removeSorted(s).............void
*/
//EFFECT
//change next into given node.
void addNext(Node node) {
this.next = node;
}
//EFFECT
//change prev into given node.
void addPrev(Node node) {
this.prev = node;
}
//determine whether it is this a Sentinel
public boolean isSentinel() {
return false;
}
//counts the number of nodes in a list Deque
public int size() {
if (this.prev.isSentinel())
return 1;
else return 1 + this.prev.size();
}
//EFFECT
//remove the first node of the list
void removeFromHead(Sentinel sent) {
this.prev = sent;
}
//EFFECT
//insert the node with given data into right place of sorted list
void insertSorted(String s) {
if (this.prev.isSentinel() ||
(this.prev.data.compareTo(s) <= 0))
{ this.prev.addNext(new Node(s, this, this.prev));
this.prev = this.prev.next; }
else this.prev.insertSorted(s);
}
//EFFECT
//remove the last node of the list
void removeFromTail(Sentinel sent) {
this.next = sent;
}
//EFFECT
//remove the node with given data
public void removeSorted(String s) {
if (this.data.equals(s))
{ this.prev.next = this.next;
this.next.prev = this.prev; }
else if (this.prev.isSentinel())
throw new RuntimeException("No such String in the list");
else
this.prev.removeSorted(s);
}
}
|
package com.tencent.mm.plugin.setting.ui.setting;
import com.tencent.mm.s.a.a;
import com.tencent.mm.storage.aa;
class SettingsUI$1 implements a {
final /* synthetic */ SettingsUI mUx;
SettingsUI$1(SettingsUI settingsUI) {
this.mUx = settingsUI;
}
public final void gl(int i) {
if (i == 262145 || i == 262157 || i == 262158) {
SettingsUI.a(this.mUx);
}
}
public final void gm(int i) {
}
public final void b(aa.a aVar) {
if (aVar != null && aVar == aa.a.sZC) {
SettingsUI.b(this.mUx);
}
}
}
|
package com.projet3.library_webservice.library_webservice_service;
import com.projet3.library_webservice.library_webservice_business.interfaces.BookManager;
import com.projet3.library_webservice.library_webservice_business.interfaces.BookingManager;
public abstract class AbstractBookService {
protected static BookManager bookManager;
protected static BookingManager bookingManager;
public static void setManagers(BookingManager bookingManager, BookManager bookManager) {
AbstractBookService.bookingManager = bookingManager;
AbstractBookService.bookManager = bookManager;
}
}
|
package com.company;
import java.util.Scanner;
public class Ninth {
private static final Scanner input = new Scanner(System.in);
public static void main(String[] args) {
long numberForCheck = input.nextInt();
long s = 0;
long sn = 1;
System.out.println("0\n1");
for (long i = 2; i <= numberForCheck; i++) {
if (i % 2 == 0) {
s += sn;
System.out.println(s);
} else {
sn += s;
System.out.println(sn);
}
}
}
}
|
package com.lucky.watisrain;
import com.lucky.watisrain.backend.Util;
import com.lucky.watisrain.map.MapView;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.util.Log;
public class Global {
/*
* There are two maps in the system: map_full and map_downsized. To convert from
* map_full to map_downsized:
* (x,y) -> ((x-611)*0.8156, (y-773)*0.8156)
*
* To convert from map_downsized to map_full:
* (x,y) -> ((x/0.8156)+611, (y/0.8156)+773)
*/
public static final float MAP_WIDTH = 2048.0f;
public static final float MAP_HEIGHT = 964.0f;
public static final float MAP_ADJUST_X = 611f;
public static final float MAP_ADJUST_Y = 773f;
public static final float MAP_ADJUST_SCALING = 0.8156f;
public static void println(Object s){
Log.d("DEBUG_MSG", s.toString());
}
static String[] pathing_choices = new String[]{"None","Within reason","At any cost"};
static int pathing_selected = 1;
/**
* Show the settings dialog (to select pathing mode)
* Automatically recalculate the route when settings change.
*/
public static void showSettings(Context context, final MapView mapview){
AlertDialog.Builder db = new AlertDialog.Builder(context);
db.setTitle("Prefer indoors:");
db.setSingleChoiceItems(pathing_choices, pathing_selected, new OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// no change
if(which == pathing_selected) return;
pathing_selected = which;
switch(which){
case 0:
Util.GLOBAL_PATHING_WEIGHT = 1.0;
break;
case 1:
Util.GLOBAL_PATHING_WEIGHT = 3.0;
break;
case 2:
Util.GLOBAL_PATHING_WEIGHT = 100.0;
break;
}
mapview.recalculateRoute();
}
});
db.setPositiveButton("OK", null);
db.create().show();
}
}
|
package leetcode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* @Author: Mr.M
* @Date: 2019-02-27 20:49
* @Description: https://leetcode-cn.com/problems/implement-trie-prefix-tree/
**/
// 依据数组进行的实现,好处是执行时间短,占用空间小,但是数组的大小仅为26只能存放26个小写字母不能扩展
class Trie {
/**
* Initialize your data structure here.
*/
private TrieNode root;
public Trie() {
root = new TrieNode();
}
/**
* Inserts a word into the trie.
*/
public void insert(String word) {
TrieNode ws = root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if (ws.children[c - 'a'] == null) {
ws.children[c - 'a'] = new TrieNode(c);
}
ws = ws.children[c - 'a'];
}
ws.isWorld = true;
}
/**
* Returns if the word is in the trie.
*/
public boolean search(String word) {
TrieNode ws = root;
for (int i = 0; i < word.length(); i++) {
char c = word.charAt(i);
if (ws.children[c - 'a'] == null) {
return false;
}
ws = ws.children[c - 'a'];
}
return ws.isWorld;
}
/**
* Returns if there is any word in the trie that starts with the given prefix.
*/
public boolean startsWith(String prefix) {
TrieNode ws = root;
for (int i = 0; i < prefix.length(); i++) {
char c = prefix.charAt(i);
if (ws.children[c - 'a'] == null) {
return false;
}
ws = ws.children[c - 'a'];
}
return true;
}
}
class TrieNode {
private char val;
boolean isWorld;
TrieNode[] children = new TrieNode[26];
TrieNode() {
}
TrieNode(char c) {
TrieNode node = new TrieNode();
node.val = c;
}
}
// 依据Map进行的实现,执行时间长,占用空间大,但是可能任意输入字符,扩展能力强
class Trie1 {
static HashMap<Character, HashMap> root;
/**
* Initialize your data structure here.
*/
// private TrieNode1 root;
public Trie1() {
root = new HashMap<>();
}
/**
* Inserts a word into the trie.
*/
public void insert(String word) {
HashMap<Character, HashMap> ws = root;
for(char c : word.toCharArray()){
if(!ws.containsKey(c)){
ws.put(c,new HashMap());
}
ws = ws.get(c);
}
ws.put('#',new HashMap());
}
/**
* Returns if the word is in the trie.
*/
public boolean search(String word) {
HashMap<Character, HashMap> ws = root;
for(char c : word.toCharArray()){
if(!ws.containsKey(c)){
return false;
}
ws = ws.get(c);
}
return ws.containsKey('#');
}
/**
* Returns if there is any word in the trie that starts with the given prefix.
*/
public boolean startsWith(String prefix) {
HashMap<Character, HashMap> ws = root;
for(char c : prefix.toCharArray()){
if(!ws.containsKey(c)){
return false;
}
ws = ws.get(c);
}
return true;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.